iOS開發拓展篇—UIDynamic(捕捉行為)
一、簡介
可以讓物體迅速沖到某個位置(捕捉位置),捕捉到位置之后會帶有一定的震動
UISnapBehavior的初始化
- (instancetype)initWithItem:(id <UIDynamicItem>)item snapToPoint:(CGPoint)point;
UISnapBehavior常見屬性
@property (nonatomic, assign) CGFloat damping;
用於減幅、減震(取值范圍是0.0 ~ 1.0,值越大,震動幅度越小)
UISnapBehavior使用注意
如果要進行連續的捕捉行為,需要先把前面的捕捉行為從物理仿真器中移除
二、代碼說明
在storyboard中放一個view控件,作為演示用的仿真元素。
代碼如下:
1 // 2 // YYViewController.m 3 // 13-捕捉行為 4 // 5 // Created by apple on 14-8-8. 6 // Copyright (c) 2014年 yangyong. All rights reserved. 7 // 8 9 #import "YYViewController.h" 10 11 @interface YYViewController () 12 @property (weak, nonatomic) IBOutlet UIView *blueView; 13 @property(nonatomic,strong)UIDynamicAnimator *animator; 14 @end 15 16 @implementation YYViewController 17 18 -(UIDynamicAnimator *)animator 19 { 20 if (_animator==nil) { 21 //創建物理仿真器,設置仿真范圍,ReferenceView為參照視圖 22 _animator=[[UIDynamicAnimator alloc]initWithReferenceView:self.view]; 23 } 24 return _animator; 25 } 26 - (void)viewDidLoad 27 { 28 [super viewDidLoad]; 29 } 30 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 31 { 32 //獲取一個觸摸點 33 UITouch *touch=[touches anyObject]; 34 CGPoint point=[touch locationInView:touch.view]; 35 36 //1.創建捕捉行為 37 //需要傳入兩個參數:一個物理仿真元素,一個捕捉點 38 UISnapBehavior *snap=[[UISnapBehavior alloc]initWithItem:self.blueView snapToPoint:point]; 39 //設置防震系數(0~1,數值越大,震動的幅度越小) 40 snap.damping=arc4random_uniform(10)/10.0; 41 42 //2.執行捕捉行為 43 //注意:這個控件只能用在一個仿真行為上,如果要擁有持續的仿真行為,那么需要把之前的所有仿真行為刪除 44 //刪除之前的所有仿真行為 45 [self.animator removeAllBehaviors]; 46 [self.animator addBehavior:snap]; 47 } 48 49 @end