关于键盘弹出后遮挡屏幕的解决办法
在实际使用中,我们经常会遇到键盘弹出后遮挡住屏幕的问题。通常情况下,我们是通过在弹出键盘的时候同时上移整个View来解决的,下面是解决过程用需要用到的代码
首先,我们要在viewDidLoad
方法里面往通知中心注册一个监听来获取键盘的状态
- (void)viewDidLoad
{
[super viewDidLoad];
// 注册键盘监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillHideNotification object:nil];
}
然后在回调方法keyboardWillShow:(NSNotification *)notification
里面获取键盘的大小,位置来进行动画
#pragma mark - 根据键盘动态改变高度
- (void)keyboardWillShow:(NSNotification *)notification
{
// 这里我们首先获取一下当前键盘的位置和大小(iOS8)
NSDictionary* info = [notification userInfo];
CGRect kbRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSInteger offset = self.view.frame.size.height - kbRect.origin.y;
NSTimeInterval animationDuration;
UIViewAnimationCurve animationCurve;
// 然后获取键盘动画的animationDuration和animationOptions属性
[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
[[info objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
UIViewAnimationOptions options = animationCurve << 16;
[UIView animateWithDuration:animationDuration
delay:0.0f
options:options
animations:^
{
self.view.y = -offset;
// 如果要更改约束记得通知View重新计算布局
[self.view layoutIfNeeded];
}
completion:nil];
}
[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
[[info objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
我们可以获取这两个值来使View和键盘的动画时间和动画曲线完全吻合的效果