The critical issue is that your if
statements are not checking the state
property. It should be:
if (recognizer.state == UIGestureRecognizerStateBegan)
{
// began code here
}
else if (recognizer.state == UIGestureRecognizerStateEnded)
{
// ended code here
}
Also be aware that this gesture recognizer will only work if you have autolayout turned off. If you're using autolayout, you have to change the constraints.
If you forgive the stylistic observations, I might also be inclined to suggest:
use block-based animations;
not reference non-local variables if not needed (i.e. reference
recognizer.view
rather thanbloemen
), which makes it easier to reuse this handler for dragging and dropping of variousUIView
objects you choose to add this gesture to; anduse standard naming conventions, start method names with lowercase letter and follow the
verbNoun
convention.
None of this is critical and please use or disregard as you see fit, but this exhibits a few best practices:
- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
if (recognizer.state == UIGestureRecognizerStateBegan)
{
[UIView animateWithDuration:0.4
delay:0.0 // you had 0.1, but seems worthwhile to give immediate feedback
options:0
animations:^{
recognizer.view.alpha = 0.7f;
recognizer.view.transform = CGAffineTransformMakeScale(1.5,1.5);
}
completion:nil];
}
if (recognizer.state == UIGestureRecognizerStateEnded)
{
[UIView animateWithDuration:0.1
delay:0.0 // you had 0.1, but seems worthwhile to give immediate feedback
options:0
animations:^{
recognizer.view.alpha = 1.0f;
recognizer.view.transform = CGAffineTransformIdentity;
}
completion:nil];
}
}