swift3监听软键盘的弹出、收起,和高度变化

来源:互联网 发布:天猫和淘宝的客流量 编辑:程序博客网 时间:2024/06/06 02:08

swift3监听软键盘的弹出、收起,和高度变化

示例代码

    override func viewDidLoad() {        super.viewDidLoad()        //监听软键盘的弹出        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)        //监听软键盘的收起        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)        //监听软键盘的高度变化        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)        //获取屏幕大小        let screenSize : CGSize = UIScreen.main.bounds.size        //调整消息显示的高度        labelHeight.constant = screenSize.height - 200    }    //注销监听软键盘    deinit {        //移除通知        NotificationCenter.default.removeObserver(self)    }    //键盘的出现    func keyBoardWillShow(_ notification: Notification){        //调整消息显示区域高度        labelHeight.constant -= 210    }    //键盘的隐藏    func keyBoardWillHide(_ notification: Notification){        //调整消息显示区域高度        labelHeight.constant += 210    }    //软键盘的高度变化    func keyboardWillChangeFrame(_ notification: Notification) {        //获取屏幕高度的坐标        let endFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue        let y = endFrame.origin.y        //获取屏幕大小        let screenSize : CGSize = UIScreen.main.bounds.size        //调整按钮底部约束        if info != nil {            buttonBottom.constant = screenSize.height - y + 10        } else {            buttonBottom.constant = screenSize.height - y - 40        }    }
0 0