Swift - 根据UITextView布局约束的UITableViewCell高度

时间:2016-11-01 19:05:32

标签: ios swift

在我的表视图中,单元格是3个对象;图像视图,标签和文本视图。

这就是我设置textView及其约束的方法:

textView.translatesAutoresizingMaskIntoConstraints = false
textView.textColor = UIColor.blue
textView.font = UIFont.systemFont(ofSize:15.0)
textView.textAlignment = NSTextAlignment.left
textView.isScrollEnabled = false

**请注意,self是包含textView的UIView。表格视图单元格的内容视图将包含此UIView

self.addConstraints([
            textView.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 10.0),
            textView.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10.0),
            textView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10.0),
            textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 20.0)
            ])

我制作了isScrollEnabled = false,以便textView的高度根据其内容计算

对于我的UITableView,我这样做了:

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

使用上面的代码,我的tableviewcell没有显示正确的高度。我相信它是因为我的textview高度约束使tableviewcell内容视图的高度错误。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

  1. 设置isScrollEnabled = false不会影响计算textView的高度。
  2. 为了根据textView的内容调整单元格大小,除了 top(=)textView添加底部(=)约束strong>和 可选身高(> =)

答案 1 :(得分:0)

您是否尝试过使用tableView(heightForRowAt:)委托方法?

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   return textView.frame.height // Assuming you have a reference to the textview
}