思路相同、写法不一样而已
OC
//添加检测者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
//移除通知
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 监听
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
// 修改约束
CGFloat keyboardY = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
//控件距离底部约束
self.bottomMargin.constant = screenH - keyboardY;
// 执行动画
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}
Swift2.3
// 注册通知监听键盘弹出和消失
NSNotificationCenter.defaultCenter().addObserver(self , selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// 只要键盘改变就会调用
func keyboardChange(notify: NSNotification)
{
print(notify)
// 1.取出键盘最终的rect
let value = notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
let rect = value.CGRectValue()
// 2.修改工具条的约束
// 弹出 : Y = 409 height = 258
// 关闭 : Y = 667 height = 258
// 667 - 409 = 258
// 667 - 667 = 0
let height = UIScreen.mainScreen().bounds.height
//更改约束
toolbarBottonCons?.constant = -(height - rect.origin.y)
// 3.更新界面
let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
UIView.animateWithDuration(duration.doubleValue) { () -> Void in
self.view.layoutIfNeeded()
}
}
Swift3.0
// 0.注册通知监听键盘弹出和消失
NotificationCenter.default.addObserver(self, selector: #selector(keyboardChange(notify:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
deinit {
NotificationCenter.default.removeObserver(self)
}
/// 只要键盘改变就会调用
func keyboardChange(notify:NSNotification)
{
print(notify)
// 1.取出键盘最终的rect
let value = notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
let rect = value.cgRectValue
// 2.修改工具条的约束
// 弹出 : Y = 409 height = 258
// 关闭 : Y = 667 height = 258
// 667 - 409 = 258
// 667 - 667 = 0
let height = UIScreen.main.bounds.height
toolbar.snp.updateConstraints { (make) in
make.bottom.equalTo(-(height - rect.origin.y))
}
// 3.更新界面
let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
UIView.animate(withDuration: TimeInterval(duration)) {
self.view.layoutIfNeeded()
}
}
网友评论