ios - UITextView 在 UITableViewCell 内部增长

标签 ios uitableview uitextview

我在 SO 上看到了很多与此相关的问题,但是,没有一个与我的问题有关。

我要创建一个具有消息传递功能的应用程序。类似于 Apple 在他们的应用程序中有 Mail 和 LinkedIn 在他们的应用程序中有邮件功能,我想要一个包含 3 行的 UITableView。第三行有 UITextView,它必须随着用户输入而增长。我的代码如下:

- (void)textViewDidChange:(UITextView *)textView {
    if (bodyText.contentSize.height > currentContentHeight) {
        currentContentHeight = bodyText.contentSize.height;

        [tblView beginUpdates];
        [tblView endUpdates];

        [bodyText setFrame:CGRectMake(0, 0, 310.0, currentContentHeight)];

        bodyText.selectedRange = NSMakeRange(textView.text.length - 1, 0);

    } else {
        currentContentHeight = minimumContentHeight;

        [tblView beginUpdates];
        [tblView endUpdates];
    }
}

当我在 iPhone 上按下回车键时,它会停机并完美运行。问题是,如果我转到中心或 UITextView 的任何其他中间部分,它似乎会产生有趣的行为,因为它错误地获取了 contentSize。例如:

  • 我按回车键 10 次
  • 转到第五行并输入“dog”
  • 它根据第 5 行获取 contentHeight,是否有意义?

有没有办法根据当前的所有文本来计算呢?如果上面遗漏了什么,请告诉我。我广泛阅读了以下内容:

http://dennisreimann.de/blog/uitextview-height-in-uitableviewcell/

https://stackoverflow.com/questions/985394/growing-uitextview-and-uitableviewcell

UITextView inside a UITableViewCell

How do I size a UITextView to its content?

最佳答案

我用以下代码编辑了上面的代码,它对我有用:

- (void)textViewDidChange:(UITextView *)textView {    
    // Get the number of lines in the current view
    NSUInteger lines = textView.text.length;
    if ((lines * 25) > currentContentHeight && (lines * 25) >= minimumContentHeight && bodyText.contentSize.height > minimumContentHeight) {

        currentContentHeight = bodyText.contentSize.height;

    } else if (lines < 5){
        currentContentHeight = minimumContentHeight;
    }

    [tblView beginUpdates];
    [tblView endUpdates];

    [bodyText setFrame:CGRectMake(5, 5, 310, currentContentHeight)];

    bodyText.selectedRange = [bodyText selectedRange];
}

我一开始根据手机大小设置了currentContentHeight等于minimumContentHeight

关于ios - UITextView 在 UITableViewCell 内部增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14404634/

相关文章:

iphone - 便利构造函数会增加应用程序的大小吗?

ios - TextView和TextField的单个扩展以添加工具栏

ios - 从 UITextView 的第一行创建标题(Think Apple Notes 应用程序)Swift

iphone - UITextView 不随 ARC 发布

iphone - 更改 UIVIEW 的变换/旋转/缩放而不使用动画

ios - 在 Objective C UITableVIew 中如何在调用重新加载后保留滚动位置

ios - 在 UITableViewController 中为多个实例初始化结构的位置

ios - 表格 View 上下文菜单 : custom animation from row to a preview view controller

ios - Swift 单元格内容不显示

android - iOS中的 Activity 生命周期相当于什么?