I have a view controller that uses a custom cell called searchCell to bring content in and I am wondering how I can get the height of the label lblLeft and use it in the tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat function to return the height of the label. The code I'm using in my Main View Controller:
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
if searchMode == searching {
let cell: MHSearchCell = tableView.dequeueReusableCell(withIdentifier:
MHSearchCell.ReusableIdentifier()) as! MHSearchCell
cell.helper = helpers[indexPath.row]
cell.delegate = self
return cell
}
}
Part of the code that creates the label in my MHSearchCell, the label is connected here as an IBOutlet:
lblLeft.text = ""
if let expertiseCount = helper.expertise {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = NSTextAlignment.center
lblLeft.numberOfLines = 0
let finalString = expertiseCount.map({$0.name!}).joined(separator: " \u{00B7} ")
let finalAttributedString = NSMutableAttributedString(string: finalString, attributes: [NSParagraphStyleAttributeName:paragraphStyle])
lblLeft.attributedText = finalAttributedString
}
I use a custom extension to calculate the height of NSAttributedString. The "containerWidth" would be the max width of your label, which is most likely the contentView.bounds.size.width of your cell.
}
One "trick" is that heightForRowAtIndexPath is called before cellForRowAtIndexPath. You need to create a placeholder cell and keep a reference to it. Then you do something like this:
You don't want to init the placeholder cell in heightForRowAtIndexPath because it will really kill your performance to initialize an object every time that's called. That's why you initialize it from the beginning and keep reusing it.
//
If you're using auto layout, you can also look up how to have the UITableView automatically set the height of the cell for you. Which could be a better option.
First Way either use Automatic Dimensions
1) Apply Appropriate constraints on label check the image below.
Make sure label Lines are set to
0
in storyboard.Now in controller class do this-:
Table Function-:
Another Way of calculating estimatedHeightForLabel-:
1) Apply same constraints to label as mentioned above
2) use
boundingRect
method of NSString to find exact height for cell from label -:Table View Functions-:
Remember-:
1) Provide same font size you have for label.
2) For multiline label use option as
.usesLineFragmentOrigin
.CustomCellClass-: