標籤:
(1)UIDynammic使用分三步:
——建立模擬器(順便定義模擬範圍)(可利用懶載入定義)
——建立模擬行為(順便添加模擬元素)
——把模擬行為 添加到 模擬器 中
(2)下面是結合重力行為和碰撞行為的例子
#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UIView *rectView;@property(nonatomic,strong) UIDynamicAnimator *ani;@property (weak, nonatomic) IBOutlet UIView *blueView;@end@implementation ViewController-(UIDynamicAnimator *)ani{ if (!_ani) { //建立模擬器(順便定義模擬範圍) _ani=[[UIDynamicAnimator alloc]initWithReferenceView:self.view]; } return _ani;}- (void)viewDidLoad { [super viewDidLoad];}//blueView只參與碰撞模擬,不參與重力下落的模擬-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ //建立模擬器(順便定義模擬範圍),在懶載入中 //UIDynamicAnimator *ani=[[UIDynamicAnimator alloc]initWithReferenceView:self.view]; //建立模擬行為(順便添加模擬元素) UIGravityBehavior *behave=[[UIGravityBehavior alloc]initWithItems:@[self.rectView]]; //按照向量來定義方向 behave.gravityDirection=CGVectorMake(1, 1); //按照角度定義方向// behave.angle=-M_PI_4; //定義重力加速度 behave.magnitude=1; //碰撞檢測,把模擬範圍設為邊界 UICollisionBehavior *collisionBehave=[[UICollisionBehavior alloc]initWithItems:@[self.rectView,self.blueView]]; collisionBehave.translatesReferenceBoundsIntoBoundary=YES; //模擬行為 添加到 模擬器 中 [self.ani addBehavior:behave]; [self.ani addBehavior:collisionBehave];}@end
——重力行為的3個重要屬性,兩個方向屬性gravityDirection和angle,一個加速度屬性magnitude。
——碰撞比較重要的屬性是有幾種定義邊界的方法。
如上面的translatesReferenceBoundsIntoBoundary屬性。還有其他兩種主要的:
//碰撞檢測,把模擬範圍設為邊界 UICollisionBehavior *collisionBehave=[[UICollisionBehavior alloc]initWithItems:@[self.rectView,self.blueView]]; collisionBehave.translatesReferenceBoundsIntoBoundary=YES; //添加一條左右傾斜的直線作為碰撞邊界 [collisionBehave addBoundaryWithIdentifier:@"line" fromPoint:CGPointMake(0, 300) toPoint:CGPointMake(320, 400)]; //添加一個圓做邊界 UIBezierPath *path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 320, 320)]; [collisionBehave addBoundaryWithIdentifier:@"circle" forPath:path];
(3)捕捉行為,主要屬性是減震屬性damping。
#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UIView *pinkView;@property(nonatomic,strong) UIDynamicAnimator *ani;@end@implementation ViewController-(UIDynamicAnimator *)ani{ if (_ani==nil) { _ani=[[UIDynamicAnimator alloc]initWithReferenceView:self.view]; } return _ani;}- (void)viewDidLoad { [super viewDidLoad];}-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch=[touches anyObject]; CGPoint point=[touch locationInView:touch.view]; //建立捕捉行為 UISnapBehavior *snap=[[UISnapBehavior alloc]initWithItem:self.pinkView snapToPoint:point]; //設定捕捉屬性 //減震設定,0~1,值越大,減震越好,震動幅度就小。 snap.damping=0.5; //刪除所有行為(以保證每次點擊都有效,否則第二次以後點擊,沒反應) [self.ani removeAllBehaviors]; //添加行為 [self.ani addBehavior:snap];}
(4)除以上3種行為之外,還有其他行為:
——UIPushBehavior:推動行為
——UIAttachmentBehavior:附著行為
——UIDynamicItemBehavior:動力元素行為
【iOS開發-112】UIDynamic物理類比介紹,如重力行為、碰撞行為、碰撞行為以及其他