iOS键盘隐藏时的事件

25
我需要控制,在键盘显示和完成按钮被按下之后,当键盘隐藏时。在iOS上隐藏键盘时触发的事件是哪个?谢谢

http://developer.apple.com/library/ios/search/?q=keyboard+hide - jscs
可能是ipad如何知道键盘已隐藏的重复问题。 - jscs
3个回答

59

可以,使用以下方法:

//UIKeyboardDidHideNotification when keyboard is fully hidden
//name:UIKeyboardWillHideNotification when keyboard is going to be hidden

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onKeyboardHide:) name:UIKeyboardWillHideNotification object:nil];

而且是 onKeyboardHide

-(void)onKeyboardHide:(NSNotification *)notification
{
     //keyboard will hide
}

1
这将在解除时触发,而不是键盘完全隐藏时。 - Andres Canella
2
是的,正确的,请检查更新后的答案。要完全隐藏通知,请使用 UIKeyboardDidHideNotification - Omar Abdelhafith

6
如果您想知道用户何时按下“完成”按钮,您需要采用UITextFieldDelegate协议,然后在您的视图控制器中实现此方法:
Swift 3:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // this will hide the keyboard
    textField.resignFirstResponder()
    return true
}

如果您想简单了解键盘何时显示或隐藏,请使用 Notification

Swift 3:

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

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

func keyboardWillShow(_ notification: NSNotification) {
    print("keyboard will show!")

    // To obtain the size of the keyboard:
    let keyboardSize:CGSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size

}

func keyboardWillHide(_ notification: NSNotification) {
    print("Keyboard will hide!")
}

5
您可以监听一个UIKeyboardWillHideNotification,每当键盘被隐藏时它就会被发送。

7
准确来说,在键盘消失之前通知会被发送。 - Henri Normak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接