iOS開發(fā)拓展篇—UIDynamic(捕捉行為)
一、簡(jiǎn)介
可以讓物體迅速?zèng)_到某個(gè)位置(捕捉位置)终惑,捕捉到位置之后會(huì)帶有一定的震動(dòng)
UISnapBehavior的初始化
- (instancetype)initWithItem:(id <UIDynamicItem>)item snapToPoint:(CGPoint)point;
UISnapBehavior常見屬性
@property (nonatomic, assign) CGFloat damping;
用于減幅轩性、減震(取值范圍是0.0 ~ 1.0,值越大狠鸳,震動(dòng)幅度越写铡)
UISnapBehavior使用注意
如果要進(jìn)行連續(xù)的捕捉行為,需要先把前面的捕捉行為從物理仿真器中移除
二件舵、代碼說明
在storyboard中放一個(gè)view控件卸察,作為演示用的仿真元素。
代碼如下:
復(fù)制代碼
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 //創(chuàng)建物理仿真器铅祸,設(shè)置仿真范圍坑质,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 //獲取一個(gè)觸摸點(diǎn)
33 UITouch *touch=[touches anyObject];
34 CGPoint point=[touch locationInView:touch.view];
35
36 //1.創(chuàng)建捕捉行為
37 //需要傳入兩個(gè)參數(shù):一個(gè)物理仿真元素,一個(gè)捕捉點(diǎn)
38 UISnapBehavior *snap=[[UISnapBehavior alloc]initWithItem:self.blueView snapToPoint:point];
39 //設(shè)置防震系數(shù)(0~1临梗,數(shù)值越大涡扼,震動(dòng)的幅度越小)
40 snap.damping=arc4random_uniform(10)/10.0;
41
42 //2.執(zhí)行捕捉行為
43 //注意:這個(gè)控件只能用在一個(gè)仿真行為上盟庞,如果要擁有持續(xù)的仿真行為吃沪,那么需要把之前的所有仿真行為刪除
44 //刪除之前的所有仿真行為
45 [self.animator removeAllBehaviors];
46 [self.animator addBehavior:snap];
47 }
48
49 @end
復(fù)制代碼