Thursday, June 9, 2016

UI Dynamics

@interface ViewController ()

@property (strong, nonatomic) UIDynamicAnimator* animator;
@property (nonatomic) UIOffset offset;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIPanGestureRecognizer* pg = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(actionPanGesture:)];
    [self.imageView addGestureRecognizer:pg];
    self.imageView.userInteractionEnabled = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) actionPanGesture:(UIPanGestureRecognizer*)pg {
    CGPoint pInView = [pg locationInView:self.view];
    CGPoint pInSubView = [pg locationInView:pg.view];
    CGPoint center = CGPointMake(pg.view.bounds.size.width/2., pg.view.bounds.size.height/2.);
 
    CGPoint v = [pg velocityInView:self.view];
 
    if (pg.state == UIGestureRecognizerStateBegan) {
        self.offset = UIOffsetMake(pInSubView.x - center.x, pInSubView.y - center.y);
        NSLog(@"OffsetX: %f, OffsetY: %f", self.offset.horizontal, self.offset.vertical);
    }
    else if (pg.state == UIGestureRecognizerStateEnded) {
        self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
     
        NSLog(@"PushVX: %f, PushVY: %f", v.x, v.y);
        UIPushBehavior* push = [[UIPushBehavior alloc] initWithItems:@[pg.view] mode:UIPushBehaviorModeInstantaneous];
        [push setPushDirection:CGVectorMake(v.x/10.0, v.y/10.0)];
        [self.animator addBehavior:push];
     
        UIGravityBehavior* gravity = [[UIGravityBehavior alloc] initWithItems:@[pg.view]];
        [self.animator addBehavior:gravity];
    }
    else {
        if (self.animator) {
            self.attachBehavior.anchorPoint = pInView;
            return;
        }
        else {
            self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
        }
        UIGravityBehavior* gravity = [[UIGravityBehavior alloc] initWithItems:@[pg.view]];
        [self.animator addBehavior:gravity];
     
        UIAttachmentBehavior *attachment;
        attachment = [[UIAttachmentBehavior alloc] initWithItem:pg.view offsetFromCenter:self.offset attachedToAnchor:pInView];
        [attachment setLength:0];
        [attachment setFrequency:0];
        [attachment setDamping:5];
        [self.animator addBehavior:attachment];
     
    }
}
@end

No comments:

Post a Comment