关于键盘弹出后遮挡屏幕的解决办法

关于键盘弹出后遮挡屏幕的解决办法

在实际使用中,我们经常会遇到键盘弹出后遮挡住屏幕的问题。通常情况下,我们是通过在弹出键盘的时候同时上移整个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和键盘的动画时间和动画曲线完全吻合的效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值