#import "ViewController.h"
@interface ViewController ()
{
UIDynamicAnimator *_animator;
UIAttachmentBehavior *_attachment;
// 大虫子头部视图
UIView *_headerView;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 1. 实例化animator
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
// 2. 绘制所有的视图
CGFloatstartX =20;
CGFloatstartY =60;
CGFloatr =12;
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:9];
for(NSIntegeri =0; i <9; i++) {
UIView*view =nil;
if(i <8) {
view = [[UIViewalloc]initWithFrame:CGRectMake(startX + i *2* r, startY,2* r,2* r)];
[view.layersetCornerRadius:r];
view.backgroundColor= [UIColorblueColor];
}else{
view = [[UIViewalloc]initWithFrame:CGRectMake(startX + i *2* r, startY - r,4* r,4* r)];
[view.layersetCornerRadius:2* r];
view.backgroundColor = [UIColor greenColor];
}
[self.viewaddSubview:view];
[arrayMaddObject:view];
}
_headerView= arrayM[8];
// 3. 附加行为
for(NSIntegeri =0; i <8; i++) {
UIAttachmentBehavior*attachment = [[UIAttachmentBehavioralloc]initWithItem:arrayM[i]attachedToItem:arrayM[i +1]];
[_animatoraddBehavior:attachment];
}
// 4. 重力行为
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:arrayM];
[_animatoraddBehavior:gravity];
// 5. 碰撞行为
UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:arrayM];
collision.translatesReferenceBoundsIntoBoundary = YES;
[_animatoraddBehavior:collision];
// 6. 添加手势监听
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
[self.view addGestureRecognizer:pan];
}
#pragma mark- 手势拖动监听方法
- (void)panGesture:(UIPanGestureRecognizer *)sender
{
CGPointlocation = [senderlocationInView:self.view];
// 拖动头部
if (UIGestureRecognizerStateBegan == sender.state) {
// 1. 定义一个附加行为
_attachment = [[UIAttachmentBehavior alloc] initWithItem:_headerView attachedToAnchor:location];
[_animator addBehavior:_attachment];
}else if (UIGestureRecognizerStateChanged == sender.state) {
[_attachmentsetAnchorPoint:location];
}else if (UIGestureRecognizerStateEnded == sender.state) {
[_animator removeBehavior:_attachment];
}
}
@end