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

注册通知
NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.keyboardWillChangeFrame(node:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
移除通知
deinit {
    NotificationCenter.default.removeObserver(self)
}
监听键盘高度变化
@objc private func keyboardWillChangeFrame(node : Notification){
    //1.获取动画执行的时间
    let duration =  node.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
    //2. 获取键盘最终的Y值
    let endFrame = (node.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
    let y = endFrame.origin.y
    //3.计算工具栏距离底部的间距
    let margin =  UIScreen.main.bounds.height - y
    //4.执行动画
    toolBarBottomCons.constant = margin
    UIView.animate(withDuration: duration) {
        self.view.layoutIfNeeded()
    }
}

常用的通知的名字
. 监听软键盘的弹出
.UIKeyboardWillShow
. 监听软键盘的收起
.UIKeyboardWillHide
.监听软键盘的高度变化
.UIKeyboardWillChangeFrame

你可能感兴趣的:(swift4监听软键盘的弹出、收起,和高度变化)