码迷,mamicode.com
首页 > 其他好文 > 详细

Adding Gravity to your UI Components

时间:2014-06-02 20:01:49      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:des   c   a   tar   color   int   

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 "WSYViewController.h"

 

@interface WSYViewController ()

@property (nonatomic,strong)UIView *squareView;

@property (nonatomic,strong)UIDynamicAnimator * animator;

@end

 

@implementation WSYViewController

 

 

- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

   

    //create our little square view add it to self.view

    self.squareView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];

   

    self.squareView.backgroundColor =[UIColor greenColor];

    self.squareView.center = self.view.center;

    [self.view addSubview:self.squareView];

   

    self.animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];

   

    UIGravityBehavior * gravity = [[UIGravityBehavior alloc]initWithItems:@[self.squareView]];

   

    [self.animator addBehavior:gravity];

}

 

 

@end

 

Now if you run your app, as soon as your view controller’s view appears on screen, you will see the colored view drop from the center of the screen all the way down and out of the screen.

Adding Gravity to your UI Components,布布扣,bubuko.com

Adding Gravity to your UI Components

标签:des   c   a   tar   color   int   

原文地址:http://www.cnblogs.com/ios-mark/p/3762734.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!