1

我试图实现一个通知,提醒键盘将出现并且应该随着键盘高度向上移动的视图。

func subscribeToKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
}

这是KeyboardWillShow方法体:

@objc func KeyboardWillShow(_ notification: Notification) {
    view.frame.origin.y -= getKeyBoardHeight(notification)
}

getKeyBoardHeight函数:

func getKeyBoardHeight(_ notification: Notification) -> CGFloat {
    let userinfo = notification.userInfo
    let keyboardsize = userinfo![UIKeyboardFrameEndUserInfoKey] as! NSValue

    return keyboardsize.cgRectValue.height
}

为什么当我在模拟器中打开键盘时,我的应用程序会完全移出视线?

4

1 回答 1

1

这些是我经常使用的有效方法,我认为你的问题是 using -= getKeyboardHeight,试试keyboardWillShow下面我方法中的代码

class VC: UIViewController {

    func subscribeToKeyboardNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
    }

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

    @objc func keyboardWillHide(notification: NSNotification) {
        view.frame.origin.y = 0
    }

    @objc func keyboardWillShow(notification: NSNotification) {
        view.frame.origin.y = -getKeyboardHeight(notification: notification)
    }

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

}
于 2018-08-20T11:01:48.623 回答