iOS键盘弹出遮挡输入框

Obejctive-C 专栏收录该内容
9 篇文章 0 订阅

问题:输入框被键盘遮挡

期望效果:输入框位于键盘上方
在这里插入图片描述
解决思路:
监听键盘出现和消失的状态,当键盘出现时,当前视图上移,当输入完成收起键盘时,视图回到初始状态。

难点:视图向上平移的距离
在这里插入图片描述
原理都差不多,oc版参考代码:

	self.phoneInput = [UITextField new];
    self.phoneInput.placeholder = @"请输入...";
    [self.view addSubview:self.phoneInput];


///键盘弹出 处理遮挡问题
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification
{
  //获取处于焦点中的view
  NSArray *textFields = @[self.phoneInput];
  UIView *focusView = nil;
  for (UITextField *view in textFields) {
    if ([view isFirstResponder]) {
      focusView = view;
      break;
    }
  }
  if (focusView) {
     //获取键盘弹出的时间
     double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
     //获取键盘上端Y坐标
     CGFloat keyboardY = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
     //获取输入框下端相对于window的Y坐标
     CGRect rect = [focusView convertRect:focusView.bounds toView:[[[UIApplication sharedApplication] delegate] window]];
     CGPoint tmp = rect.origin;
     CGFloat inputBoxY = tmp.y + focusView.frame.size.height;
     //计算二者差值
     CGFloat ty = keyboardY- inputBoxY;
     NSLog(@"position keyboard: %f, inputbox: %f, ty: %f", keyboardY, inputBoxY, ty);
     //差值小于0,做平移变换
     [UIView animateWithDuration:duration animations:^{
       if (ty < 0) {
          self.view.transform = CGAffineTransformMakeTranslation(0, ty);
       }
     }];
   }
}

- (void)keyboardWillHide:(NSNotification *)notification
{
  //获取键盘弹出的时间
  double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  //还原
  [UIView animateWithDuration:duration animations:^{
     self.view.transform = CGAffineTransformMakeTranslation(0, 0);
  }];
}
///<UITextFieldDelegate>
///UITextFieldDelegate编辑完成,视图恢复原状
-(void)textFieldDidEndEditing:(UITextField *)textField
{
     self.view.frame =CGRectMake(0, 0,  [[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height);
}
  • 1
    点赞
  • 2
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值