我想在使用将它拖到屏幕上其他地方的CALayer
a 后将其动画化回其初始位置 。UIPanGestureRecognizer
这是我所拥有的:
@interface ViewController () {
CGPoint defaultButtonPosition;
CGPoint lastPosition;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
defaultButtonPosition = _roundShape.layer.position;
self.view.backgroundColor = [UIColor blackColor];
[_roundShape displayShape];
[self.view.layer addSublayer:_roundShape.layer];
}
//code so I can drag my CALayer
- (IBAction)dragShape:(UIPanGestureRecognizer *)sender
{
CGPoint translation = [sender translationInView:self.view];
sender.view.center = CGPointMake(sender.view.center.x + translation.x, sender.view.center.y + translation.y);
[sender setTranslation:CGPointMake(0, 0) inView:self.view];
lastPosition = sender.view.center;
if (sender.state == UIGestureRecognizerStateEnded) {
NSLog(@"Pan ended");
[self animateBackToOriginalPosition];
_roundShape.center = lastPosition;
}
}
- (void)animateBackToOriginalPosition
{
CABasicAnimation *moveBackToOriginalPosition = [CABasicAnimation animationWithKeyPath:@"position"];
moveBackToOriginalPosition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
moveBackToOriginalPosition.fromValue = [NSValue valueWithCGPoint:lastPosition];
moveBackToOriginalPosition.toValue = [NSValue valueWithCGPoint:defaultPosition];
moveBackToOriginalPosition.repeatCount = 0;
moveBackToOriginalPosition.duration = 1.0;
[_roundShape.layer addAnimation:moveBackToOriginalPosition forKey:@"position"];
}
这段代码产生的动画与我想要的相差甚远。当我放开正在拖动的 CALayer 时,它突然消失并从看似随机的位置动画到 lastPosition 而不是我设置的 toValue (=defaultPosition)。之后,CALayer 不再可见。
似乎当我拖动 CALayer 时,位置属性并没有改变,因为 NSLog 总是告诉我它仍然处于默认位置。这就是我尝试使用的_roundShape.center = lastPosition;
原因,但这只会导致 CALayer 消失。没有这个,CALayer 会在屏幕上保持可见。
我希望我能很好地解释我的问题。我很想听听我在代码中犯了哪些新手错误。