将布局约束动画与设备旋转同步

时间:2018-04-15 13:22:54

标签: ios swift animation

当键盘启动且设备正在旋转时,我正在努力处理文本字段底部约束动画。基本上我需要将文本字段位置更改动画与旋转动画同步。就像在视频中一样:https://www.youtube.com/watch?v=bbMYVEdodJQ

我正在使用viewWillTransition(to size :) - 获取用于设备旋转动画的动画持续时间和曲线参数的方法。那好吧。

然后我使用名为UIKeyboardWillChangeFrame的通知中心通知来通知我键盘大小,以便我可以相应地移动textField。多数民众赞成也好。不幸的是,UIKeyboardWillChangeFrame通知总是在调用viewWillTransition(to size :)方法之后发生。

我应该如何同步动画?下面是动画不同步的代码。

    func setKeyboardObservers() {

     NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame , object: nil)
}



override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

    super.viewWillTransition(to: size, with: coordinator)

    coordinator.animate(alongsideTransition: { (context) in

        self.deviceRotating = true

        self.animationDuration = context.transitionDuration
        self.animationCurve = UInt(context.completionCurve.rawValue)

    }) { (_) in

      self.deviceRotating = false
    }

}



@objc func keyboardWillChange(_ notification: NSNotification) {

    let keyboardFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue


    if deviceRotating {

         textFieldBottomContstrain.constant = -keyboardFrame.height

        UIView.animateKeyframes(withDuration: animationDuration, delay: 0, options: UIViewKeyframeAnimationOptions(rawValue: animationCurve), animations: {
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}

0 个答案:

没有答案