按下按钮时,我有一个UIImageView在屏幕上运行。当按下按钮时,会更改UIImageView的UIImage,当按钮松开时,我将其更改为原始的UIImage。当图像变回时,它会快速回到图像开始的位置。
按下按钮时调用此Timer:
//This is the image that changes when the button is pressed.
imView.image = image2;
runTimer = [NSTimer scheduledTimerWithTimeInterval:0.04
target:self
selector:@selector(perform)
userInfo:nil
repeats:YES];
当按钮停止按住时调用此方法:
- (IBAction)stopPerform:(id)sender{
[runTimer invalidate];
//THIS IS WHAT SNAPS THE ANIMATION BACK:
//Without this the animation does not snap back
imView.image = image1;
}
- (void)performRight{
CGPoint point0 = imView.layer.position;
CGPoint point1 = { point0.x + 4, point0.y };
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position.x"];
anim.fromValue = @(point0.x);
anim.toValue = @(point1.x);
anim.duration = 0.2f;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
// First we update the model layer's property.
imView.layer.position = point1;
// Now we attach the animation.
[imView.layer addAnimation:anim forKey:@"position.x"];
}
我是否需要将图像更改添加到动画中?如果是这样的话?我真的很困惑。
答案 0 :(得分:0)
Core Animation使用不同的属性集来表示对象:
来自Core Animation Programming Guide:
模型图层树(或简称为“图层树”)是您的应用最常互动的图层。此树中的对象是存储任何动画的目标值的模型对象。无论何时更改图层的属性,都可以使用其中一个对象。
演示文稿树包含任何正在运行的动画的动态值。尽管图层树对象包含动画的目标值,但表示树中的对象会反映屏幕上显示的当前值。您永远不应该修改此树中的对象。相反,您可以使用这些对象来读取当前动画值,也许是为了从这些值开始创建新动画。
因此,当您为属性设置动画时,您将更改表示层,但是一旦完成动画,对象将恢复为其模型属性值。
解决此问题需要做的是使用[CAAnimation animationDidStop:finished:]
委托方法设置最终属性值以及您想要执行的任何其他操作。我想你可以用它来转储你正在使用的那个可怕的NSTimer
代码,而且世界的一小部分会好得多。