今天看到有人問(wèn)UITableView嵌套WKWebView的問(wèn)題乍丈,恰好最近公司有這么一個(gè)需求,cell上嵌套網(wǎng)頁(yè)并能點(diǎn)擊網(wǎng)頁(yè)上展開(kāi)收回按鈕佑稠,恰好我做了镀梭。cell上嵌套網(wǎng)頁(yè)問(wèn)題很多铐伴,特別是嵌套WKWebView,網(wǎng)上的解決方案也很多疑故,但是很多都有問(wèn)題杠览,既然做完了那就分享下吧。
- (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監(jiān)聽(tīng)contentSize纵势,你們也可以改成用系統(tǒng)方法
[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 );
//因?yàn)閃KWebView的contentSize在加載的時(shí)候是不斷變化的踱阿,可能高度已經(jīng)獲取出來(lái)了但是還在刷新,然后又獲取到相同的高度钦铁,所以當(dāng)高度相同的時(shí)候我們不刷新tableview软舌,高度不相同的時(shí)候我們刷新tableView獲取最新值
if (number != height) {
[self.tableView reloadData];
}
number = height;
_webViewHeight = height;//_webViewHeight全局更新的WKWebView的高度
}];
}];
}
看下效果如何
展開(kāi)前
展開(kāi)前.jpg
展開(kāi)后
展開(kāi)后.jpg
完美解決tableViewcell上嵌套WKWebView并能自由點(diǎn)擊展開(kāi)收回按鈕_