先看效果圖:
下面是代碼(測(cè)試環(huán)境:Xcode8.2.1,模擬器是iPhone7,iOS10.2)
1:導(dǎo)入頭文件
import <WebKit/WebKit.h> @property (strong, nonatomic) WKWebView *webView; @property (strong, nonatomic) UIProgressView *progressView;
** 2:初始化**
// 創(chuàng)建urlrequest11111 NSURL *url = [NSURL URLWithString:@"http://www.reibang.com/"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; // WKWebView初始化 self.webView = [[WKWebView alloc] initWithFrame:self.view.frame]; // 加載請(qǐng)求 [self.webView loadRequest:request]; [self.view addSubview:self.webView]; // KVO塔嬉,監(jiān)聽(tīng)webView屬性值得變化(estimatedProgress,title為特定的key) [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; // UIProgressView初始化 self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; self.progressView.frame = CGRectMake(0, 0, self.webView.frame.size.width, 2); self.progressView.trackTintColor = [UIColor clearColor]; // 設(shè)置進(jìn)度條的色彩 self.progressView.progressTintColor = [UIColor magentaColor]; // 設(shè)置初始的進(jìn)度,防止用戶(hù)進(jìn)來(lái)就懵逼了(微信大概也是一開(kāi)始設(shè)置的10%的默認(rèn)值) [self.progressView setProgress:0.1 animated:YES]; [self.webView addSubview:self.progressView];
3:完成監(jiān)聽(tīng)方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([object isEqual:self.webView] && [keyPath isEqualToString:@"estimatedProgress"]) { // 進(jìn)度條 CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue]; NSLog(@"打印測(cè)試進(jìn)度值:%f", newprogress); if (newprogress == 1) { // 加載完成 // 首先加載到頭 [self.progressView setProgress:newprogress animated:YES]; // 之后0.3秒延遲隱藏 __weak typeof(self) weakSelf = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ weakSelf.progressView.hidden = YES; [weakSelf.progressView setProgress:0 animated:NO]; }); } else { // 加載中 self.progressView.hidden = NO; [self.progressView setProgress:newprogress animated:YES]; } } else if ([object isEqual:self.webView] && [keyPath isEqualToString:@"title"]) { // 標(biāo)題 self.title = self.webView.title; } else { // 其他 [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } }