Skip to content

Instantly share code, notes, and snippets.

@WestonHanners
Created January 23, 2014 17:56
Show Gist options
  • Save WestonHanners/8583496 to your computer and use it in GitHub Desktop.
Save WestonHanners/8583496 to your computer and use it in GitHub Desktop.
Modified Teehan+Lax UIDynamics Snippet.
-(void)setupContentViewControllerAnimatorProperties {
NSAssert(self.animator == nil, @"Animator is not nil – setupContentViewControllerAnimatorProperties likely called twice.");
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self];
self.animator.delegate = self;
UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[self.overlayView]];
// Need to create a boundary that lies to the left off of the right edge of the screen.
[collisionBehavior setTranslatesReferenceBoundsIntoBoundaryWithInsets:UIEdgeInsetsMake(0, -280, 0, 0)];
[self.animator addBehavior:collisionBehavior];
self.gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[self.overlayView]];
self.gravityBehavior.gravityDirection = CGVectorMake(1, 0);
[self.animator addBehavior:self.gravityBehavior];
self.pushBehavior = [[UIPushBehavior alloc] initWithItems:@[self.overlayView] mode:UIPushBehaviorModeInstantaneous];
self.pushBehavior.magnitude = 1.0f;
self.pushBehavior.angle = 0.0f;
[self.animator addBehavior:self.pushBehavior];
UIDynamicItemBehavior *itemBehaviour = [[UIDynamicItemBehavior alloc] initWithItems:@[self.overlayView]];
itemBehaviour.elasticity = 0.45f;
[self.animator addBehavior:itemBehaviour];
}
- (void)overlayWasPanned:(UIPanGestureRecognizer *)gestureRecognizer {
CGPoint location = [gestureRecognizer locationInView:self];
location.y = CGRectGetMidY(self.bounds);
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
[self.animator removeBehavior:self.gravityBehavior];
self.attachmentBehavior = [[UIAttachmentBehavior alloc] initWithItem:self.overlayView attachedToAnchor:location];
[self.animator addBehavior:self.attachmentBehavior];
}
else if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
self.attachmentBehavior.anchorPoint = location;
}
else if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
[self.animator removeBehavior:self.attachmentBehavior], self.attachmentBehavior = nil;
CGPoint velocity = [gestureRecognizer velocityInView:self];
if (velocity.x < 0) {
// Open menu
self.trayOpen = YES;
velocity.x = -20;
self.gravityBehavior.gravityDirection = CGVectorMake(-1, 0);
}
else {
// Close menu
self.trayOpen = NO;
velocity.x = 20;
self.gravityBehavior.gravityDirection = CGVectorMake(1, 0);
}
[self.animator addBehavior:self.gravityBehavior];
self.pushBehavior.pushDirection = CGVectorMake(velocity.x, 0);
self.pushBehavior.active = YES;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment