下面是 UIView 子类中的一些相关代码:
- (void) doMyCoolAnimation {
CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"position.x"];
anim.duration = 4;
[self.layer setValue:@200 forKeyPath:anim.keyPath];
[self.layer addAnimation:anim forKey:nil];
}
- (CGFloat) currentX {
CALayer* presLayer = self.layer.presentationLayer;
return presLayer.position.x;
}
当我在动画运行时使用 [self currentX]
时,我得到 200
(结束值)而不是 between 0
(起始值)和 200
。是的,动画对用户可见,所以我在这里真的很困惑。
这是我调用 doMyCoolAnimation:
以及 1 秒后调用 currentX
的代码。
[self doMyCoolAnimation];
CGFloat delay = 1; // 1 second delay
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
NSLog(@"%f", [self currentX]);
});
有什么想法吗?
最佳答案
我不知道在动画代码中使用 KVC setter 的想法从何而来,但这就是动画本身的用途。您基本上是在用这一行告诉图层树立即更新到新位置:
[self.layer setValue:@200 forKeyPath:anim.keyPath];
然后想知道为什么图层树不会使用没有起始值或结束值的动画动画到该位置。没有什么可以动画的!适本地设置动画的 toValue
和 fromValue
并放弃 setter。或者,如果您希望使用隐式动画,请保留 setter,但放弃动画并通过改变图层的 speed
来设置其持续时间。
关于ios - UIView.layer.presentationLayer 返回最终值(而不是当前值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22741496/