UITableView含有UIWebView或WKWebView,如何正確顯示webView高度

2018年7月14日
一.tableView上webView(UIWebView和 WKWebView)高度運算不正確解決
第一步:設(shè)置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;
}

第二步:用通知監(jiān)聽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回調(diào)
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [self addObserverForWebViewContentSize];
     //5s后移除( 5s內(nèi)先離開界面也是會調(diào)用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內(nèi)先離開界面也是會調(diào)用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監(jiān)聽
[原因:內(nèi)容變化,contentSize也會變化,所以最后一次肯定是加載好的]
實現(xiàn)(viewController)
1:創(chuàng)建監(jiān)聽

//webView高度相關(guān)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;
        /* 獲取網(wǎng)頁現(xiàn)有的frame*/
        CGRect frame = _answerWV.frame;
        /* 改版WebView的高度*/
        frame.size.height = height;
        /* 重新設(shè)置網(wǎng)頁的frame*/
        _answerWV.frame = frame;
        [self.tableView beginUpdates];
// 注意不需要調(diào)用heighforRow接口,該復(fù)制會自動修改其高度
        [self.tableView setTableHeaderView:_answerWV];
//         [self.tableView setTableFooterView:_answerWV];
        [self.tableView endUpdates];
    }
}

二.場景2 不太推薦(每個Cell都還有一個UIWebView)
如果cell少于10個可以用如下方法(大于會有點問題:原因就是判斷所有webVIew計算完成的條件,應(yīng)該是重用問題導致,cellforrowatindexpath 執(zhí)行次數(shù)少于numberOfRowsInSection個數(shù)l)
另外該方法不太推薦的原因:webViewDidFinishLoad執(zhí)行后,頁面不一定加載完成,可能有些圖片還沒顯示出來

1.基本原理:tableView reloadData 調(diào)用兩次[加變量_webView_fistload控制,避免進入死循環(huán)]。第一次,主要是計算webView的高度,第二次才是正在的reloadData。

2.具體實現(xiàn)如下:
2.1 controller 和cell實現(xiàn)

#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
{
    /* 網(wǎng)頁是含有UIScrollview 對象,我們通過獲取 webView的ScrollvIew的內(nèi)容的高度來獲取webView的高度,同事達到高度適配*/
    CGFloat height = [webView.scrollView contentSize].height;
    /* 設(shè)置frame*/
    CGRect frame = CGRectMake(xPos, yPos, width, height);
    /* 改版WebView的高度*/
    frame.size.height = height;
    /* 重新設(shè)置網(wǎng)頁的frame*/
    _answerWV.frame = frame;
    //block回調(diào)
    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];
    /* 獲取網(wǎng)頁現(xiàn)有的frame*/
    CGRect frame = webView.frame;
    frame.size.height = fittingSize.height;

如果您發(fā)現(xiàn)本文對你有所幫助,如果您認為其他人也可能受益,請把它分享出去。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容