ios键盘出现或者消失的问题

想要达到的效果是当键盘出现的时候,底部的button和label会自动上挪,处于键盘上方的位置。而当键盘消失的时候,button和label会自动回到底部。

我用的是添加scrollView的方法,然后监控键盘的状态,但是遇到的问题是:键盘消失时,button和label的确在底部,但是当键盘出现时,button和label会被出现的键盘盖住。有没有什么方法可以解决这个问题?多谢

阅读 5.6k
4 个回答

如果用的地方不多,可以注册键盘出现和隐藏的通知,并参考如下代码做视图偏移

#define  yOffset  -50

-(void)textViewDidBeginEditing:(UITextView *)textView{
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    CGRect rect=CGRectMake(0.0f,yOffset,width,height);
    self.view.frame=rect;
    [UIView commitAnimations];
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    [self resumeView];
}

//恢复原始视图位置
-(void)resumeView{
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    //如果当前View是父视图,则Y为20个像素高度,如果当前View为其他View的子视图,则动态调节Y的高度
    float Y = 0.0f;
    CGRect rect=CGRectMake(0.0f,Y,width,height);
    self.view.frame=rect;
    [UIView commitAnimations];
}

如果用的地方比较多,建议使用IQKeyboardManager

新手上路,请多包涵

如果button和label在scrollView上,那么scrollView向上滚动一个键盘的高度

新手上路,请多包涵

可以监听当前textfield 或者 textview的位置,判断有没有被键盘挡住,然后根据位置差来移动scrollview.

  1. 监听键盘通知 UIKeyboardWillShowNotification UIKeyboardWillHideNotification, 分别调用键盘处理方法

    • 取出键盘的 frame

    • 取出键盘弹出需要花费的时间

    • 修改约束

    • [self.view layoutIfNeeded]

  2. 监听键盘通知 UIKeyboardWillChangeFrameNotification 在方法中做键盘处理,处理方式和方法一一致

  3. 通过 tranform 做键盘处理,

    • 取出键盘最终的frame
      CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    • 取出键盘弹出需要花费的时间
      double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    • 修改transform
      [UIView animateWithDuration:duration animations:^{

      CGFloat ty = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
      self.view.transform = CGAffineTransformMakeTranslation(0, - ty);

      }];

  4. 用 Swift 的话,推荐一个库 IQKeyboardManager

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题