请查看以下我用来将子层沿 y 轴向上移动 50 个点的方法。特别要注意最后一行(已注释掉)。
@objc func animateButtonPressed(_ sender: UIButton) {
let initialValue = customView.sublayer.position.y
let finalValue = customView.sublayer.position.y - 50
let animation = CABasicAnimation(keyPath: "position.y")
animation.fromValue = initialValue
animation.toValue = finalValue
animation.duration = 2
customView.sublayer.add(animation, forKey: "Reposition")
//customView.sublayer.position.y = finalValue
}
使用如图所示的代码,我得到以下行为:
- 图层从初始位置缓慢移动到最终位置。
- 然后该层跳回初始位置。
- 该层保持在初始位置。
我读到的所有内容都告诉我,发生“跳回”是因为我没有更新模型以反映最终值。因此,让我们通过取消注释最后一行来更新模型。现在的行为是:
- 图层从初始位置跳到最终位置。
- 然后该层跳回初始位置。
- 然后该层缓慢移动到最终位置。
- 该层保持在最终位置。
跳跃显然正在发生,因为最终位置是在模型上设置的。我觉得我处于 22 号陷阱。任何帮助将不胜感激。
Xcode 10.0、iOS 12.2、Swift 4.2