如何在现有的UIViewController中为UIViewPropertyAnimator添加向后兼容性(iOS 9)?

时间:2019-06-09 16:48:49

标签: ios swift

我为我的项目创建了一个现有的UIViewController,该UIViewController是为iOS 10的部署目标而构建的。此视图控制器使用新的UIViewPropertyAnimator为某些视图设置动画。现在,我的团队想添加对无法使用UIViewPropertyAnimator类的iOS 9.3的支持。

动画师是视图控制器中的存储属性,因此我可以在整个类中的各种动画函数中引用动画师。

我不能将动画师声明为@available(iOS 10.0, *),因为它是属性而不是函数。

我无法在handlePan函数中本地声明动画制作器,因为每次调用该函数时都会重新创建动画制作器。

class PickerViewController: UIViewController {

    //This causes the error because it is unavailable in iOS 9.3
    fileprivate var animator = UIViewPropertyAnimator()

    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 10.0, *) {
            let panGesture:UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:)))
            panGesture.maximumNumberOfTouches = 1
            panGesture.minimumNumberOfTouches = 1
            self.view.addGestureRecognizer(panGesture)
        } else {
            // Fallback on earlier versions
            let swipeLeftGesture:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(viewSwipeLeft(sender:)))
            swipeLeftGesture.direction = .left
            self.view.addGestureRecognizer(swipeLeftGesture)

            let swipeRightGesture:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(viewSwipeRight(sender:)))
            swipeRightGesture.direction = .right
            self.view.addGestureRecognizer(swipeRightGesture)
        }
    }

    @objc func handlePan(recognizer: UIPanGestureRecognizer) {

        switch recognizer.state {
        case .began:
            animator = UIViewPropertyAnimator(duration: 0.2, curve: .easeOut, animations: { [unowned self] in
                //do stuff...
                self.view.layoutIfNeeded()
            })
            animator.addCompletion { (animatingPosition) in
                //complete stuff
            }

            animator.startAnimation()
            animator.pauseAnimation()
        case .changed:
            // calculate percent
            animator.fractionComplete = percent
        case .ended:
            animator.continueAnimation(withTimingParameters: nil, durationFactor: 0)
        default:
            animator.continueAnimation(withTimingParameters: nil, durationFactor: 0)
        }
    }
}

我不想创建2个单独的UIViewController类,并将它们都插入到我的.storyboard文件中,具体取决于iOS版本,它们的顺序不同。但是到目前为止,我能想到的就是所有这些...

0 个答案:

没有答案