Swift--监听iPhone键盘弹出及隐藏事件

前端之家收集整理的这篇文章主要介绍了Swift--监听iPhone键盘弹出及隐藏事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

开发需求:对键盘弹出及隐藏事件进行监听

需要通过NotificationCenter对键盘事件进行监听

  1. //键盘即将弹出
  2. NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardShow(note:)),name: NSNotification.Name.UIKeyboardWillShow,object: nil)
  3. //键盘即将隐藏
  4. NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardHidden(note:)),name: NSNotification.Name.UIKeyboardWillHide,object: nil)
  5.  
  6. //键盘弹出监听
  7. @objc func keyboardShow(note: Notification) { guard let userInfo = note.userInfo else {return}
  8. guard let keyboardRect = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect else{return}
  9. //获取键盘弹起的高度
  10. let keyboardTopYPosition = SCREENHEIGHT - keyboardRect.height
  11.  
  12. }
  13.  
  14. //键盘隐藏监听
  15. @objc func keyboardHidden(note: Notification){ }
  16.  
  17. //取消键盘监听
  18. deinit { NotificationCenter.default.removeObserver(self) }

如果要监听键盘完全弹起或隐藏后进行操作,则使用

  1. //注意,这里使用的是UIKeyboardDidShow
  2. NotificationCenter.default.addObserver(self,name: NSNotification.Name.UIKeyboardDidShow,object: nil)
  3.  
  4. //注意,这里使用的是UIKeyboardDidHide
  5. NotificationCenter.default.addObserver(self,name: NSNotification.Name.UIKeyboardDidHide,object: nil)

猜你在找的Swift相关文章