我想通过 CABasicAnimation 将 blueView 移动到视图中心。这是我的代码:
import Cocoa
class ViewController: NSViewController {
private let blueView: NSView = NSView()
private lazy var blueViewCenterXAnchor: NSLayoutConstraint? = nil
private lazy var blueViewCenterYAnchor: NSLayoutConstraint? = nil
private lazy var blueViewWidthAnchor: NSLayoutConstraint? = nil
private lazy var blueViewHeightAnchor: NSLayoutConstraint? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.view.wantsLayer = true
blueView.wantsLayer = true
blueView.layer?.backgroundColor = NSColor.blue.cgColor
self.view.addSubview(blueView)
blueView.translatesAutoresizingMaskIntoConstraints = false
blueViewCenterXAnchor = blueView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: -300.0)
blueViewCenterYAnchor = blueView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
blueViewWidthAnchor = blueView.widthAnchor.constraint(equalToConstant: 200.0)
blueViewHeightAnchor = blueView.heightAnchor.constraint(equalToConstant: 200.0)
blueViewCenterXAnchor?.isActive = true
blueViewCenterYAnchor?.isActive = true
blueViewWidthAnchor?.isActive = true
blueViewHeightAnchor?.isActive = true
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(1)) {
self.updateConstantViaCABasicAnimation()
}
}
func updateConstantViaCABasicAnimation() {
let animation = CABasicAnimation()
animation.keyPath = "position.x"
animation.fromValue = blueViewCenterXAnchor!.constant // need to convert it to usable value
animation.toValue = blueViewCenterXAnchor!.constant + 300.0 // need to convert it to usable value
animation.duration = 1.0
blueView.layer?.add(animation, forKey: "basic")
//blueView.layer?.position = CGPoint(x: self.view.centerXAnchor.x, y: self.view.centerXAnchor.y) // need to convert it to usable value
}
}
在这段代码中,如您所见,我正在尝试访问 blueViewCenterXAnchor 携带的数据或值,以避免建立所需值的数学计算。所以问题的目标不是用数学方法解决问题,而是访问视图的 NSLayoutConstraint。在这行代码中,我将常量从
self.view.centerXAnchor
设置为 -300.0,以便稍后使用动画移动到 self.view.centerXAnchor。这意味着完成动画后,蓝色视图应该位于self.view
的中心。
来自:
blueView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: -300.0)
至:
blueView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0.0)
所以我遇到了访问动画所需值以避免数学计算的问题。动画有效但方式错误。那么我应该怎么做呢?
这个问题的主要目标基本上是用
CABasicAnimation更新
NSLayoutConstraint
,如果我的代码示例不适合解决这个目标的问题,你可以用你自己的示例代码来回答,用CABasicAnimation更新NSLayoutConstraint。