使 tableview 单元格以 textView 文本大小扩展

Make tableview cell expand with textView text size

为此我学习了很多教程但是我找不到解决问题的方法

我想在 table 单元格上显示 textView。 Cell 应使用用户在 textView 中输入的文本展开。

我发现有两种方法可以做到这一点

第一个:-

self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 30;


func textViewDidChange(_ textView: UITextView!, for indexPath: IndexPath!) {
    self.presenter?.valueChanged(section: indexPath.section, value: textView.text)
    isChanged = true

    self.tableView.beginUpdates()
    self.tableView.endUpdates()
}
Make the table view to adjust height automatically. But in this case when there is no data to display in cellForRow at index path then textview height is automatically adjusted to 0 and i was not able to select the text view.

第二种方式:-

删除自动尺寸代码

// MARK: TextViewTableViewCellDelegate
func textViewDidChange(_ textView: UITextView!, for indexPath: IndexPath!) {
    self.presenter?.valueChanged(section: indexPath.section, value: textView.text)
    isChanged = true

    self.tableView.beginUpdates()
    self.tableView.endUpdates()
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    var ret = DEFAULT_CELL_HEIGHT

    if let cell = tableView.dequeueReusableCell(withIdentifier: SECTION_TYPE_FREEFORM) as? TextViewTableViewCell {
        cell.textView.text = self.presenter?.cellBody(section: indexPath.section)
        cell.textView.sizeToFit()

        let width = self.view.frame.size.width - HORIZONTAL_PADDING
        let calculatedHeight = cell.textView.sizeThatFits(CGSize(width: width, height: CGFloat(MAXFLOAT))).height + 10
        if(calculatedHeight > ret) {
            ret = calculatedHeight
        }
    }

    return ret
}

但在此我检查了我在 heightForRowAtIndexPath 方法中创建单元格然后 textview 高度不合适。而且自动调整高度也不行。

请提出相同的解决方案。提前致谢。

向您的文本视图添加最小高度限制并使用第一种方法怎么样?只需确保禁用 UITextView 的滚动。 因为你在第一个解决方案中遇到的唯一问题是单元格高度太小,而里面什么也没有...

否则你的代码看起来很不错,可能会给你流畅的动画。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  return UITableViewAutomaticDimension 
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { 
  return yourinitialheight 
}

移除高度约束,并设置顶部、底部、前导和尾随约束。