简体   繁体   中英

Dynamically set TableCell height based on Webview

I'm struggling with adjusting the height of a UITableViewCell that contains a dynamically high WebView.

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

将这些高度存储在NSMutableArray方法中的webViewDidFinishLoad:方法中,然后最后重新加载UITableView的数据,并根据indexPath.RowheightForRowAtIndexPath使用这些高度。

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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