Introducing UIKit Dynamics in iOS 7

UIKit Dynamics is a physics engine integrated into UIKit. It allows a developer to attach real-life behaviours to views such as gravity. In this tutorial we will create a view on which we will apply a gravity behaviour.

Open Xcode and create a new Single View Application. For product name, use iOS7UIKitDynamicsTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices.

First, let's create a view where we can attach some physics to later on. Open ViewController.m and add the following code to viewDidLoad

UIView *myView = [[UIView alloc] initWithFrame: CGRectMake(125,100,50,50)];
myView.backgroundColor = [UIColor redColor];

[self.view addSubview:myView];

In the interface section add the following properties

@property (nonatomic, strong) UIDynamicAnimator *animator;
@property (nonatomic, strong) UIGravityBehavior *gravity;
  • A dynamic animator is responsible for all the dynamic events that happens on the screen.
  • A gravity behavior applies gravity to its dynamic items. 

In viewDidLoad we will init our animator with our view and add some gravity behavior to our view.

self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
self.gravity = [[UIGravityBehavior alloc] initWithItems:@[myView]];

[self.animator addBehavior:self.gravity];

Build and Run, our view should be falling down because of the applied gravity. 

As you will notice, the view falls through the bottom of our screen, this is because we haven't defined a boundary. In the interface section, add the following property

@property (nonatomic, strong) UICollisionBehavior *collision;

The collision behavior allows the views to collide with each other and with the specified boundaries. at the end of viewDidLoad add the following lines 

self.collision = [[UICollisionBehavior alloc] initWithItems:@[myView]];
self.collision.translatesReferenceBoundsIntoBoundary = YES;

[self.animator addBehavior:self.collision];

The translatesReferenceBoundsIntoBoundary property sets the boundaries to the reference view, so our view will collide with the main view.

Build and Run, the View should collide with the bottom of the screen.

You can download the source code of the iOS7UIKitDynamicsTutorial at the ioscreator repository on github.