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
複製代碼
發佈了4 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章