ios 监控键盘状态

Posted 荣超

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ios 监控键盘状态相关的知识,希望对你有一定的参考价值。

增加键盘显示和隐藏事件监听

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)

 

@objc func keyboardWillShow(notification:Notification){
        let userinfo:Dictionary = notification.userInfo!
        let frame = (userinfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        UIView.animate(withDuration: 0.4, animations: {
            self.view.frame.origin.y = 0 - frame.height
        })
    }
    
    @objc func keyboardWillHide(notification:Notification){
        UIView.animate(withDuration: 0.4, animations: {
            self.view.frame.origin.y = 0
        })
    }

  删除事件监听

NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)

  

以上是关于ios 监控键盘状态的主要内容,如果未能解决你的问题,请参考以下文章

iOS中监控软键盘显示或隐藏的可靠方法

关闭 dialogFragment 时键盘未关闭

iOS - 更改为不同的 TextField 时保持 TextField 状态的输入键盘

ios 键盘状态栏的高度是多少

iOS收起键盘

iOS--实时监控网络状态的改变