iOS7 UISnapBehavior

####iOS7 Programming Cookbook 第二章学习笔记 UIDynamicAnimator

#####Adding a Dynamic Snap Effect to Your UI Components

#####ViewController.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@interface ViewController ()
//方形view
@property (nonatomic, strong) UIView *squareView;
//动态动画师
@property (nonatomic, strong) UIDynamicAnimator *animator;
//提前的行为定义一个动态项的运动到指定点,结束与一个振荡的数量可以设置。
@property (nonatomic, strong) UISnapBehavior *snapBehavior;
@end

@implementation ViewController

//创建手势识别
- (void) createGestureRecognizer{
//创建并添加点击事件
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTap:)];
//点击事件添加到view
[self.view addGestureRecognizer:tap];

}

//创建小方块view
- (void) createSmallSquareView{
//创建小方块为80x80
self.squareView = [[UIView alloc] initWithFrame:
CGRectMake(0.0f, 0.0f, 80.0f, 80.0f)];
//小方块颜色
self.squareView.backgroundColor = [UIColor greenColor];
//初始剧中
self.squareView.center = self.view.center;
//添加到view
[self.view addSubview:self.squareView];
}

//创建动画和动态项目
- (void) createAnimatorAndBehaviors{
self.animator = [[UIDynamicAnimator alloc]
initWithReferenceView:self.view];//指定视图为self.view

//创建碰撞检测
UICollisionBehavior *collision = [[UICollisionBehavior alloc]
initWithItems:@[self.squareView]];
//基于系统,指定一个碰撞边界
collision.translatesReferenceBoundsIntoBoundary = YES;
//添加一个动态碰撞行为
[self.animator addBehavior:collision];
//创建提前运动到指定点item为self。方块view ,,
self.snapBehavior = [[UISnapBehavior alloc]
initWithItem:self.squareView
snapToPoint:self.squareView.center];
//阻尼设置为中等震荡
self.snapBehavior.damping = 0.5f;
//动画师添加提前运动
[self.animator addBehavior:self.snapBehavior];
}

- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];

//创建手势识别
[self createGestureRecognizer];
//创建小方块view
[self createSmallSquareView];
//创建动画和动态项目
[self createAnimatorAndBehaviors];
}

- (void) handleTap:(UITapGestureRecognizer *)paramTap{

//从方块中心和点击点得到角度
//点击点(CGPoint) $1 = (x=243, y=155)
CGPoint tapPoint = [paramTap locationInView:self.view];
//<UISnapBehavior: 0x8f50e90> <UIView: 0x8c63370; frame = (120 244; 80 80); layer = <CALayer: 0x8c4e0d0>> <--> {160, 284}
if (self.snapBehavior != nil){
[self.animator removeBehavior:self.snapBehavior];
}

self.snapBehavior = [[UISnapBehavior alloc] initWithItem:self.squareView
snapToPoint:tapPoint];
//中等震荡
self.snapBehavior.damping = 0.5f;
//动画师添加行为
[self.animator addBehavior:self.snapBehavior];
}

@end

Reference

坚持原创技术分享,您的支持将鼓励我继续创作!
0%