我正在设置propertyAnimator?.fractionComplete
根据平移手势的翻译来更改视图的位置。稍后,我打算CGPoint.zero
在手指抬起后将其动画化。这是我的代码:
class ViewController: UIViewController {
let squareContainerView = UIView(frame: CGRect(x: 100, y: 70, width: 230, height: 30))
let squareView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
let targetSquareViewOrigin = CGFloat(200)
let label = UILabel(frame: CGRect(x: 25, y: 140, width: 350, height: 30))
var propertyAnimator: UIViewPropertyAnimator?
var panGesture: UIPanGestureRecognizer!
var totalTranslation = CGFloat(0) {
didSet {
label.text = "Translation: \(totalTranslation.rounded()), percentage: \(totalTranslation / squareContainerView.frame.width)"
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(squareContainerView)
squareContainerView.addSubview(squareView)
view.addSubview(label)
squareContainerView.backgroundColor = UIColor.red
squareView.backgroundColor = UIColor.blue
label.text = "Translation: \(totalTranslation.rounded()), percentage: \(totalTranslation / squareContainerView.frame.width)"
panGesture = UIPanGestureRecognizer(target: self, action:(#selector(self.handleGesture(_:))))
squareContainerView.addGestureRecognizer(panGesture)
propertyAnimator = UIViewPropertyAnimator(duration: 1, curve: .linear)
propertyAnimator?.addAnimations {
self.squareView.frame.origin.x = self.targetSquareViewOrigin
}
}
@objc func handleGesture(_ sender: UIPanGestureRecognizer) {
totalTranslation += sender.translation(in: squareContainerView).x
let fractionComplete = totalTranslation / squareContainerView.frame.width
propertyAnimator?.fractionComplete = fractionComplete
sender.setTranslation(.zero, in: squareContainerView) /// reset to zero
}
}
方形视图正在移动,但是当百分比高于1
或低于0
时,它会停止。这是有道理的,因为它的原始来源是CGPoint.zero
,我用addAnimations()
.
但是,我希望它继续移动,即使分数完成了。在文档中它说:
定义自定义动画器时,如果您支持动画运行超过其起点或终点,则可以允许大于 1.0 或小于 0.0 的值。
我该如何启用它?我应该创建一个子类,如果是,我应该重写哪些方法?