Reputation: 3600
I have a custom table view cell that I want to automatically resize based on the amount of text in a label.
Here is my cell. I want to resize it in order to show all the text in the review label.
In my table view controller I use UITableViewAutomaticDimension
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
if indexPath.row == 0 {
return 200
} else {
return 49
}
} else if indexPath.section == 1 {
return 100
} else if indexPath.section == 2 {
if indexPath.row == 0 {
return 200
} else {
return 400
}
} else {
return UITableViewAutomaticDimension
}
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
This is what I end up with.
Upvotes: 1
Views: 288
Reputation: 757
Make sure you have constraints set for the top, bottom, trailing and leading margins to the contentView from a child UIView
or whatever child elements you have. This might help you
In your case, you will need to define a bottom spacing constraint from the ReviewLabel to the contentView to make it work. The top, trailing and leading margins will be needed too from the corresponding UILabel
s. The top space can be defined from the DateLabel while the leading and trailing spaces can be defined from the UIView containing the stars
Why?
The contentView needs to know about the frame of it's child views to have the uitableviewautomaticdimension work on it. If it does not know about it's child view frames then it wouldn't know what to automatically resize to
Upvotes: 0
Reputation: 2446
You need:
top, trailing, leading, bottom
constraints to superView in IBnumberOfLines = 0
Content Compression Resistance Priority Vertical
and Content Hugging Priority Vertical
self.tableView.estimatedRowHeight = MinControlSize;
self.tableView.rowHeight = UITableViewAutomaticDimension;
And after set the text call this
cell.setNeedsDisplay();
cell.layoutIfNeeded();
in delegate method
optional func tableView(_ tableView: UITableView,
heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
Hope this help. I took this from Self Sizing example from Apple
Upvotes: 1
Reputation: 3130
Implement the height calculations in the delegate function:
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let cell = tableView.cellForRowAtIndexPath(indexPath)
let size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
return size.height + 1.0 // Add 1.0 for the cell separator height
}
Upvotes: 0