(iOS)关于键盘遮挡textfield问题

记录一下自己经常遇到问题。使用textfield(textview)。当输入框位置比较靠下时,弹出的键盘会遮挡输入框,这是就需要动态移动输入框编辑状态时self.view的位置,

自己经常用的方法有两个

1、项目中很多地方用到输入框,并出现这些问题,用第三方库---IQKeyboardManager,非常的方便,什么都不用写就能实现很多功能。就不详叙述了

2、一两处地方用到,可以自己简单的写一下

  两个通知:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

self.tempTF------定义的中间textfield。当有多个输入框是,在代理中

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

    self.tempTF = textField;

    return YES;

}

 

 --------------------------------------------------------------------------------------------------------------------------------------------------

/**

 *  键盘出现

 */

- (void)keyboardWillShow:(NSNotification *)notification

{

    //获取键盘高度,在不同设备上,以及中英文下是不同的

    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;

    // 取得键盘的动画时间,这样可以在视图上移的时候更连贯

    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    CGFloat offset = HEIGHT - (self.tempTF.frame.origin.y+self.tempTF.frame.size.height+kbHeight);

    if(offset<=0)

    {

        [UIView animateWithDuration:duration animations:^{

            CGRect frame = self.view.frame;

            frame.origin.y = offset;

            self.view.frame = frame;

        }];

    }

}

/**

 *  键盘消失

 */

- (void)keyboardWillHide:(NSNotification *)notification

{

    // 键盘动画时间

    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    

    //视图下沉恢复原状

    [UIView animateWithDuration:duration animations:^{

        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

    }];

}

 --------------------------------------------------------------------------------------------------------------------------------------------------

over---新手,有很多不足,敬请见谅。 

 

转载于:https://www.cnblogs.com/helonghl/p/5488173.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值