When dealing with gravity, UIKit Dynamics does not conform to the boundaries of the screen. Although it is not visible, the food image continues to fall after it has passed the edge of the screen. It will continue to fall unless we set boundaries that will contain the image view. At the top of the file, create another instance variable:
UICollisionBehavior *collision;
Now in our viewDidLoad
method, add the following code below our gravity code:
collision = [[UICollisionBehavior alloc] initWithItems:@[self.foodImageView]]; collision.translatesReferenceBoundsIntoBoundary = YES; [animator addBehavior:collision];
Here we are creating an instance of a new class (which is a behavior), UICollisionBehavior
. Just like our gravity behavior, we associate this behavior with our food image view.
Rather than explicitly defining the coordinates for the boundary, we use the convenient translatesReferenceBoundsIntoBoundary
property on our collision behavior. By setting this property to...