user3766930 user3766930 - 1 year ago 82
Swift Question

How can I adjust the UITableViewCell height to the content of UITextView that's inside?

In my story board I have a

with dynamically generated
s. Each cell contains 2 labels and 1 text view:

enter image description here

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:

enter image description here

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?

Answer Source

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

  • 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).
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download