Created
July 9, 2015 11:01
-
-
Save tjosten/fdefe25ee82bec69a560 to your computer and use it in GitHub Desktop.
Creating UITableViewCells with dynamic height based upon Auto Layout constraints with iOS 8
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
# pragma mark - Cell Setup | |
- (void)setUpCell:(DynamicTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { | |
cell.label.text = [self.dataSource objectAtIndex:indexPath.row]; | |
} | |
# pragma mark - UITableViewControllerDelegate | |
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { | |
return 1; | |
} | |
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
return self.dataSource.count; | |
} | |
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
DynamicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; | |
[self setUpCell:cell atIndexPath:indexPath]; | |
return cell; | |
} | |
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { | |
static DynamicTableViewCell *cell = nil; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; | |
}); | |
[self setUpCell:cell atIndexPath:indexPath]; | |
return [self calculateHeightForConfiguredSizingCell:cell]; | |
} | |
- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell { | |
[sizingCell layoutIfNeeded]; | |
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; | |
return size.height; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment