ios10版本textView和textField注冊鍵盤通知
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("Textfield獲得焦點(diǎn),點(diǎn)擊Return鍵")
textField.resignFirstResponder()
return true
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
print("textview獲得焦點(diǎn),點(diǎn)擊return鍵")
textView.resignFirstResponder()
return false
}
return true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//注冊鍵盤出現(xiàn)通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
//注冊鍵盤隱藏通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(_:)), name: UIResponder.keyboardDidHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
//注銷鍵盤出現(xiàn)通知
NotificationCenter.default.removeObserver(self,name:UIResponder.keyboardDidShowNotification,object:nil)
//注銷鍵盤隱藏通知
NotificationCenter.default.removeObserver(self,name:UIResponder.keyboardDidHideNotification,object:nil)
}
@objc func keyboardDidShow(_ notification: Notification){
print("鍵盤打開")
}
@objc func keyboardDidHide(_ notification: Notification){
print("鍵盤關(guān)閉")
}