Stats

33 Contributors: 3 Saturday, May 27, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

UIKit Dynamics

Introduction

UIKit Dynamics is a full real-world physics engine integrated into UIKit. It allows you to create interfaces that feel real by adding behaviors such as gravity, attachments, collision and forces. You define the physical traits that you would like your interface elements to adopt, and the dynamics engine takes care of the rest.

Remarks

An import thing to keep in mind when using UIKit Dynamics is views that are positioned by the animator cannot readily be positioned by other common iOS layout methods.

Newcomers to UIKit Dynamics often struggle with this important caveat. Placing constraints on a view that is also an item of a UIDynamicBehavior will likely cause confusion as a both the auto layout engine and the dynamic animator engine fight over the appropriate position. Similarly, attempting to set the frame directly of a view being controlled by the animator will typically result in jittery animation and unexpected placement. Adding a view as an item to a UIDynamicBehavior means that the animator will take on the responsibility of positioning a view and as such changes of view positions should be implemented through the animator.

A view's frame that is being updated by a dynamic animator can be set, but that should be immediately followed by messaging the animator to update the animator's internal model of the view hierarchy. For example, if I have UILabel, label that is an item of a UIGravityBehavior I can move it to the top of the screen to watch it fall again by saying:

Swift

label.frame = CGRect(x: 0.0, y: 0.0, width: label.intrinsicContentSize.width, height: label.intrinsicContentSize.height)
dynamicAnimator.updateItem(usingCurrentState: label)

Objective-C

self.label.frame = CGRectMake(0.0, 0.0, self.label.intrinsicContentSize.width, self.label.intrinsicContentSize.height);
[self.dynamicAnimator updateItemUsingCurrentState: self.label];

After which the animator will apply the gravity behavior from the label's new location.

Another common technique is to use UIDynamicBehaviors to position views. For example if positioning a view under a touch event is desired, creating a UIAttachmentBehavior and updating its anchorPoint in either touchesMoved or a UIGestureRecognizer's action is an effective strategy.

Related Examples