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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容