I know that there is a similar question, but I'd like to give more hints about how I tried to achieve that since the original question doesn't give any advice.
I have a UITableViewCell
as a subview of the contentView there is a UICollectionView
, I'd like to have the cell height in function of the collectionview contentSize
, the table view cell is the collection view delegate and datasource.
The collection view should be fixed without scrolling possibilities in a vertical flow and it should adapt its height on the number of cell lines.
To do that I've tried to used the same technique I use with common table view cells. I create a fake cell and keep a reference to it, then in the method - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
I feed the cell with the data that it should display and then ask to its height for compressed size.
Something like that:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGSize size = CGSizeZero;
NSDictionary * data = self.data[indexPath.row];
if (data[KEY_CELL_IDENTIFIER] == CellIdentifierPost) {
NSNumber * cachedHeight = [self.heightCaches objectForKey:[(PostObject*)data[KEY_CELL_DATA] postObjectId]];
if (cachedHeight) {
return (CGFloat)[cachedHeight doubleValue];
}
[_heightCell configureCellWith:data[KEY_CELL_DATA]];
size = [_heightCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
[self.heightCaches setObject:@(size.height) forKey:[(PostObject*)data[KEY_CELL_DATA] postObjectId]];
}
else if (data[KEY_CELL_IDENTIFIER] == CellIdentifierComment){
size = (CGSize) {
.width = NSIntegerMax,
.height = 160.f
};
}
else {
size = (CGSize) {
.width = NSIntegerMax,
.height = 50.f
};
}
return size.height;
}
This method works really fine for the other cells, but not for this one, the result is a totally compressed cell with almost a zero height.
The problem seems to be due to the inner cells placement. Even if after feeding the data I force the collection view to reload data, it seems to never call the -collectionView:cellForItemAtIndexPath:
this happens probably because the cell is still not displayed.
Is there a work around?