1、监听键盘通知
// 注册键盘弹出通知
NotificationCenter.default.addObserver(self, selector: #selector(GGComposeViewController.keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
2、获取通知内的信息
@objc fileprivate func keyboardWillChangeFrame(note : Notification) {
// 取出通知中有用的信息
let userInfo = note.userInfo!
// 键盘弹出的动画时间
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
// 键盘最后的frame
let keyBoardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
//do something
}
3、改变底部工具栏距离底部的约束
@objc fileprivate func keyboardWillChangeFrame(note : Notification) {
// 取出通知中有用的信息
let userInfo = note.userInfo!
// 键盘弹出的动画时间
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
// 键盘最后的frame
let keyBoardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
// 计算工具栏约束高度 工具栏距离底部的约束高度 = 屏幕的高度 - 键盘的Y值
let margin = UIScreen.main.bounds.height - keyBoardFrame.origin.y
// 添加动画效果
tabBarBottomCons.constant = margin
UIView.animate(withDuration: duration) {
self.view.layoutIfNeeded()
}
}
4、注销通知
网友评论