Created
March 8, 2014 21:42
-
-
Save irace/9439335 to your computer and use it in GitHub Desktop.
A draggable circle that snaps back into place when released, just like the "3kb" circle on http://moofx.mad4milk.net
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SnapViewController.m | |
// DynamicsExample | |
// | |
// Created by Bryan Irace on 3/8/14. | |
// Copyright (c) 2014 Bryan Irace. All rights reserved. | |
// | |
#import "SnapViewController.h" | |
static CGFloat const CircleWidth = 50; | |
static CGFloat const SnapDamping = 0.2; | |
@interface SnapViewController() | |
@property (nonatomic) UIView *circle; | |
@property (nonatomic) UIDynamicAnimator *animator; | |
@property (nonatomic) UISnapBehavior *snapBehavior; | |
@end | |
@implementation SnapViewController | |
#pragma mark - UIViewController | |
- (void)viewDidLoad { | |
[super viewDidLoad]; | |
self.circle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CircleWidth, CircleWidth)]; | |
self.circle.backgroundColor = [UIColor grayColor]; | |
self.circle.layer.cornerRadius = CGRectGetWidth(self.circle.frame)/2; | |
[self.view addSubview:self.circle]; | |
[self.circle addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]]; | |
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; | |
} | |
- (void)viewWillAppear:(BOOL)animated { | |
[super viewWillAppear:animated]; | |
self.circle.center = CGPointMake(CGRectGetWidth(self.view.bounds)/2, | |
CGRectGetHeight(self.view.bounds)/2); | |
self.snapBehavior = [[UISnapBehavior alloc] initWithItem:self.circle snapToPoint:self.circle.center]; | |
self.snapBehavior.damping = SnapDamping; | |
} | |
#pragma mark - Gestures | |
- (void)pan:(UIPanGestureRecognizer *)gestureRecognizer { | |
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) { | |
[self.animator removeBehavior:self.snapBehavior]; | |
} | |
else if (gestureRecognizer.state == UIGestureRecognizerStateChanged) { | |
self.circle.center = ^{ | |
CGPoint center = self.circle.center; | |
CGPoint translation = [gestureRecognizer translationInView:self.circle]; | |
center.x += translation.x; | |
center.y += translation.y; | |
[gestureRecognizer setTranslation:CGPointZero inView:self.circle]; | |
return center; | |
}(); | |
} | |
else if (gestureRecognizer.state == UIGestureRecognizerStateEnded || gestureRecognizer.state == UIGestureRecognizerStateCancelled) { | |
[self.animator addBehavior:self.snapBehavior]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment