iOS 精準(zhǔn)獲取webView內(nèi)容高度并自適應(yīng)高度

參考文檔:
iOS【終極方案】精準(zhǔn)獲取webView內(nèi)容高度,自適應(yīng)高度
iOS精準(zhǔn)獲取webView內(nèi)容高度,自適應(yīng)高度(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;
        //這個(gè)屬性不加,webview會(huì)顯示很大.
        _webView.scalesPageToFit = YES;
        _webView.opaque =NO;
        //預(yù)先加載url
        [_webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/api/product/piclist?item_id=%@",SERVER,self.model.itemid]]]];
        //給webView的scrollView的contentSize屬性添加監(jiān)聽(tīng),每當(dāng)內(nèi)容發(fā)生變化,contentSize一定會(huì)跟著變,捕獲這個(gè)變動(dòng)
//        [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-監(jiān)聽(tīng)的處理1、監(jiān)聽(tīng)tableview偏移(控制導(dǎo)航的透明度)2、監(jiān)聽(tīng)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;
        //設(shè)置一個(gè)顏色并轉(zhuǎn)化為圖片
        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"]) {
         //通過(guò)JS代碼獲取webview的內(nèi)容高度
        //self.webViewHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
       //通過(guò)webview的contentSize獲取內(nèi)容高度
       //self.webViewHeight = [self.showWebView.scrollView contentSize].height;
        CGRect frame = self.webView.frame;
        //通過(guò)webview的contentSize獲取內(nèi)容高度
        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的內(nèi)容高度,會(huì)導(dǎo)致獲取的內(nèi)容高度不精確,因?yàn)閣ebViewDidFinishLoad代理方法被調(diào)用時(shí),頁(yè)面并不一定完全展現(xiàn)完成,可能有圖片還未加載出來(lái),導(dǎo)致此時(shí)獲取的高度是并不是最終高度,過(guò)會(huì)兒圖片加載出來(lái)后,瀏覽器會(huì)重新排版,而我們?cè)谶@之前給了一個(gè)錯(cuò)誤高度,導(dǎo)致顯示異常。所以需要在監(jiān)聽(tīng)到webView.scrollView的contentSize變化時(shí),獲取到的webView的內(nèi)容高度才時(shí)精確的。

#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、實(shí)例化創(chuàng)建webView的時(shí)候,必須設(shè)置frame值,否值不顯示

// 高度隨便多少,可以為1,但不能為0,為0 則webView不顯示
_webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,1)];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 1、通過(guò)CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽(yáng)明AI閱讀 16,208評(píng)論 3 119
  • 上周我用笑來(lái)老師給出的終極問(wèn)題“什么是最重要”,思考了在選擇工作中什么是重要的。具體可見(jiàn)文章,選擇工作時(shí)什么是最重...
    vinlson閱讀 2,142評(píng)論 0 50
  • 殘破的墻邊, 倚著一個(gè)殘破的人。 殘破的人兒, 有著一個(gè)殘破的夢(mèng)。 殘破的夢(mèng)中, 住著一個(gè)殘破的你。 殘破的你矣,...
    凌書(shū)力閱讀 226評(píng)論 0 3

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