iOS UIKit Dynamics

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any iOS Question?