关于键盘出现与隐藏时调整UITextField的显示位置问题

1、首先在ViewDidLoad里面添加注册键盘隐藏与出现的通知:

    ///< 注册通知,以便在键盘将要出现时,调整页面
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    ///< 注册通知,以便在键盘将要隐藏时,恢复页面
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

2、在viewWillDisappear里移除对键盘隐藏与出现的通知:

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    /// 注意:在此处需要移除通知,否则容易照成崩溃
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    return;
}

3、实现键盘出现、隐藏时的通知回调:

#pragma mark - UIKeyboardWillShowNotification 通知
- (void)onKeyboardWillShow:(NSNotification *)notification {
    CGRect frame = self.view.frame;
    if (frame.origin.y < 0) {
        return;
    }
    // 获取键盘的高度
    CGFloat keyboardHeight = [self keyboardHeightWithKeyboardNotification:notification];
    frame.origin.y -= (keyboardHeight - 20);
    [UIView animateWithDuration:0.35 animations:^{
        self.view.frame = frame;
    }];
    return;
}

#pragma mark - UIKeyboardWillHideNotification 通知
- (void)onKeyboardWillHide:(NSNotification *)notification {
    CGRect frame = self.view.frame;
    if (frame.origin.y > 0) {
        return;
    }
    // 获取键盘的高度
    CGFloat keyboardHeight = [self keyboardHeightWithKeyboardNotification:notification];
    frame.origin.y += (keyboardHeight - 20);
    [UIView animateWithDuration:0.35 animations:^{
        self.view.frame = frame;
    }];
    return;
}

/// 获取键盘高度
- (CGFloat)keyboardHeightWithKeyboardNotification:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    CGFloat keyboardHeight = keyboardSize.height;
    
    return keyboardHeight;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值