UITableViewCell嵌套WKWebView

今天看到有人问UITableView嵌套WKWebView的问题,恰好最近公司有这么一个需求,cell上嵌套网页并能点击网页上展开收回按钮,恰好我做了。cell上嵌套网页问题很多,特别是嵌套WKWebView,网上的解决方案也很多,但是很多都有问题,既然做完了那就分享下吧。

- (void)viewDidLoad {
 webViewRace = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, YMWidth(320), 200)];
 webViewRace.backgroundColor = [UIColor clearColor];
 webViewRace.opaque = NO;
 webViewRace.userInteractionEnabled = YES;
 webViewRace.scrollView.bounces = NO;       
 [webViewRace sizeToFit];   
 webViewRace.UIDelegate = self;
 webViewRace.navigationDelegate = self;
 NSString *url =@“http://120.24.215.97:9998/marathon/web/matchIndex.html?id=388&lang=zh-cn”;
 [webViewRace loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *cell = [tableView        dequeueReusableCellWithIdentifier:@"WebViewCell" forIndexPath:indexPath];                 
   cell.selectionStyle = UITableViewCellSelectionStyleNone;
   cell.backgroundColor = [UIColor colorWithHexString:@"ffffff"];
//只添加一次
   if (url1 != nil) {
         if (isC == NO) {
             isC = YES;
             [cell addSubview:webViewRace];
             }
   }
    return cell;

}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    __block CGFloat number = 0;  
//我这里用的RAC监听contentSize,你们也可以改成用系统方法               
[RACObserve(webViewRace.scrollView, contentSize) subscribeNext:^(id  _Nullable x) {
                        
[webViewRace evaluateJavaScript:@"document.documentElement.offsetHeight"
                                     completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSNumber *height1 = result;
CGFloat height = [height1 floatValue];
// do with the height
webViewRace.frame = CGRectMake(0, YMHeight(20), YMWidth(320), height );
//因为WKWebView的contentSize在加载的时候是不断变化的,可能高度已经获取出来了但是还在刷新,然后又获取到相同的高度,所以当高度相同的时候我们不刷新tableview,高度不相同的时候我们刷新tableView获取最新值                              
if (number != height) {
[self.tableView reloadData];
}
number = height;
_webViewHeight = height;//_webViewHeight全局更新的WKWebView的高度
}];
}];
}

看下效果如何
展开前


展开前.jpg

展开后


展开后.jpg

完美解决tableViewcell上嵌套WKWebView并能自由点击展开收回按钮_

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 今天一直在网上找如何在UITableViewCell嵌套WKWebView,问题还挺多了,最后还是在stac...
    断忆残缘阅读 11,779评论 10 7
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,256评论 4 61
  • 文/笔芯儿 灵性的指引与被发现 最近我经常提到于文博老师,因为我是认识他之后,才有了明确的成长方向——万物改变由我...
    01零壹阅读 5,836评论 4 8
  • 呼吸、发呆、打呵欠、打瞌睡、冥想、倾听、沐浴、品尝、睡觉、享受当下…… 看似没意义,其实有着巨大的人生的美感和意义...
    湘女夺秦阅读 3,514评论 0 0
  • 社群打卡从2016年热起来,以初入职场的年轻人为主,年龄上下浮动一定范围,基本上是价值观初形成但还不成熟不系统、又...
    曾小藩阅读 3,980评论 0 0