2012-06-05 122 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!") 
}