简体   繁体   English

设置带有UIWebView的UITableViewCell的高度

[英]Setting height for UITableViewCell with UIWebView inside

I have a UIWebView inside my custom UITableViewCells . 我的自定义UITableViewCells内部有一个UIWebView 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. 问题是我不太了解如何动态调整UITableViewCell单元的大小,因为单元中的webview需要先渲染才能知道webview的高度。

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. CustomCell.m符合UIWebViewDelegate并且在其中的Webview完成加载后,将使用委托方法返回其自身的高度。

- (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: 然后, TableViewController.m符合单元格的委托,并通过执行以下操作来重绘:

- (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... 一些单元格似乎是正确的高度,但是其中许多单元格最终的高度为0 ...

remove : 去掉 :

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

add : 添加:

[self.tableView reloadData];




This is Apple Documents: 这是Apple Documents:
beginUpdates beginUpdates
reloadData reloadData

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM