键盘出现时调整UITableView的大小。动画不稳定

时间:2017-03-29 04:23:28

标签: ios swift uitableview

我有一个全屏UITableView,它固定在顶部,底部,尾部和前端。此ViewController位于导航控制器内。我希望桌子的底部向上移动,并在出现时使用键盘进行动画制作。我有以下代码:

    // MARK: Keyboard

    func registerObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func unregisterObservers() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(_ notification: Notification) {
        let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let keyboardAnimationDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        let keyboardAnimationCurve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        tableViewBottomConstraint.constant = keyboardFrame.height
        UIView.animate(withDuration: TimeInterval(keyboardAnimationDuration), delay: 0, options: [UIViewAnimationOptions(rawValue: UInt(keyboardAnimationCurve))], animations: {
            self.view.layoutIfNeeded()
        }, completion: { (finished: Bool) in
        })
    }

    func keyboardWillHide(_ notification: Notification) {
        let keyboardAnimationDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        let keyboardAnimationCurve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        tableViewBottomConstraint.constant = 0
        UIView.animate(withDuration: TimeInterval(keyboardAnimationDuration), delay: 0, options: [UIViewAnimationOptions(rawValue: UInt(keyboardAnimationCurve))], animations: {
            self.view.layoutIfNeeded()
        }, completion: { (finished: Bool) in
        })
    }

我在ViewDidLoad上注册了观察者。当键盘出现时,动画看起来非常生涩。然而,解雇动画似乎没有任何问题。我在这做错了什么?我是否设置了动画持续时间或曲线错误?

1 个答案:

答案 0 :(得分:4)

我通过以下方式完成了这项工作:

为底部约束声明一个IBOutlet变量。请确保链接适当的约束,对于您的情况,该约束是tableView的底部约束。

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

添加一个功能来处理调整。

    func keyboardChangeFrame(_ notification: Notification) {
    let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    bottomConstraint.constant = view.bounds.height - endFrame.origin.y
    self.view.layoutIfNeeded()
}

最后,在viewDidLoad中添加UIKeyboardWillChangeFrame观察者。

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