#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()
@property (weak, nonatomic) WKWebView *webView;
@property (weak, nonatomic) CALayer *progresslayer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
WKWebView *webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
// 添加监听
[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
self.webView = webView;
[self.view addSubview:webView];
self.title = @"加载中...";
//进度条
UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), 3)];
progress.backgroundColor = [UIColor clearColor];
[self.view addSubview:progress];
CALayer *layer = [CALayer layer];
layer.frame = CGRectMake(0, 0, 0, 3);
layer.backgroundColor = [UIColor blueColor].CGColor;
[progress.layer addSublayer:layer];
self.progresslayer = layer;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"estimatedProgress"]) {
self.progresslayer.opacity = 1;
if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {
return;
}
self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
if ([change[@"new"] floatValue] == 1) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.opacity = 0;
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
});
}
} else if ([keyPath isEqualToString:@"title"]) {
if (object == self.webView) {
self.title = self.webView.title;
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}}
}
- (void)dealloc{
// 移除监听
[(WKWebView *)self.view removeObserver:self forKeyPath:@"estimatedProgress"];
[(WKWebView *)self.view removeObserver:self forKeyPath:@"title"];
}
[OC]WKWebView加载进度条
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Swift版本点击这里欢迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
- WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一种新的协议。它实...