This is part 2 of the animations post. In this post, we will look at how to add special animations to views. Like when you slide from the bottom of an iPhone and the menu appears with a small bounce.
Add UIDynamicItems (usually UIViews) to the UIDynamicBehaviors.
1
2
3
4
5
6
letitem1:UIDynamicItem=...// usually a UIViewletitem2:UIDynamicItem=...// usually a UIViewgravity.addItem(item1)collider.addItem(item1)gravity.addItem(item2)
UIDynamicItem
The UIDynamicItem protocol looks like this. UIView implements this protocol and if you change center or transform while the animator is running, you must call this method in UIDynamicAnimator: func updateItemUsingCurrentState(item: DynamicItem)`
varcollisionMode:UICollisionBehaviorMode// .Items, .Boundaries, .Everything// with .Items, any items you add to a UICollisionBehavior will bounce off of each other// with .Boundaries, then you add UIBezierPath boundaries for items to bounce off offuncaddBoundaryWithIdentifier(identifier:NSCopying,forPath:UIBezierPath)funcremoveBoundaryWithIdentifier(identifier:NSCopying)vartranslatesReferenceBoundsIntoBoundary:Bool// referencesView's edges
classDropBlockViewController:UIViewController{@IBOutletweakvargameView:UIView!vardropsPerRow=10vardropSize:CGSize{letsize=gameView.bounds.size.width/CGFloat(dropsPerRow)returnCGSize(width:size,height:size)}letdropBehavior=DropItBehavior()lazyvaranimator:UIDynamicAnimator={// set to gameView in viewDidLoad because it has to set OutletreturnUIDynamicAnimator(referenceView:self.gameView)}()@IBActionfuncdrop(sender:UITapGestureRecognizer){drop()}overridefuncviewDidLoad(){super.viewDidLoad()animator.addBehavior(dropBehavior)}funcdrop(){varframe=CGRect(origin:CGPointZero,size:dropSize)frame.origin.x=CGFloat.random(dropsPerRow)*dropSize.widthletdropView=UIView(frame:frame)dropView.backgroundColor=UIColor.randomdropBehavior.addDrop(dropView)}}privateextensionCGFloat{staticfuncrandom(max:Int)->CGFloat{returnCGfloat(arc4random()%UInt32(max))}}