通过单元格内的textView的内容更改单元格高度

我有一个名为todoTableView的表视图与用户创build的单元格。 每个单元格都有文本视图。 我想通过文本视图的内容来改变单元格的高度。 这是我试过的:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath:indexPath) as! TableViewCell cell.bounds.size.height = cell.textView.bounds.size.height return cell } 

使用边界约束将您的textviewcell绑定在一起( 引导,尾随,顶部和底部约束

在这里输入图像说明

  • 禁用textView滚动

viewDidLoad()中添加以下内容。

 tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension 

这将使您的单元格大小根据您的textview内容大小。

看看结果:

在这里输入图像说明

您不需要编写heightForRowAtIndexPath

Irfan的回答对我不起作用。

它在我进入Size Inspector之后工作,并且检查“Row Height”的“Automatic”。

你也应该实现heightForRowAtIndexPath

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return // Calculate your custom row height here. }