2012-06-05 96 views
24

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

+0

http://developer.apple.com/library/ios/search /?q =键盘+隐藏 –

+0

[ipad如何知道键盘已隐藏]的可能重复(http://stackoverflow.com/questions/7912246/ipad-how-to-know-keyboard-has-been-hidden) –

回答

56

是使用以下

//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

这将在解雇时触发,而不是在键盘完全隐藏时触发。 –

+2

是的,正确的,请检查更新的答案,对于完全隐藏的通知使用'UIKeyboardDidHideNotification' –

5

您可以收听UIKeyboardWillHideNotification,每当键盘被解散时发送它。

+7

确切地说,通知在键盘被解除前发送。 –

+0

@亨利,对,因为我现在正在处理这个问题。 – Morkrom

3

如果你想知道,当用户按下完成按钮,你必须采取UITextFieldDelegate协议,那么在您查看控制器执行此方法:

Swift 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!") 
}