0

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...

Apollo
  • 8,874
  • 32
  • 104
  • 192
  • @matt I'm not sure that would work. For one thing, calling reloadData would cause each cell to re-render its webview. Are you available for a quick SO chat session? I think it would be faster to explain my specific situation there rather than here in the comment sections. http://chat.stackoverflow.com/rooms/123193/webview – Apollo Sep 13 '16 at 01:12
  • @matt why not just call `beginUpdates` and `endUpdates` though, since this calls `heightForRowAtIndexPath`? – Apollo Sep 13 '16 at 01:37

1 Answers1

0

remove :

[self.tableView beginUpdates];
[self.tableView endUpdates];

add :

[self.tableView reloadData];




This is Apple Documents:
beginUpdates
reloadData

https://stackoverflow.com/a/8174094/2530660

Community
  • 1
  • 1
LEETAEJUN
  • 186
  • 9