UISnapBehavior的简单使用

来源:互联网 发布:如何用备忘录编程 编辑:程序博客网 时间:2024/03/29 20:57



#import "ViewController.h"


@interface ViewController ()


@property (weak, nonatomic) UIImageView * imageView1;


@property (strong,nonatomic)UIDynamicAnimator * animator;


@property (strong,nonatomic)UISnapBehavior * snap;



@end


@implementation ViewController


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

  

  //UISnapBehavior

  [selfsetupSnapBehaviorTest:toucheswithEvent:event];

  

  

}


- (void)viewDidLoad {

  

  [superviewDidLoad];

  

  [selfsetupViews];

  

}


//setup  UISnapBehavior

- (void)setupSnapBehaviorTest:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

  

  CGPoint location = [touches.anyObjectlocationInView:self.view];

  

  _snap.snapPoint = location;

}



- (void)setupViews{

  

  UIImageView * imageView1 = [[UIImageViewalloc]init];

  imageView1.backgroundColor = [UIColorredColor];

  imageView1.frame = CGRectMake(50, 100, 100, 100);

  imageView1.layer.masksToBounds =YES;

  imageView1.layer.cornerRadius = imageView1.frame.size.width/2;

  imageView1.userInteractionEnabled =YES;

  _imageView1 = imageView1;

  [self.viewaddSubview:imageView1];

  

  

  

  /**

   UISnapBehavior是继承自UIDynamicBehaviorUIDynamicBehavior是继承自NSObject

   是一个吸附行为,

   */

  

  _snap = [[UISnapBehavioralloc]initWithItem:self.imageView1snapToPoint:imageView1.center];

  

  //default 0.5这个值越大,震动的幅度越小 是从0.01.0当时当它为负数时也震动,可以试试

  _snap.damping =0.1;

  

  //snap.snapPoint是你的这个吸附行为要吸附到哪个点上当改变这个值的时候会启动这个行为

  NSLog(@"point  %@",NSStringFromCGPoint(_snap.snapPoint));

//  _snap.snapPoint = self.view.center;

  

  

  NSLog(@"dynamicAnimator %@",_snap.dynamicAnimator);

  //这个animator为空这个是父累的UIDynamicAnimator,因为没有创建所以是空的,null

  

  [self.animatoraddBehavior:_snap];

  

  //加一个UICollisionBehavior就不会出现在屏幕外面只要一接触边界 就停止snap动画

  UICollisionBehavior * collision = [[UICollisionBehavioralloc]initWithItems:@[self.imageView1]];

  collision.translatesReferenceBoundsIntoBoundary =YES;

  [self.animatoraddBehavior:collision];

  

  

}

- (UIDynamicAnimator *)animator{

  

  if (_animator ==nil) {

    _animator = [[UIDynamicAnimatoralloc]initWithReferenceView:self.view];

  }

  return_animator;

  

}

@end


0 0
原创粉丝点击