Calculate content bounds for dynamic cell heights
suggest changeA common use case for calculating the frame a label will take up is sizing table view cells. The recommended way is the NSString method boundingRectWithSize:options:attributes:context:.
options takes string drawing options:
NSStringDrawingUsesLineFragmentOriginshould be used for labels with multiple linesNSStringDrawingTruncatesLastVisibleLineshould be added with the|operator when there is a maximum number of lines
attributes is an NSDictionary of attributes that affect attributed strings (full list: Apple Docs). The factors that affect height include:
- NSFontAttributeName: Very important, the size and font family is a critical part of the label’s displayed size.
- NSParagraphStyleAttributeName: For customizing how the text is displayed. This includes line spacing, text alignment, truncation style, and a few other options. If you did not explicitly change any of these values you should not have to worry about this much, but may be important if you toggled some values on IB.
context should be nil. The main use of NSStringDrawingContext is letting the font shrink to fit a given rect, which is not what a dynamic-height calculation is doing.
Calling cellForRowAtIndexPath: from heightForRowAtIndexPath: can recurse, or return a cell that has not been configured yet. Reading the string from the data source avoids that. The samples below assume a custom cell with a theLabel property. heightOfObjectsOnTopOfLabel and heightOfObjectBelowLabel stand in for the vertical space around that label.
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *labelContent = cell.theLabel.text;
// you may choose to get the content directly from the data source if you have done minimal customizations to the font or are comfortable with hardcoding a few values
// NSString *labelContent = [self.dataSource objectAtIndexPath:indexPath];
// value may be hardcoded if retrieved from data source
UIFont *labelFont = [cell.theLabel font];
// The NSParagraphStyle, even if you did not code any changes these values may have been altered in IB
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = @{NSFontAttributeName: labelFont,
NSParagraphStyleAttributeName: paragraphStyle};
// The width is also important to the height
CGFloat labelWidth = CGRectGetWidth(cell.theLabel.frame);
// If you have been hardcoding up to this point you will be able to get this value by subtracting the padding on left and right from tableView.bounds.size.width
// CGFloat labelWidth = CGRectGetWidth(tableView.frame) - 20.0f - 20.0f;
CGRect bodyBounds = [labelContent boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
return CGRectGetHeight(bodyBounds) + heightOfObjectsOnTopOfLabel + heightOfObjectBelowLabel;
}
Swift 3
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cell = tableView.cellForRow(at: indexPath)!
let labelContent = cell.theLabel.text ?? ""
let labelFont = cell.theLabel.font
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .center
let attributes = [NSFontAttributeName: labelFont, NSParagraphStyleAttributeName: paragraphStyle]
let labelWidth: CGFloat = cell.theLabel.frame.width
let bodyBounds = labelContent.boundingRect(with: CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
return bodyBounds.height + heightOfObjectsOnTopOfLabel + heightOfObjectBelowLabel
}
Conversely, if there is a maximum number of lines, first calculate the height of a single line so the result is not taller than the allowed size:
// Measure one line by omitting NSStringDrawingUsesLineFragmentOrigin, which lays the string out on a single line.
CGRect singleLineRect = [labelContent boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)
options:NSStringDrawingTruncatesLastVisibleLine
attributes:attributes
context:nil];
CGFloat lineHeight = CGRectGetHeight(singleLineRect);
CGFloat maxHeight = lineHeight * cell.theLabel.numberOfLines;
// Now you can call the method appropriately
CGRect bodyBounds = [labelContent boundingRectWithSize:CGSizeMake(labelWidth, maxHeight) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine) attributes:attributes context:nil];
return CGRectGetHeight(bodyBounds) + heightOfObjectsOnTopOfLabel + heightOfObjectBelowLabel;