ios - 出现键盘时调整 UITextView 的大小

标签 ios objective-c uitextview

我想在键盘出现时调整 TextView 的大小。我的代码如下。我启用了自动布局,因此使用来自 superview 的 textView->bottom 空间的约束并通过 IBOutlet distanceFromBottom 引用它。

- (void)keyboardWillShow:(NSNotification *)notification
{
  [UIView animateWithDuration:0.3 animations:^{
    NSDictionary* d = [notification userInfo];
    CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    r = [textView convertRect:r fromView:Nil];
    if(IS_IPHONE_6||IS_IPHONE_6P)
      distanceFromBottom.constant = r.origin.y+78;
    else if(IS_IPHONE_5)
      distanceFromBottom.constant = r.origin.y+183;
  }];
}

上面的代码工作完美。我不明白的是为什么我需要为 iPhone6 添加 +78 或为 iPhone5 添加 183。这两个值是我通过反复试验得出的。如果我不添加这些,textView 会延伸到键盘下方。请帮我解开这个谜。

最佳答案

viewWillAppear 方法中,添加以下内容:

- (void) viewWillAppear:(BOOL)paramAnimated{
    [super viewWillAppear:paramAnimated];

    [[NSNotificationCenter defaultCenter] 
        addObserver:self 
           selector:@selector(handleKeyboardDidShow:) 
               name:UIKeyboardDidShowNotification object:nil];

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

然后实现通知中心的两个方法,像这样:

- (void) handleKeyboardDidShow:(NSNotification *)paramNotification{

    NSValue *keyboardRectAsObject =
        [[paramNotification userInfo] 
            objectForKey:UIKeyboardFrameEndUserInfoKey];

    CGRect keyboardRect = CGRectZero;
    [keyboardRectAsObject getValue:&keyboardRect];

    yourTextView.contentInset =
        UIEdgeInsetsMake(0.0f,
                         0.0f,
                         keyboardRect.size.height,
                         0.0f);
}

另一个像:

- (void) handleKeyboardWillHide:(NSNotification *)paramNotification{

    yourTextView.contentInset = UIEdgeInsetsZero;
}

它适用于所有设备;)

关于ios - 出现键盘时调整 UITextView 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27992591/

相关文章:

ios - MPMediaPickerController 和 MPMediaitemPropertyAssetUrl

objective-c - 如何配置 Xcode 以将 '{' 放在生成文件中我想要的位置

ios - UITextView 文本指示器在错误的位置

objective-c - 根据 iOS 中的文本宽度动态更改 TextView 宽度

ios - text 和 textStorage 有什么区别

ios - 在自调整单元格、iOS8 及更高版本中为 UITextView 启用滚动

iphone - 一个可用的 MGTwitterEngine iPhone 示例项目

ios - 绘制一个带有一些阴影偏移的圆边平行四边形

ios - 在 NSUserDefaults 或文档目录中保存和读取图像数组及其数据

ios - 使用 CocoaPods 时如何向 Xcode 添加自定义项目配置?