Swift--监听iPhone键盘弹出及隐藏事件
发布时间:2020-12-14 06:00:40 所属栏目:百科 来源:网络整理
导读:开发需求:对键盘弹出及隐藏事件进行监听 需要通过NotificationCenter对键盘事件进行监听 //键盘即将弹出 NotificationCenter. default .addObserver( self , selector : # selector ( self .keyboardShow(note:)),name: NSNotification.Name.UIKeyboardWill
开发需求:对键盘弹出及隐藏事件进行监听需要通过NotificationCenter对键盘事件进行监听 //键盘即将弹出
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardShow(note:)),name: NSNotification.Name.UIKeyboardWillShow,object: nil)
//键盘即将隐藏
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardHidden(note:)),name: NSNotification.Name.UIKeyboardWillHide,object: nil)
//键盘弹出监听
@objc func keyboardShow(note: Notification) { guard let userInfo = note.userInfo else {return}
guard let keyboardRect = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect else{return}
//获取键盘弹起的高度
let keyboardTopYPosition = SCREENHEIGHT - keyboardRect.height
}
//键盘隐藏监听
@objc func keyboardHidden(note: Notification){ }
//取消键盘监听
deinit { NotificationCenter.default.removeObserver(self) }
如果要监听键盘完全弹起或隐藏后进行操作,则使用 //注意,这里使用的是UIKeyboardDidShow
NotificationCenter.default.addObserver(self,name: NSNotification.Name.UIKeyboardDidShow,object: nil)
//注意,这里使用的是UIKeyboardDidHide
NotificationCenter.default.addObserver(self,name: NSNotification.Name.UIKeyboardDidHide,object: nil) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |