UITableView含有UIWebView或WKWebView

作者: wangyu2488 | 来源:发表于2017-06-13 10:35 被阅读0次

2018年7月14日
一.tableView上webView(UIWebView和 WKWebView)高度运算不正确解决
第一步:设置webview滚动属性为空,这样通知的时候肯定会获取正确的高度
_webView.scrollView.scrollEnabled = NO;

- (WKWebView *)webView {
    if (_webView == nil) {
        CGRect frame = CGRectMake(0, 0, HHBWIDTH, 0);
        _webView.backgroundColor = [UIColor redColor];
        _webView = [[WKWebView alloc] initWithFrame:frame];
        _webView.navigationDelegate = self;
        //**********
        _webView.scrollView.scrollEnabled = NO;
    }
    return _webView;
}

第二步:用通知监听webView的高度

#define contentSizeKey @"contentSize"
- (void)addObserverForWebViewContentSize {
    [self.webView.scrollView addObserver:self forKeyPath:contentSizeKey options:NSKeyValueObservingOptionNew context:nil];
}
- (void)removeObserverForWebViewContentSize {
    [self.webView.scrollView removeObserver:self forKeyPath:contentSizeKey];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:contentSizeKey]) {
        CGFloat height = self.webView.scrollView.contentSize.height;
        if (height > _webHeight) {
            _webHeight = height;
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *iden = @"webViewcell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];
        }
        CGRect frame = self.webView.frame;
        frame.size.height = _webHeight;
        self.webView.frame = frame;
        [cell addSubview:self.webView];
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return _webHeight;
    } 
     return 0.0;
}

//wk回调
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [self addObserverForWebViewContentSize];
     //5s后移除( 5s内先离开界面也是会调用remove 和 dealloc的)【如果5s也不够,可以直接放在dealloc里面做也可以】
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self removeObserverForWebViewContentSize];

    });
    
}

ps:

日志  5s内先离开界面也是会调用remove 和 dealloc的
[07:53:41] -[RNMissionDetailViewController addObserverForWebViewContentSize] [第271行] add
[07:53:41] -[RNMissionDetailViewController removeObserverForWebViewContentSize] [第276行] remove
[07:53:41] -[RNMissionDetailViewController dealloc] [第401行] dealloc

2017年6月13日
一.场景1(tableView里面 最多2个UIWebView)推荐用KVO监听
[原因:内容变化,contentSize也会变化,所以最后一次肯定是加载好的]
实现(viewController)
1:创建监听

//webView高度相关key
#define contentSizeKey @"contentSize"
[self.answerWV.scrollView addObserver:self forKeyPath:contentSizeKey options:NSKeyValueObservingOptionNew context:nil];


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:contentSizeKey]) {
        
        CGFloat height = [_answerWV.scrollView contentSize].height;
        /* 获取网页现有的frame*/
        CGRect frame = _answerWV.frame;
        /* 改版WebView的高度*/
        frame.size.height = height;
        /* 重新设置网页的frame*/
        _answerWV.frame = frame;
        [self.tableView beginUpdates];
// 注意不需要调用heighforRow接口,该复制会自动修改其高度
        [self.tableView setTableHeaderView:_answerWV];
//         [self.tableView setTableFooterView:_answerWV];
        [self.tableView endUpdates];
    }
}

二.场景2 不太推荐(每个Cell都还有一个UIWebView)
如果cell少于10个可以用如下方法(大于会有点问题:原因就是判断所有webVIew计算完成的条件,应该是重用问题导致,cellforrowatindexpath 执行次数少于numberOfRowsInSection个数l)
另外该方法不太推荐的原因:webViewDidFinishLoad执行后,页面不一定加载完成,可能有些图片还没显示出来

1.基本原理:tableView reloadData 调用两次[加变量_webView_fistload控制,避免进入死循环]。第一次,主要是计算webView的高度,第二次才是正在的reloadData。

2.具体实现如下:
2.1 controller 和cell实现

#import "RequiredSkillViewController.h"
@interface RequiredSkillViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    BOOL _webView_fistload;
}

- (void)loadData{
    WS(weakSelf)
    [ShuLanHttps requestShuLanPost:dict funItem:@"[article.qa](http://article.qa)" view:self.view success:^(NSDictionary *dic) {
        //第一次加载
        [weakSelf reloadWebView];
       
    } error:^(NSDictionary *dic) {
    } failure:^{    
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RequiredSkillTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:kSkillCell forIndexPath:indexPath];
    WS(weakSelf)
    cell.getWebViewHeight = ^(CGFloat height){
        weakSelf.webCellHeightArr[indexPath.row] = @(height);
        //第二次加载,web页面全部显示完成
        if (weakSelf.webCellHeightArr.count >= weakSelf.dataArray.count) {
            if (_webView_fistload == NO ) {
                [weakSelf.tableView reloadData];
                _webView_fistload = YES;
            }
         }
    };
        
   RequiredSkillModel * model = self.dataArray[indexPath.row];
   cell.model = model;
   return cell;   
 }

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    NSInteger row = indexPath.row;
    //给个默认值
    CGFloat height = requiredSkill_aImg_uMargin + requiredSkill_img_height + requiredSkill_aImg_dMargin;
   //如果计算完成用新的值
    if (_webCellHeightArr.count >= _dataArray.count && row < _webCellHeightArr.count ) {
        height = [_webCellHeightArr[row] floatValue];
    }
    return height;
}

@interface RequiredSkillTableViewCell : UITableViewCell<UIWebViewDelegate>
@property (nonatomic, copy) blk_Float getWebViewHeight;
@end

#import "RequiredSkillTableViewCell.h"
@implementation RequiredSkillTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
         ///
        [self.contentView addSubview: self.answerWV];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return  self;
}

- (void)setModel:(RequiredSkillModel *)model{
   ///
    NSString *scaleHeader =@"<head><meta name=\"viewport\" content=\"initial-scale=1,width=self.view.frame.size.width, maximum-scale=2, minimum-scale=1, user-scalable=yes\"><style>img{max-width: 100%; width:auto; height:auto;}</style><style>*{max-width:100%;max-height:100%}</style></head>";
    NSString *htmlContent = [NSString stringWithFormat:@"<html>%@<body><p style=\"word-break:break-all\">%@</p></body></html>",scaleHeader,model.a];

    [_answerWV loadHTMLString:htmlContent baseURL:nil];
}

- (UIWebView *)answerWV{
    if (_answerWV == nil) {
        _answerWV = [[UIWebView alloc] initWithFrame:CGRectZero];
        _answerWV.delegate = self;
        _answerWV.scrollView.scrollEnabled = NO;
    }
    _answerWV.backgroundColor = [UIColor redColor];
    return _answerWV;
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    /* 网页是含有UIScrollview 对象,我们通过获取 webView的ScrollvIew的内容的高度来获取webView的高度,同事达到高度适配*/
    CGFloat height = [webView.scrollView contentSize].height;
    /* 设置frame*/
    CGRect frame = CGRectMake(xPos, yPos, width, height);
    /* 改版WebView的高度*/
    frame.size.height = height;
    /* 重新设置网页的frame*/
    _answerWV.frame = frame;
    //block回调
    self.getWebViewHeight(height);
}

三.场景3(像场景2这种,建议直接用一个webVIew搞点,可以用本地H5代码组装)

四.补充获取webview高度的方法
1.方法1

CGFloat height = [_answerWV.scrollView contentSize].height;

2.方法2

CGFloat webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

3.方法3

    CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
    /* 获取网页现有的frame*/
    CGRect frame = webView.frame;
    frame.size.height = fittingSize.height;

如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。

相关文章

网友评论

    本文标题:UITableView含有UIWebView或WKWebView

    本文链接:https://www.haomeiwen.com/subject/bfhdqxtx.html