首先,确保将您的 animator 定义为一个属性,而不仅仅是一个局部变量(我倾向于使用animator
它的名称,以避免与@dynamic
关键字混淆):
@property (strong, nonatomic) UIDynamicAnimator *animator;
然后实例化动画师:
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.scrollView];
并添加重力:
UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[viewToAnimate]];
[self.animator addBehavior:gravityBehavior];
如果您希望它们在contentSize
到达滚动视图的底部时停止,则不能使用典型translatesReferenceBoundsIntoBoundary
设置。您必须自己制作一条路径,例如:
UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[viewToAnimate]];
CGRect contentSizeRect = {CGPointZero, self.scrollView.contentSize};
UIBezierPath *path = [UIBezierPath bezierPathWithRect:contentSizeRect];
[collision addBoundaryWithIdentifier:@"contentSize" forPath:path];
[self.animator addBehavior:collision];
或者,如果您希望它们飞离滚动视图,您可能希望在它们不再与contentSize
滚动视图相交时将它们移除:
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[viewToAnimate]];
UIGravityBehavior __weak *weakGravity = gravity;
CGRect contentSizeRect = {CGPointZero, self.scrollView.contentSize};
gravity.action = ^{
if (!CGRectIntersectsRect(contentSizeRect, viewToAnimate.frame)) {
NSLog(@"removing view");
[viewToAnimate removeFromSuperview];
[self.animator removeBehavior:weakGravity];
}
};
[self.animator addBehavior:gravity];