1. 程式人生 > >給wkwebview頂部新增載入進度條!

給wkwebview頂部新增載入進度條!

本篇內容比較簡單,希望給iOS 新手學習,大神請勿吐槽!謝謝。
內容介紹:
1.在webview頂部新增一個進度條UIProgressView。
2.給webVIew新增一個監聽屬性“estimatedProgress”。
3.在監聽事件中,設定ProgressView 的進度等於webview的estimatedProgress。
廢話不多說,直接上程式碼!

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView = [[WKWebView alloc]initWithFrame:self.view.bounds
]; self.webView.UIDelegate = self; self.webView.navigationDelegate = self; [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]]; [self.view addSubview:self.webView]; self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self
.view.frame), 2)]; self.progressView.progressTintColor = [UIColor greenColor]; [self.view addSubview:self.progressView]; // 給webview新增監聽 [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil]; // Do any additional setup after loading the view, typically from a nib.
}

// 監聽事件處理

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)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:YES];
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView setNavigationDelegate:nil];
    [self.webView setUIDelegate:nil];
}