Reputation: 1
I am trying to implement UIDynamicAnimator
effects on a scrollView
with many elements. I couldn't find too much information about it anywhere ,so i just need some starting point.
So i have my scrollView
, with many UIViews
in it. i want to make any kind of animation to its "subViews" while scrolling.
Tried that-nothing happens .
//DYNAMICS ANIMATIONS
UIDynamicAnimator *dynamic=[[UIDynamicAnimator alloc] initWithReferenceView:scroller];
UIGravityBehavior *gravityBeahvior = [[UIGravityBehavior alloc] initWithItems:mainCellsArray];
[dynamic addBehavior:gravityBeahvior];
When mainCellsArray
holds all the "subViews" of the scroller .
EDIT:
I have a strong property
for the dynamic
.
The array holds my costume classes pointers , that each class is a UIView
subclass, and they all the scroller children's.
Upvotes: 2
Views: 1065
Reputation: 437622
First, make sure you define your animator as a property, not solely as a local variable (and I tend to use animator
for the name of that, to avoid confusion with the @dynamic
keyword):
@property (strong, nonatomic) UIDynamicAnimator *animator;
Then instantiate the animator:
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.scrollView];
And add the gravity:
UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[viewToAnimate]];
[self.animator addBehavior:gravityBehavior];
If you want them to stop when they hit the bottom of the contentSize
of the scroll view, you can't use the typical translatesReferenceBoundsIntoBoundary
setting. You have to make a path yourself, e.g. something like:
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];
Or, if you want them to fly off the scroll view, you probably want to remove them when they no longer intersect the contentSize
of the scroll view:
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];
Upvotes: 2