WKWebView添加进度条

1.导入头文件

#import <WebKit/WebKit.h>

2.创建WKWebView和ProcessView, 并且添加观察者,代理WKUIDelegate,WKNavigationDelegate

@property (strong, nonatomic) WKWebView *webView;

@property (strong, nonatomic) UIProgressView *progressView;

- (void)viewDidLoad {

[super viewDidLoad];

self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];

self.webView.UIDelegate = self;

self.webView.navigationDelegate = self;

[self.view addSubview:self.webView];

self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame),2)];

[self.view addSubview:self.progressView];

[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];

[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];

}

3. 实现代理方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context

{

if ([keyPath isEqual: @"estimatedProgress"] && object == self.webView) {

[self.progressView setAlpha:1.0f];

[self.progressView setProgress:self.webView.estimatedProgress animated:YES];

if(self.webView.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];

}

}

4.移除观察者

- (void)dealloc {

[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];

[self.webView setNavigationDelegate:nil];

[self.webView setUIDelegate:nil];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容