欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS键盘弹出遮挡输入框的解决方法

程序员文章站 2024-01-10 22:57:37
本文为大家分享了ios键盘弹出遮挡输入框的解决方法,供大家参考,具体内容如下问题:输入框被键盘遮挡期望效果:输入框位于键盘上方解决思路:监听键盘出现和消失的状态,当键盘出现时,当前视图上移,当输入完成...

本文为大家分享了ios键盘弹出遮挡输入框的解决方法,供大家参考,具体内容如下

问题:输入框被键盘遮挡

期望效果:输入框位于键盘上方

iOS键盘弹出遮挡输入框的解决方法

解决思路:

监听键盘出现和消失的状态,当键盘出现时,当前视图上移,当输入完成收起键盘时,视图回到初始状态。

难点:视图向上平移的距离

iOS键盘弹出遮挡输入框的解决方法

原理都差不多,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);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。