- 先注册键盘监听,代码如下:
- (void)registerForKeyboardNotification {
// 键盘出现
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)name:UIKeyboardWillChangeFrameNotification object:nil];
// 键盘隐藏
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- 键盘出现时动画,代码如下:
// 键盘出现时
- (void)keyboardWillShow:(NSNotification*)aNotification {
NSDictionary *info = [aNotification userInfo];
CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
UIViewAnimationCurve curve = [aNotification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
CGRect endRect = [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 更新officialBottomView位置
CGRect newFrame = self.officialBottomView.frame;
if (isIPhoneX) {
newFrame.origin.y = endRect.origin.y - 80 - 90;
}
else {
newFrame.origin.y = endRect.origin.y - 80 - 70;
}
UIViewAnimationOptions options = (UIViewAnimationOptions)curve << 16;
[UIView animateWithDuration:duration delay:0.0 options:options animations:^{
self.officialBottomView.frame = newFrame;
} completion:NULL];
}
- 键盘隐藏时动画,代码如下:
// 当键盘隐藏时
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
NSTimeInterval duration = [aNotification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationCurve curve = [aNotification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
CGRect endRect = [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 复原officialBottomView位置
CGRect newFrame = self.officialBottomView.frame;
if (isIPhoneX) {
newFrame.origin.y = self.view.frame.size.height - officialBottomViewHeight - 34;
}
else {
newFrame.origin.y = self.view.frame.size.height - officialBottomViewHeight;
}
UIViewAnimationOptions options = (UIViewAnimationOptions)curve << 16;
[UIView animateWithDuration:duration delay:0.0 options:options animations:^{
self.officialBottomView.frame = newFrame;
} completion:NULL];
}
网友评论