将 UITableViewCell 的高度调整为 UITextView 的高度

Oli*_*ver 3 uitableview ios swift

我的UITableView. 一个是自定义UITableViewCell,另一个是带有UITextView内部并称为 type的单元格TextViewCell

因为它们是静态的,所以单元格是viewDidLoad从 xib以方法加载的:

textCell = Bundle.main.loadNibNamed(String(describing: TextViewCell.self),
                                        owner: self, options: nil)?.first! as! TextViewCell
ratingCell = Bundle.main.loadNibNamed(String(describing: RatingCell.self),
                                          owner: self, options: nil)?.first! as! RatingCell
Run Code Online (Sandbox Code Playgroud)

现在我尝试使用heightForRowAt委托更改高度:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == 1 {
        return textCell.textView.contentSize.height
    }
    return ratingCell.ratingView.frame.height
}
Run Code Online (Sandbox Code Playgroud)

我禁用了滚动,UITextView但单元格没有正确调整大小。事实上,细胞变小了。TextViewCell看起来像这样的约束: 在此处输入图片说明

有什么建议?

Rom*_*mov 5

我认为您需要使用 self-sizing UITableViewCell。将您当前的实现替换heightForRowAt为以下内容:

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

    return UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)

现在UITableView将根据约束自动计算对象中单元格的高度。另外,为行高添加一些估计值:

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

    return 100.0 // You can set any other value, it's up to you
}
Run Code Online (Sandbox Code Playgroud)

现在您将看到UITextView视图填充了整个UITableViewCell单元格。