1. 程式人生 > >iOS WKWebView添加網頁加載進度條(轉)

iOS WKWebView添加網頁加載進度條(轉)

err -i original 網頁 star span rop remove ram

一、效果展示

技術分享
WKWebProgressViewDemo.gif

二、主要步驟

1.添加UIProgressView屬性

@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIProgressView *progressView;

2.初始化progressView

- (void)viewDidLoad {
    [super viewDidLoad];    
    //進度條初始化
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 20, [[UIScreen mainScreen] bounds].size.width, 2)];
    self.progressView.backgroundColor = [UIColor blueColor];
    //設置進度條的高度,下面這句代碼表示進度條的寬度變為原來的1倍,高度變為原來的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view addSubview:self.progressView];
}

3.添加KVO,WKWebView有一個屬性estimatedProgress,就是當前網頁加載的進度,所以監聽這個屬性。

[self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

4.在監聽方法中獲取網頁加載的進度,並將進度賦給progressView.progress

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.wkWebView.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一個簡單的動畫,將progressView的Height變為1.4倍,在開始加載網頁的代理中會恢復為1.5倍
             *動畫時長0.25s,延時0.3s後開始動畫
             *動畫結束後將progressView隱藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;

            }];
        }    
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

5.在WKWebViewd的代理中展示進度條,加載完成後隱藏進度條

//開始加載
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"開始加載網頁");
    //開始加載網頁時展示出progressView
    self.progressView.hidden = NO;
    //開始加載網頁的時候將progressView的Height恢復為1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被網頁擋住
    [self.view bringSubviewToFront:self.progressView];
}

//加載完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加載完成");
    //加載完成後隱藏progressView
    //self.progressView.hidden = YES;
}

//加載失敗
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加載失敗");
    //加載失敗同樣需要隱藏progressView
    //self.progressView.hidden = YES;
}

6.在dealloc中取消監聽

- (void)dealloc {
    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}

三、github 代碼地址

請戳這裏查看demo

iOS WKWebView添加網頁加載進度條(轉)