键盘隐藏时的 iOS 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10902465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS event when keyboard hides
提问by Jaume
I need to control, after keyboard is shown and done button is pressed, when keyboard hides. Which event is triggered when hides keyboard on iOS? Thank you
我需要控制,在显示键盘并按下完成按钮后,当键盘隐藏时。在 iOS 上隐藏键盘时会触发哪个事件?谢谢
回答by Omar Abdelhafith
Yes Use the following
是 使用以下
//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];
And the onKeyboardHide
而 onKeyboardHide
-(void)onKeyboardHide:(NSNotification *)notification
{
//keyboard will hide
}
回答by Domenico
If you want to know when the user press the Done button, you have to adopt the UITextFieldDelegate
protocol, then in you View controller implement this method:
如果您想知道用户何时按下 Done 按钮,您必须采用该UITextFieldDelegate
协议,然后在您的 View 控制器中实现此方法:
Swift 3:
斯威夫特 3:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// this will hide the keyboard
textField.resignFirstResponder()
return true
}
If you want to know simply when keyboard is shown or is hiding, use a Notification
:
如果您只想知道键盘何时显示或隐藏,请使用Notification
:
Swift 3:
斯威夫特 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!")
}
回答by kevboh
You can listen for a UIKeyboardWillHideNotification
, it's sent whenever the keyboard is dismissed.
您可以收听UIKeyboardWillHideNotification
,它会在键盘关闭时发送。