我正在阅读 12th number of Objc.io并在尝试第一段代码时遇到问题。 在第一部分“基本动画”中,最后一段代码使用 byValue 来使用初始属性值和添加 byValue 来插入属性。
所以我在我的项目中尝试了代码,发现它无法正常工作并且有一个非常奇怪的行为。
这是一个非常简短的 gif 说明问题:
这是我唯一使用的代码:
class ViewController: UIViewController {
var rocket1: UIView!
var rocket2: UIView!
override func viewDidLoad() {
super.viewDidLoad()
rocket1 = UIView(frame: CGRect(x: 20, y: 100, width: 50, height: 20))
rocket1.backgroundColor = UIColor.redColor()
rocket2 = UIView(frame: CGRect(x: 20, y: 150, width: 50, height: 20))
rocket2.backgroundColor = UIColor.blueColor()
self.view.addSubview(rocket1)
self.view.addSubview(rocket2)
}
@IBAction func button() {
let animation = CABasicAnimation(keyPath: "position.x")
animation.byValue = 300
animation.duration = 1
rocket1.layer.addAnimation(animation, forKey: "basic")
rocket1.layer.position.x += 300
animation.beginTime = CACurrentMediaTime() + 0.5
rocket2.layer.addAnimation(animation, forKey: "basic")
rocket2.layer.position.x += 300
}
}
如果你想尝试这个项目,这里是完整的项目(使用 iPhone 6 模拟器或形状将被隐藏,因为 5S 太“短”):https://dl.dropboxusercontent.com/u/378166/VCoreAnimation.zip
最佳答案
你应该像这样为这个动画创建一个完成 block :
@IBAction func button() {
let animation = CABasicAnimation(keyPath: "position.x")
animation.byValue = 300
animation.duration = 1
CATransaction.begin()
CATransaction.setCompletionBlock({
rocket1.layer.position.x += 300
})
rocket1.layer.addAnimation(animation, forKey: "basic")
CATransaction.commit()
animation.beginTime = CACurrentMediaTime() + 0.5
CATransaction.begin()
CATransaction.setCompletionBlock({
rocket2.layer.position.x += 300
})
rocket2.layer.addAnimation(animation, forKey: "basic")
CATransaction.commit()
}
在这种情况下,我们需要 2 个 CATransaction block ,因为我们有 2 个动画以彼此不同的时间运行。
关于ios - CABasicAnimation byValue 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383747/