Calculate content bounds (for dynamic label cell height)

Janvi Arora
1 min readMar 8, 2023

--

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var cell = tableView.cellForRow(atIndexPath: indexPath)!
var labelContent = cell.theLabel.text
var labelFont = cell.theLabel.font
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .center
var attributes = [NSFontAttributeName: labelFont, NSParagraphStyleAttributeName: paragraphStyle]
var labelWidth: CGFloat = cell.theLabel.frame.width
var bodyBounds = labelContent.boundingRect(withSize: CGSize(width: width, height: CGFLOAT_MAX), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
return bodyBounds.height + heightOfObjectsOnTopOfLabel + heightOfObjectBelowLabel
}

This code is an implementation of the tableView(_:heightForRowAt:) method, which is a UITableViewDelegate method that returns the height of a row at a given index path in a table view.

The method first retrieves the cell at the given index path by calling tableView.cellForRow(atIndexPath:). It then gets the text content of the label in the cell and the font used for the label.

Next, it creates a NSMutableParagraphStyle object and sets its line break mode to .byWordWrapping and alignment to .center. It then creates an attributes dictionary with the font and paragraph style.

It then determines the width of the label by accessing the label’s frame property, and calculates the height of the label’s text content using the boundingRect(withSize:options:attributes:context:) method of the text content, which returns the smallest rectangle that encloses the string’s bounding box, computed using the specified font, paragraph style, and other options.

Finally, it returns the sum of the calculated height of the label’s text content and the height of any objects placed above and below the label in the cell, which are represented by the heightOfObjectsOnTopOfLabel and heightOfObjectBelowLabel constants.

--

--

No responses yet