我有一个 UIImageView,当按住按钮时它会在屏幕上运行。当按下按钮时,将更改 UIImageView 的 UIImage,当松开按钮时,我将其更改为其原始 UIImage。当图像变回原样时,它会恢复到图像开始的位置。
按下按钮时调用此计时器:
//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"];
}
我需要将图像的变化添加到动画中吗?如果是这样怎么办?我真的很困惑。
核心动画使用不同的属性集来表示一个对象:
From 核心动画编程指南:
模型层树(或简称为“层树”)是您的应用程序与之交互最多的层。此树中的对象是存储任何动画的目标值的模型对象。每当您更改图层的属性时,都会使用这些对象之一。
演示树包含任何正在运行的动画的飞行中值。图层树对象包含动画的目标值,而演示树中的对象反映屏幕上出现的当前值。您永远不应该修改此树中的对象。相反,您可以使用这些对象来读取当前动画值,也许可以从这些值开始创建一个新动画。
因此,当您对属性进行动画处理时,您会更改表示层,但动画完成后,对象将恢复为其模型属性值。
您需要做的就是使用[CAAnimation animationDidStop:finished:]
委托方法来设置最终属性值以及您想要执行的任何其他操作。我想你可以用这个来摆脱那个可怕的事情NSTimer
你正在使用的代码和世界的一小部分将会变得更好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)