ios 监控键盘状态

不羁岁月 提交于 2019-12-07 09:38:25

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

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)

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!