How can I adjust the UITableViewCell height to the

2020-03-31 08:52发布

问题:

In my story board I have a UITableView with dynamically generated UITableViewCells. Each cell contains 2 labels and 1 text view:

I have a code that adjust the size of the textfield to the amount of text:

let fixedWidth = cell.myComment.frame.size.width
cell.myComment.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
let newSize = cell.myComment.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = cell.myComment.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
cell.myComment.frame = newFrame;

and it works fine, when I set a background color of my textView to red I see:

and the cell itself - I'm setting the size in here:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
     if indexPath.row == 0 {
         return 100//this is my static cell
     }
     else {
         return 117; //for now it's hardcoded - how can I set this value dynamically based on content?
     }
}

So as I wrote in the comment above - how can I set the height of the cell dynamically based on the amount of text in the text view?

回答1:

The key to getting self-sizing table cells (autolayout-based, which I recommend) is as follows:

  • Add your subviews to the contentView of the UITableViewCell
  • Provide constraints between your subviews and the contentView such that your subviews reach all edges of the table cell. In your case, this probably means aligning the leading, trailing, top, and bottom edges of your UITextView to the corresponding edges of the contentView.
  • Set the row height to UITableViewAutomaticDimension instead of a hardcoded CGFloat.
  • Somewhere in your controller, provide an estimation of the height with tableView.estimatedRowHeight = x (a hard coded constant is fine, this is for performance).