iOS 键盘挡住输入框的解决方案

本文介绍如何通过注册通知来监听iOS设备上的键盘状态变化,包括键盘显示、隐藏及尺寸变化,并提供了具体的代码实现。

原理:利用通知来实现对键盘状态的监听
直接上代码
1.注册通知

/*  
     键盘即将弹出
    UIKeyboardWillShowNotification
     键盘已经弹出
    UIKeyboardDidShowNotification
     键盘即将隐藏
    UIKeyboardWillHideNotification
     键盘已经隐藏
    UIKeyboardDidHideNotification
     键盘frame变化
    UIKeyboardWillChangeFrameNotification
*/

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldShouldChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

2.实现通知方法

- (void)textFieldShouldChangeFrame:(NSNotification *)notification{
    //通知中的字典信息
    NSDictionary *dict = notification.userInfo;
    CGRect beginRect = [dict[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endRect = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    /* 键盘弹出高度变化 */
    CGFloat changeY = beginRect.origin.y - endRect.origin.y;
    /* 键盘弹出动画时间 */
    NSTimeInterval time = [dict[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    /* 利用动画改变键盘位置 */
    [UIView animateWithDuration:time animations:^{
        _textField.frame = CGRectMake(0, _textField.frame.origin.y - changeY, _textField.frame.size.width, _textField.frame.size.height);
    }];
}

3.移除通知

- (void)dealloc{
    /* 移除通知 */
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值