UIKeyboardWillShow通知问题

时间:2017-10-22 15:52:41

标签: ios swift3 keyboard ios11

在我的应用程序视图中,我在ScrollView中有几个TextField。我实现了UIKeyboardWillShow / WillHide通知。但我有一些问题。当我点击文本字段时,WillShow工作得很完美,但在键盘隐藏并点击文本字段之后它再也不起作用了。我点击另一个文本字段和相同的问题。但是在不同的文本字段上进行2-3次点击后,它再次起作用,然后再发生相同这是我使用的代码:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

funcs:

@objc func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if view.frame.origin.y == 0 {
            view.frame.origin.y -= keyboardSize.height/2
        }
    }
}

@objc func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if view.frame.origin.y != 0{
            view.frame.origin.y += keyboardSize.height/2
        }
    }
}

这就是我在用户点按视图中的任意位置时隐藏键盘的方法:

func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
}

func dismissKeyboard() {
    view.endEditing(true)
}

我无法找到问题以及如何解决问题。我的iPhone 6上有iOS 11.0.3。

1 个答案:

答案 0 :(得分:0)

试试这个。

func keyboardWillShow(notification: NSNotification) {

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

        self.view.frame.origin.y = -keyboardSize.height/2
    }
}

func keyboardWillHide(notification: NSNotification) {

    if let _ = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

        self.view.frame.origin.y = 0
    }
}