天天看點

ios用戶端學習-WKWebView中圖檔适應螢幕并擷取WKWebView高度

WKWebView中圖檔适應螢幕并擷取WKWebView高度

//

//初始化

  • (void)initwebView:(CGRect)frame {

    if (!self.webView) {

    self.webView = [[WKWebView alloc] init];

    //以下代碼适配大小

    NSString *jScript = @“var meta = document.createElement(‘meta’); meta.setAttribute(‘name’, ‘viewport’); meta.setAttribute(‘content’, ‘width=device-width’); document.getElementsByTagName(‘head’)[0].appendChild(meta);”;

    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
      WKUserContentController *wkUController = [[WKUserContentController alloc] init];
      [wkUController addUserScript:wkUScript];
      
      WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
      wkWebConfig.userContentController = wkUController;
      
      self.webView = [[WKWebView alloc] initWithFrame:frame configuration:wkWebConfig];
      [self addSubview:self.webView];
      
      _webView.navigationDelegate = self;
               

    }

    }

#pragma mark - WKNavigationDelegate

// 将html中圖檔适應螢幕

  • (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {

    NSString *[email protected]“var script = document.createElement(‘script’);”

    “script.type = ‘text/javascript’;”

    "script.text = “function ResizeImages() { "

    “var myimg,oldwidth;”

    “var maxwidth = %f;”

    “for(i=0;i <document.images.length;i++){”

    “myimg = document.images[i];”

    “if(myimg.width > maxwidth){”

    “oldwidth = myimg.width;”

    “myimg.width = %f;”

    “}”

    “}”

    “}”;”

    “document.getElementsByTagName(‘head’)[0].appendChild(script);”;

    js=[NSString stringWithFormat:js,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width-15];

    [self.webView evaluateJavaScript:js completionHandler:nil];

    [self.webView evaluateJavaScript:@“ResizeImages();” completionHandler:nil];

    __block CGFloat webViewHeight;

    [self.webView evaluateJavaScript:@“document.body.offsetHeight” completionHandler:^(id _Nullable result,NSError * _Nullable error) {

    //擷取頁面高度,并重置webview的frame

    webViewHeight = [result doubleValue];

    webView.height = webViewHeight;

    [self regetwebviewheight:webViewHeight];

    NSLog(@"%f",webViewHeight);

    }];

    NSLog(@“結束加載”);

    }

// 擷取頁面優化後實際高度

-(void)regetwebviewheight:(CGFloat)webViewHeight{

[self.webView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, webViewHeight)];

[self.webView evaluateJavaScript:@“document.body.offsetHeight” completionHandler:^(id _Nullable result,NSError * _Nullable error) {

//擷取頁面高度

CGFloat height = [result doubleValue];

NSLog(@“頁面高度height”);

}];

}