Skip to content

Instantly share code, notes, and snippets.

@zoejessica
Last active August 29, 2015 14:01
Show Gist options
  • Save zoejessica/770a59e6f380e575ae94 to your computer and use it in GitHub Desktop.
Save zoejessica/770a59e6f380e575ae94 to your computer and use it in GitHub Desktop.
Dynamic cell height calculation where prototype cells' heights will vary according to one important UI element
// In a subclass of UITableViewCell:
- (void)awakeFromNib {
// http://stackoverflow.com/a/14127936/2199136
[super awakeFromNib];
[self layoutIfNeeded];
self.originalSize = self.bounds.size;
self.originalimportantUIElementSize = self.originalimportantUIElement.bounds.size;
}
- (CGSize)dynamicCellSize {
// http://stackoverflow.com/a/14127936/2199136
[self configureCell];
CGSize importantUIelementSize = self.importantUIelement.intrinsicContentSize;
CGSize size = self.originalSize; // set in awakeFromNib after layoutSubviewsIfNeeded
size.width += importantUIelementSize.width - self.originalimportantUIElementSize.width; // original again set in awakeFromNib after layoutSubviewsIfNeeded
size.height += importantUIelementSize.height - self.originalimportantUIElementSize.height;
return size;
}
// Then in table view delegate:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = [self cellIdentifierForIndexPath:indexPath];
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier]; // you could store the cell in a property here for efficiency
...
CGSize size = [cell dynamicCellSize];
return size.height;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment