Skip to content

Instantly share code, notes, and snippets.

@lucaspang
Last active March 18, 2016 08:24
Show Gist options
  • Save lucaspang/a3e906bb28d460c1412e to your computer and use it in GitHub Desktop.
Save lucaspang/a3e906bb28d460c1412e to your computer and use it in GitHub Desktop.
iOS UITableViewCell Height Calculation(iOS7-9)
//For iOS9, there is a new way(buggy in iOS7,8) to calculating the cell height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
/* Return an estimated height or calculate
* estimated height dynamically on information
* that makes sense in your case.
*/
return 200.0f;
}
//iOS8 or below
- (CGFloat)heightForCellAtIndexPath:(NSIndexPath *)indexPath {
static UITableViewCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"heightCell"];
});
[self configureCell:sizingCell atIndexPath:indexPath]; //set the necessary data into the cell
return [self calculateHeightForConfiguredSizingCell:sizingCell];
}
- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {
//Need to set the width for it to determine the label size
//since we are not using sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"commentCell"];
//but sizingCell = [[CommentBaseTableViewCell alloc] init]; instead
CGRect frame = sizingCell.frame;
frame.size.width = CGRectGetWidth(self.vendorTableView.frame);
sizingCell.frame = frame;
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height; // Add 1.0f for the cell separator height
}
//Also, Add this code into UITableViewCell if there is any multiline Label included
-(void)layoutSubviews{
[super layoutSubviews];
[self.contentView layoutIfNeeded];
self.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.titleLabel.frame);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment