Ios Swift:如何使UITableViewCell高度适应其内部的UITextView

Ios Swift:如何使UITableViewCell高度适应其内部的UITextView,ios,swift,uitextview,uitableview,Ios,Swift,Uitextview,Uitableview,最简单的方法是将UITextView高度调整为其内容,然后将充当容器的UITableViewCell高度调整为与该UITextView相同的高度?将UITextView行数设置为0。 在包含tableView的控制器的viewDidLoad中,使用: tableView.estimatedRowHeight = 55.0 tableView.rowHeight = UITableViewAutomaticDimension 将UITextView行数设置为0。 在包含tableView的控

最简单的方法是将
UITextView
高度调整为其内容,然后将充当容器的
UITableViewCell
高度调整为与该
UITextView
相同的高度?

将UITextView行数设置为0。 在包含tableView的控制器的viewDidLoad中,使用:

 tableView.estimatedRowHeight = 55.0
 tableView.rowHeight = UITableViewAutomaticDimension

将UITextView行数设置为0。 在包含tableView的控制器的viewDidLoad中,使用:

 tableView.estimatedRowHeight = 55.0
 tableView.rowHeight = UITableViewAutomaticDimension

要计算文本视图的高度,我认为您需要知道文本的高度。因此,在heightForRowAtIndexPath委托方法上,计算文本高度并使用以下方法返回:

func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: width, height: CGFloat.max)

    let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

    return boundingBox.height
}
您需要将textview约束、底部、顶部、前导和尾随设置为0,以便根据单元格大小进行调整。
代码已获取。

要计算文本视图的高度,我认为您需要知道文本的高度。因此,在heightForRowAtIndexPath委托方法上,计算文本高度并使用以下方法返回:

func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: width, height: CGFloat.max)

    let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

    return boundingBox.height
}
您需要将textview约束、底部、顶部、前导和尾随设置为0,以便根据单元格大小进行调整。
代码已被提取。

如果文本较大,您可能必须使用大于55的数字作为
估计值。是的,此值取决于UITableViewCell中的内容如果文本较大,您可能需要使用大于55的数字来计算
估计值。是的,此值取决于UITableViewCell中的内容