Last active
August 29, 2015 14:01
-
-
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
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
// 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