键盘隐藏时的iOS事件

时间:2012-06-05 18:03:27

标签: iphone objective-c ios xcode cocoa-touch

我需要控制,在显示键盘并按下完成按钮后,键盘隐藏。在iOS上隐藏键盘时会触发哪个事件?谢谢

3 个答案:

答案 0 :(得分:57)

是使用以下

//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 :(得分:6)

如果您想知道用户何时按下完成按钮,您必须采用UITextFieldDelegate协议,然后在您的View控制器中实现此方法:

斯威夫特3:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // this will hide the keyboard
    textField.resignFirstResponder()
    return true
}

如果您只想知道键盘何时显示或隐藏,请使用Notification

斯威夫特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!")
}

答案 2 :(得分:5)

你可以听一个UIKeyboardWillHideNotification,只要键盘被解除就会发送它。