[英]Dynamically set TableCell height based on Webview
I'm struggling with adjusting the height of a UITableViewCell that contains a dynamically high WebView. 我正在努力调整包含动态高WebView的UITableViewCell的高度。
- (void) viewDidLoad {
// ...
for (ListItem *item in self.items) {
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
[webView loadHTMLString:item.content baseURL:nil];
[self.webViews addObject: webView]
}
// ...
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// try to calculate height?
return 100.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ListItem *listItem = (self.items) [indexPath.row];
[tableView registerNib:[UINib nibWithNibName:@"AccordionCell" bundle:nil] forCellReuseIdentifier:@"MyCustomCell"];
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCustomCell"];
// [...] do something with cell
UIWebView *webView = [self.webViews objectAtIndex: indexPath.row];
webView.frame = CGRectMake(0, 0, cell.mainView.frame.size.width, 0);
[cell.mainView addSubview: webView];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *height = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('mainframe').offsetHeight;"];
// [...] adjust height of web view by using the content's height
}
However, due to multiple threads the webViewDidFinishLoad
always gets called after cellForRowAtIndexPath
, and trying to adjust the cells height by changing its frame in the webViewDidFinishLoad
did not succeed so far. 但是,由于有多个线程,
webViewDidFinishLoad
总是在cellForRowAtIndexPath
之后调用webViewDidFinishLoad
,并且webViewDidFinishLoad
,尝试通过更改webViewDidFinishLoad
框架来调整单元格的高度没有成功。
将这些高度存储在NSMutableArray方法中的webViewDidFinishLoad:
方法中,然后最后重新加载UITableView
的数据,并根据indexPath.Row
在heightForRowAtIndexPath
使用这些高度。
I don't want to mislead you, but if you need to print static HTML content into a view you can use a UILabel and an attributed string. 我不想误导您,但是如果您需要将静态HTML内容打印到视图中,则可以使用UILabel和属性字符串。
Like that : 像那样 :
NSMutableAttributedString *attributedString;
NSData *htmlData = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
attributedString = [[NSMutableAttributedString alloc] initWithData:htmlData
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
documentAttributes:nil
error:nil];
someLabel.attributedText = attributedString;
If you use this, you don't need to wait for the WebView to load, you can use standard methods in order to calculate the height. 如果使用此方法,则无需等待WebView加载,可以使用标准方法来计算高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.