【问题标题】:Dynamically set TableCell height based on Webview基于Webview动态设置TableCell高度
【发布时间】:2015-07-30 14:04:52
【问题描述】:

我正在努力调整包含动态高 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
}

但是,由于有多个线程,webViewDidFinishLoad 总是在cellForRowAtIndexPath 之后被调用,并且尝试通过更改webViewDidFinishLoad 中的框架来调整单元格高度到目前为止没有成功。

【问题讨论】:

    标签: ios objective-c uitableview uiwebview


    【解决方案1】:

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

    【讨论】:

    • 虽然 mt81 的解决方案是更好的解决方案,但我必须实现这个,否则我将无法在插入的 HTML 上捕获点击
    【解决方案2】:

    我不想误导您,但如果您需要将静态 HTML 内容打印到视图中,您可以使用 UILabel 和属性字符串。

    像这样:

    NSMutableAttributedString *attributedString;
    NSData *htmlData = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    attributedString = [[NSMutableAttributedString alloc] initWithData:htmlData                                                        
                                                               options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
                                                    documentAttributes:nil
                                                                 error:nil];
    someLabel.attributedText = attributedString;
    

    如果你使用这个,你不需要等待WebView加载,你可以使用标准的方法来计算高度。

    【讨论】:

    • 这个解决方案的一个问题是我不了解文本(我得到什么内容)并且 html sn-p 可以包含链接。据我所见,使用标签处理可点击链接要复杂得多。但当然定位要容易得多。
    猜你喜欢
    • 1970-01-01
    • 2017-06-01
    • 2021-11-10
    • 2019-10-09
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    相关资源
    最近更新 更多