iOS WKWebView新增進度條02

碼鋒窩發表於2017-03-06
之前寫了一個是關於webview新增進度條的,現在補一個WKWebView進度條。
//新增一個全域性屬性
@property(nonatomic,strong)CALayer *progresslayer;
 
//viewDidLoad裡新增監聽
[_webViewaddObserver:selfforKeyPath:@"estimatedProgress"options:NSKeyValueObservingOptionNewcontext:nil];
 
//進度條
 UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 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 greenColor].CGColor;
    [progress.layer addSublayer:layer];
    self.progresslayer = layer;
 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progresslayer.opacity = 1;
        //不要讓進度條倒著走...有時候goback會出現這種情況
        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{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
//移除監聽
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

相關文章