直接上代码:
1 // 2 // YFAttachmentBehaviorViewController.m 3 // BigShow1949 4 // 5 // Created by apple on 16/8/25. 6 // Copyright © 2016年 BigShowCompany. All rights reserved. 7 // 8 9 #import "YFAttachmentBehaviorViewController.h" 10 11 @interface YFAttachmentBehaviorViewController () 12 13 @property (nonatomic, strong) UIView *square1; 14 @property(nonatomic,strong)UIDynamicAnimator *animator; 15 @property (nonatomic, strong) UIAttachmentBehavior *attachmentBehavior; 16 17 18 19 @end 20 21 @implementation YFAttachmentBehaviorViewController 22 23 - (void)viewDidLoad 24 { 25 [super viewDidLoad]; 26 27 self.view.backgroundColor = [UIColor whiteColor]; 28 29 // 创建一个正方形 30 self.square1 =[[UIView alloc] initWithFrame: CGRectMake(0.0f, 568-80, 80.0f, 80.0f)]; 31 self.square1.backgroundColor = [UIColor greenColor]; 32 self.square1.center = self.view.center; 33 [self.view addSubview:self.square1]; 34 35 36 self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; 37 38 UICollisionBehavior* collision = [[UICollisionBehavior alloc] initWithItems:@[self.square1]]; 39 collision.translatesReferenceBoundsIntoBoundary = YES; 40 41 UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[self.square1]]; 42 43 44 [self.animator addBehavior:collision]; 45 [self.animator addBehavior:gravity]; 46 47 48 // 视图手势 49 [self createGestureRecognizer]; 50 } 51 52 53 - (void)createGestureRecognizer{ 54 UIPanGestureRecognizer *tapGestureRecognizer = 55 [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; 56 [self.view addGestureRecognizer:tapGestureRecognizer]; 57 } 58 59 - (void)handleTap:(UIPanGestureRecognizer *)gesture{ 60 61 if (gesture.state == UIGestureRecognizerStateBegan){ 62 NSLog(@"----Began"); 63 64 CGPoint squareCenterPoint = CGPointMake(self.square1.center.x, self.square1.center.y - 100.0); 65 66 UIAttachmentBehavior* attachmentBehavior = [[UIAttachmentBehavior alloc] initWithItem:self.square1 attachedToAnchor:squareCenterPoint]; 67 68 self.attachmentBehavior = attachmentBehavior; 69 [self.animator addBehavior:attachmentBehavior]; 70 71 } else if ( gesture.state == UIGestureRecognizerStateChanged) { 72 NSLog(@"----Changed"); 73 [self.attachmentBehavior setAnchorPoint:[gesture locationInView:self.view]]; 74 75 } else if (gesture.state == UIGestureRecognizerStateEnded) { 76 NSLog(@"----Ended"); 77 [self.animator removeBehavior:self.attachmentBehavior]; 78 } 79 } 80 81 82 83 @end