Skip to content

Instantly share code, notes, and snippets.

@Krelborn
Created January 26, 2015 20:30
Show Gist options
  • Save Krelborn/f881418592122f82c102 to your computer and use it in GitHub Desktop.
Save Krelborn/f881418592122f82c102 to your computer and use it in GitHub Desktop.
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;
}
}
@Krelborn
Copy link
Author

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

@Krelborn
Copy link
Author

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