UITableViewCell嵌套UIWebView

待我称王封你为后i 2023-10-17 14:10 100阅读 0赞

原文地址点击打开链接

项目需求:UITableViewCell嵌套UIWebView,并且让UIWebView根据内容自适应高度。

1 获取UIWebView高度

  1. - (void)webViewDidFinishLoad:(UIWebView *)webView
  2. {
  3. // 如果要获取webView高度必须在网页加载完成之后获取
  4. // 方法一
  5. CGFloat height = [self.webView sizeThatFits:CGSizeZero].height;
  6. // 方法二
  7. CGFloat height = webView.scrollView.contentSize.height;
  8. // 方法三 (不推荐使用,当webView.scalesPageToFit = YES计算的高度不准确)
  9. CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
  10. }

2 UIWebView加载完成后cell高度的更新,使用通知来实现。

TableViewCell.m

  1. - (void)webViewDidFinishLoad:(UIWebView *)webView
  2. {
  3. CGSize fittingSize = [self.webView sizeThatFits:CGSizeZero];
  4. self.height = fittingSize.height;
  5. self.webView.frame = CGRectMake(0, 0, fittingSize.width, fittingSize.height);
  6. // 用通知发送加载完成后的高度
  7. [[NSNotificationCenter defaultCenter] postNotificationName:@"WEBVIEW_HEIGHT" object:self userInfo:nil];
  8. }

ViewController.m

  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4. // 用于缓存cell高度
  5. self.heightDic = [[NSMutableDictionary alloc] init];
  6. // 注册加载完成高度的通知
  7. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti:) name:@"WEBVIEW_HEIGHT" object:nil];
  8. }
  9. - (void)noti:(NSNotification *)sender
  10. {
  11. TableViewCell *cell = [sender object];
  12. if (![self.heightDic objectForKey:[NSString stringWithFormat:@"%ld",cell.tag]]||[[self.heightDic objectForKey:[NSString stringWithFormat:@"%ld",cell.tag]] floatValue] != cell.height)
  13. {
  14. [self.heightDic setObject:[NSNumber numberWithFloat:cell.height] forKey:[NSString stringWithFormat:@"%ld",cell.tag]];
  15. [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:cell.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
  16. }
  17. }

图片1

3 完整项目工程

https://github.com/YiQieSuiYuan/Demo/tree/master/WebView_cell

4 参考

http://www.jianshu.com/p/e199496a8b8a

发表评论

表情:
评论列表 (有 0 条评论,100人围观)

还没有评论,来说两句吧...

相关阅读

    相关 UIWebView与WKWebView

    UIWebView UIWebView是苹果继承于UIView封装的一个加载web内容的类,它可以加载任何远端的web数据展示在你的页面上,你可以像浏览器一样前进后退刷新等操