Swift 使用键盘移动视图

Swift move view with keyboard

我试图在键盘出现时向上移动视图,在键盘隐藏时向下移动视图。

我遇到的问题是高度好像不一样:KBH1输出216,KBH2输出260。

这导致视图比最初移动的更远。

我该如何纠正?

extension UIViewController {

    func addKeyboardFunctions() {

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboardEx))
       // tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: Notification.Name.UIKeyboardWillHide, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: Notification.Name.UIKeyboardWillShow, object: nil)
    }

    @objc func keyboardWillAppear(_ notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y == 0{
                self.view.frame.origin.y -= keyboardSize.height
                print("KBH: \(keyboardSize.height)")
            }
        }
    }

    @objc func keyboardWillDisappear(_ notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y != 0{
                self.view.frame.origin.y += keyboardSize.height
                print("KBH: \(keyboardSize.height)")
            }
        }
    }

问题是您正在使用 UIKeyboardFrameBeginUserInfoKey

通知会给你一个开始帧和一个结束帧,这样你就可以相应地移动你的视图。结束帧将是键盘动画结束的地方,所以它的最终位置。你应该用这个。

我以前经常使用这个扩展,我想它是为了 Swift 2

func getKeyboardHeight(notification: NSNotification) -> CGFloat {
    let userInfo = notification.userInfo
    let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
    return keyboardSize.CGRectValue().height
}

您应该可以将其更新为 Swift 4,但最重要的部分是使用结束帧而不是开始帧