I have a UIWebView
inside my custom UITableViewCells
. The problem is that I don't quite know how to dynamically size my UITableViewCell
cells since the webview inside the cell needs to render before I can know the webview's height.
My proposed solution is as follows:
CustomCell.m conforms to UIWebViewDelegate
and it returns its own height with delegate method after the webview inside it has finished loading.
- (void)webViewDidFinishLoad:(UIWebView *)webView {
CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
[self.contentWebview setFrameHeight:height];
[self.delegate cellDidFinishLoadingWithCell:self withHeight:height];
}
Then TableViewController.m conforms to the cell's delegate, and redraws by doing something like:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
return [self.heights[[NSString stringWithFormat:@"%i%i",indexPath.section,indexPath.row]] floatValue];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UIWebViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"webview-cell" forIndexPath:indexPath];
MyData *d = self.data[indexPath.section];
[cell setUpCellForData:d];
[cell setDelegate:self];
return cell;
}
- (void)cellDidFinishLoadingWithCell:(LessonTableViewCell *)cell withHeight:(CGFloat)height {
NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];
NSString *key = [NSString stringWithFormat:@"%i%i",indexPath.section,indexPath.row];
if (!self.heights[key]) {
[self.heights setObject:[NSNumber numberWithFloat:height] forKey:key];
}
[self.tableview beginUpdates];
[self.tableview endUpdates];
}
Some cells seem to be the correct height, but many of them end up having a height of 0...