Created
January 26, 2015 20:30
-
-
Save Krelborn/f881418592122f82c102 to your computer and use it in GitHub Desktop.
Dynamic label height with KILabel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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; | |
} | |
} |
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
This is how work out the heights of rows of KILabels in a timeline view.