Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Dynamic label height with KILabel
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row < self.timeline.count)
{
NSDictionary *tweet = self.timeline[indexPath.row];
NSAttributedString *string = [TLTimelineViewController decorateLabelStringForMessage:tweet];
// Measure the string, it's height is dynamic based on content. We calculate
// a width for the string by assuming the cell will fill the width of the table
// minus some padding applied around elements.
enum { kHorzPadding = 56 };
CGSize sizeForLabel = CGSizeMake(self.tableView.frame.size.width - kHorzPadding, 0);
CGRect labelRect = CGRectMake(0, 0, sizeForLabel.width, CGFLOAT_MAX);
// Use a dummy label and its textRectForBounds method to calculate the height
// of a real label.
static KILabel *measureLabel = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
measureLabel = [[KILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width - kHorzPadding, 16)];
measureLabel.numberOfLines = 0;
});
measureLabel.attributedText = string;
labelRect = [measureLabel textRectForBounds:labelRect limitedToNumberOfLines:0];
return 48 + labelRect.size.height - 16;
}
else
{
return 44;
}
}
Owner

Krelborn commented Jan 26, 2015

This is how work out the heights of rows of KILabels in a timeline view.

Owner

Krelborn commented Apr 29, 2015

The KILabel demo app now has a solution for doing this with auto layout. You no longer need to override tableView:heightForRowAtIndexPath:.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment