1.8推行为UIPushBehavior
(一)碰撞行为UIPushBehavior作用
(二)常用属性和方法
// 根据指定的模型初始化一个推行为
- (instancetype)initWithItems:(NSArray<id <UIDynamicItem>> *)items mode:(UIPushBehaviorMode)mode;
// 添加一个动力学元素给推行为
- (void)addItem:(id <UIDynamicItem>)item;
// 移除一个动力学元素从推行为
- (void)removeItem:(id <UIDynamicItem>)item;
// 推行为包含的所有的动力学元素
@property (nonatomic, readonly, copy) NSArray<id <UIDynamicItem>> *items;
// 推行为的模型 持续推力还是瞬时推力
@property (nonatomic, readonly) UIPushBehaviorMode mode;
// 设置推行为的活跃状态 YES:活跃 NO:不活跃
@property (nonatomic, readwrite) BOOL active;
// 推力方向(弧度)
@property (readwrite, nonatomic) CGFloat angle;
// 推力大小
@property (readwrite, nonatomic) CGFloat magnitude;
// 推力方向(向量)
@property (readwrite, nonatomic) CGVector pushDirection;
// 同时设置方向和推力大小
- (void)setAngle:(CGFloat)angle magnitude:(CGFloat)magnitude;
示例代码:
@interface ViewController ()
@property (nonatomic, weak) UIView *redView;
@property (nonatomic, strong) UIDynamicAnimator *animator;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
self.redView = redView;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// 获取触摸对象
UITouch *t = touches.anyObject;
// 获取手指的坐标点
CGPoint p = [t locationInView:t.view];
// 1.创建动画者对象
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
// 2.创建行为
// UIPushBehaviorModeContinuous 持续推理(越来越快)
// UIPushBehaviorModeInstantaneous (瞬时推理)(越来越慢)
UIPushBehavior *push = [[UIPushBehavior alloc] initWithItems:@[self.redView] mode:UIPushBehaviorModeContinuous];
push.magnitude = 1;
// 计算手指到redView中心点的偏移量
CGFloat offsetX = p.x - self.redView.center.x;
CGFloat offsetY = p.y - self.redView.center.y;
// 设置手指到redView中心偏移量为推行为的向量方向
push.pushDirection = CGVectorMake(-offsetX, -offsetY);
// 设置推行为的活跃状态 YES:活跃 NO:不活跃
push.active = NO;
// 3.添加行为到动画者对象
[self.animator addBehavior:push];
// 添加一个碰撞
UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.redView]];
collision.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:collision];
}
@end