[iOS开发] UIKit Dynamics


关于 UIKit Dynamics 的中译名,我与许多开发者有过讨论,有动力、动力模型、动态等译法。但我认为译为力学更为贴切,希望文中出现的力学知识能让你认同我的看法。

http://www.cocoachina.com/applenews/devnews/2013/1226/7614.html

简单的重力影响view,使之垂直降落,在触底后有一个轻微的弹起,然后再落下

 1 #import "MainViewController.h"
 2 
 3 @interface MainViewController ()
 4 @property(nonatomic,retain)UIDynamicAnimator *animator;
 5 @property(nonatomic,retain)UIGravityBehavior *gravity;
 6 @property(nonatomic,retain)UICollisionBehavior *collision;
 7 
 8 @end
 9 
10 @implementation MainViewController
11 
12 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
13 {
14     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
15     if (self) {
16         // Custom initialization
17     }
18     return self;
19 }
20 
21 - (void)viewDidLoad
22 {
23     [super viewDidLoad];
24     // Do any additional setup after loading the view.
25     UIView *square = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];
26     square.backgroundColor = [UIColor redColor];
27     [self.view addSubview:square];
28     
29     //会出现重力现象,上面创建的正方形会掉落下去
30     //UIDynamicAnimator 是 UIKit 物理引擎。这个类会记录你添加到引擎中的各种行为(比如重力),并且提供全局上下文。当你创建动画实例时,需要传入一个参考视图用于定义坐标系。
31     //UIGravityBehavior 把重力的行为抽象成模型,并且对一个或多个元素施加作用力,让你可以建立物理交互模型。当你创建一个行为实例的时候,你需要把它关联到一组元素上,一般是一组视图。这样你就能选择受该行为影响的元素,在这个例子中就是指受重力影响的元素
32     _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
33     _gravity = [[UIGravityBehavior alloc] initWithItems:@[square]];
34     [_animator addBehavior:_gravity];
35     
36     _collision = [[UICollisionBehavior alloc] initWithItems:@[square]];
37     _collision.translatesReferenceBoundsIntoBoundary = YES;//让UIDynamicAnimator以视图的bounds为边界
38     [_animator addBehavior:_collision];
39     
40     
41     
42 }
43 
44 - (void)didReceiveMemoryWarning
45 {
46     [super didReceiveMemoryWarning];
47     // Dispose of any resources that can be recreated.
48 }
49 
50 @end
原文地址:https://www.cnblogs.com/mo-shou/p/3535448.html