iOS 精準獲取webView內容高度並自適應高度

weixin_34321977發表於2018-11-23

參考文件:
iOS【終極方案】精準獲取webView內容高度,自適應高度
iOS精準獲取webView內容高度,自適應高度(cell篇)

#pragma mark-懶載入webView
-(UIWebView *)webView{
    if (!_webView) {
//        _webView = [[UIWebView alloc] init];
        // 1隨便多少,不能為0
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,1)];
        _webView.delegate = self;
        _webView.scrollView.scrollEnabled = NO;
        //這個屬性不加,webview會顯示很大.
        _webView.scalesPageToFit = YES;
        _webView.opaque =NO;
        //預先載入url
        [_webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/api/product/piclist?item_id=%@",SERVER,self.model.itemid]]]];
        //給webView的scrollView的contentSize屬性新增監聽,每當內容發生變化,contentSize一定會跟著變,捕獲這個變動
//        [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:nil];
        [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    }
    return _webView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
}
#pragma mark - UIWebView Delegate Methods
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
     [[MBProgressHUD HUDForView:self.view] removeFromSuperview];
//    //獲取到webview的高度
////    CGFloat height =  [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"]floatValue];
//    self.webViewHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
//    CGSize webSize = [webView sizeThatFits:CGSizeZero];
//    [webView mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.height.equalTo(@(webSize.height));
//    }];
//    cellhight = self.webViewHeight;
 //   [self.tableView reloadData];

}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidStartLoad");
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nonnull NSError *)error
{
    NSLog(@"didFailLoadWithError===%@", error);
    isOpen = !isOpen;
     [[MBProgressHUD HUDForView:self.view] removeFromSuperview];
       [AMShowMessage showMessage:@"載入失敗" withDuration:2];
    [self.tableView reloadData];
}
#pragma mark-監聽的處理1、監聽tableview偏移(控制導航的透明度)2、監聽webView.scrollView的contentSize的變化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
   
    if ([keyPath isEqualToString:@"contentOffset"])
    {
      
          UIButton *  bottom = [self.view viewWithTag:1000];
        CGPoint offset = [change[NSKeyValueChangeNewKey] CGPointValue];
        CGFloat alpha = offset.y/NAVIGATION_BAR_HEIGHT >1.0f ? 1:offset.y/NAVIGATION_BAR_HEIGHT;
        //設定一個顏色並轉化為圖片
        UIImage *image = [self imageWithColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:alpha]];
        
        self.navigationView.image = image;
        self.navigationController.navigationBar.alpha = alpha;
        self.topView.backgroundColor = [UIColor colorWithPatternImage:image];
        self.topView.alpha = alpha;

        if (offset.y > 0) {
        self.navigationView.isAlphZero = NO;
            bottom.hidden = NO;
            
        }else{
            self.navigationView.isAlphZero = YES;
             bottom.hidden = YES;
        }
        
    }


    if ([keyPath isEqualToString:@"contentSize"]) {
         //通過JS程式碼獲取webview的內容高度
        //self.webViewHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
       //通過webview的contentSize獲取內容高度
       //self.webViewHeight = [self.showWebView.scrollView contentSize].height;
        CGRect frame = self.webView.frame;
        //通過webview的contentSize獲取內容高度
        frame.size.height = self.webView.scrollView.contentSize.height;
        
        //這裡獲取webView的高度
        _webViewHeight = frame.size.height;
        NSLog(@"%f",frame.size.height);

        cellhight =_webViewHeight;
        CGSize webSize = [self.webView sizeThatFits:CGSizeZero];
        [self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@(webSize.height));
        }];

        [self.tableView reloadData];
    }
}

反思:
1、在webViewDidFinishLoad方法中獲取webView的內容高度,會導致獲取的內容高度不精確,因為webViewDidFinishLoad代理方法被呼叫時,頁面並不一定完全展現完成,可能有圖片還未載入出來,導致此時獲取的高度是並不是最終高度,過會兒圖片載入出來後,瀏覽器會重新排版,而我們在這之前給了一個錯誤高度,導致顯示異常。所以需要在監聽到webView.scrollView的contentSize變化時,獲取到的webView的內容高度才時精確的。

#pragma mark - UIWebView Delegate Methods
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
     [[MBProgressHUD HUDForView:self.view] removeFromSuperview];
//    //獲取到webview的高度
////    CGFloat height =  [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"]floatValue];
//    self.webViewHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
//    CGSize webSize = [webView sizeThatFits:CGSizeZero];
//    [webView mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.height.equalTo(@(webSize.height));
//    }];
//    cellhight = self.webViewHeight;
    [self.tableView reloadData];

}

2、例項化建立webView的時候,必須設定frame值,否值不顯示

// 高度隨便多少,可以為1,但不能為0,為0 則webView不顯示
_webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,1)];

相關文章