O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.1. Adding Gravity to Your UI Components

Problem

You want your UI components to have gravity, so that if they are dragged up to the top of the screen, they will descend on their own. Combining this with the collision behavior that you will learn later, you can create UI components that fall from their current location until they collide with a path that you’ll specify.

Solution

Initialize an object of type UIGravityBehavior and add your UI components that need gravity to this object. After you are done, create an instance of UIDynamicAnimator, add your gravity behavior to the animator, and let the animator take care of the rest of the work for you.

Discussion

For the purpose of this recipe, we are going to create a simple colored square view in our single-view application and place that view at the center of the screen. We will then add gravity to that view and watch it fall from the center all the way down and eventually outside the bounds of the screen.

So let’s start by defining our animator and the view:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UIView *squareView;
@property (nonatomic, strong) UIDynamicAnimator *animator;
@end

@implementation ViewController

<# Rest of your view controller's code will go here #>

Next, we are going to create our little view, assign a color to it, and place it at the center of our view controller’s view. Then we will create an instance of the UIGravityBehavior class using its initWithItems: initializer. This ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required