標籤:
一、簡介
可以讓物體迅速衝到某個位置(捕捉位置),捕捉到位置之後會帶有一定的震動
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 @end15 16 @implementation YYViewController17 18 -(UIDynamicAnimator *)animator19 {20 if (_animator==nil) {21 //建立物理模擬器,設定模擬範圍,ReferenceView為參照視圖22 _animator=[[UIDynamicAnimator alloc]initWithReferenceView:self.view];23 }24 return _animator;25 }26 - (void)viewDidLoad27 {28 [super viewDidLoad];29 }30 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event31 {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
iOS開發拓展篇—UIDynamic(捕捉行為)