Reputation: 10172
I want to expand label's height based on the text inside. I use tableviewcontroller with static cells.
I have an UILabel
in a tableview cell and I set top, bottom, right and left constraints of the label.
I tried these solutions:
self.eDesc.numberOfLines = 0
self.eDesc.lineBreakMode = NSLineBreakMode.byWordWrapping
self.eDesc.sizeToFit()
self.tableView.estimatedRowHeight = 140
self.tableView.rowHeight = UITableViewAutomaticDimension
But none of them worked.
Is there any other approach on this (maybe changing size by label frame)?
Upvotes: 5
Views: 3755
Reputation: 79676
To set automatic dimension for row height & estimated row height, ensure following steps to make, auto dimension effective for cell/row height layout. I just tested following steps and code and works fine.
UITableViewAutomaticDimension
to rowHeight & estimatedRowHeightheightForRowAt
and return a value UITableViewAutomaticDimension
to it)-
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set dataSource and delegate for table
table.dataSource = self
table.delegate = self
// Set automatic dimensions for row height
// Swift 4.2 onwards
table.rowHeight = UITableView.automaticDimension
table.estimatedRowHeight = UITableView.automaticDimension
// Swift 4.1 and below
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Swift 4.2 onwards
return UITableView.automaticDimension
// Swift 4.1 and below
return UITableViewAutomaticDimension
}
For label instance in UITableviewCell
Edit: You must be missing top or bottom or height layout constraint for anyone UIElement in cell. Ensure all UIElements in cell, have valid top and bottom (and height, whereever required) constraints attached with it vertical (adjacent) UIElement.
Note: If you've more than one labels (UIElements) with dynamic length, which should be adjusted according to its content size: Adjust 'Content Hugging and Compression Resistance Priority` for labels which you want to expand/compress with higher priority.
Here in this example I set low hugging and high compression resistance priority, that leads to set more priority/importance for contents of second (yellow) label.
Upvotes: 9