创建一个继承自wkwebview的类
1、可以创建一个公开的成员变量URL,外部创建的时候传入
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self p_setup];
}
return self;
}
- (void)p_setup{
WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc]init];
conf.preferences = [[WKPreferences alloc]init];
conf.preferences.minimumFontSize = 10;
conf.preferences.javaScriptEnabled = YES;
conf.userContentController = [[WKUserContentController alloc]init];
conf.processPool = [[WKProcessPool alloc]init];
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
[self loadRequest:[NSURLRequest requestWithURL:url]];
self.progresslayer = [[CALayer alloc]init];
self.progresslayer.frame = CGRectMake(0, 0, 20, 2);
self.progresslayer.backgroundColor = [UIColor colorWithRed:32.0/255.0 green:95.0/255.0 blue:144.0/255.0 alpha:1].CGColor;
[self.layer addSublayer:self.progresslayer];
[self addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"estimatedProgress"]) {
self.progresslayer.opacity = 1;
float newValue = [[change objectForKey:@"new"] floatValue];
self.progresslayer.frame = CGRectMake(0, 0, self.frame.size.width * newValue, 2);
if (newValue == 1) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.opacity = 0;
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.frame = CGRectMake(0, 0, 0, 2);
});
}
}
}