协议:WKNavigationDelegate
@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIProgressView *progressView;// 设置加载进度条
- (void)createPro{
// 创建进度条
if (!self.progressView) {
self.progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
self.progressView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 1);
[self.progressView setTrackTintColor:[UIColor clearColor]];
self.progressView.progressTintColor = [UIColor blueColor];// 设置进度条的色彩
[self.wkWebView addSubview:self.progressView];
}
[self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if (object == self.wkWebView) {
[self.progressView setAlpha:1.0f];
static double progress = 0;
if (progress<self.wkWebView.estimatedProgress) {
progress = self.wkWebView.estimatedProgress;
}
[self.progressView setProgress:progress animated:YES];
if(self.wkWebView.estimatedProgress >= 1.0f) {
[UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.progressView setAlpha:0.0f];
} completion:^(BOOL finished) {
[self.progressView setProgress:0.0f animated:NO];
}];
}
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark - WKNavigationDelegate
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSLog(@"加载完成");
// 禁止放大缩小
NSString *injectionJSString = @"var script = document.createElement('meta');"
"script.name = 'viewport';"
"script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
[webView evaluateJavaScript:injectionJSString completionHandler:nil];
//计算出webView滚动视图滚动的高度
[webView evaluateJavaScript:@"document.body.scrollWidth"completionHandler:^(id _Nullable result,NSError * _Nullable error){
CGFloat ratio = CGRectGetWidth(self.wkWebView.frame) /[result floatValue];
[webView evaluateJavaScript:@"document.body.scrollHeight"completionHandler:^(id _Nullable result,NSError * _Nullable error){
NSLog(@"scrollHeight计算高度:%.2f",[result floatValue]*ratio);
CGFloat newHeight = [result floatValue]*ratio;
//[self resetWebViewFrameWithHeight:newHeight];
}];
}];
}