目前市場上APP常會嵌入不少的h5頁面,參照支付寶顯示web頁面的方式, 做了一個導航欄下的加載進度條. 因為項目最低支持iOS7,所以不能使用WKWebView來加載網(wǎng)頁, 只能使用 UIWebView, 但是查看 UIWebView的API, 并沒有代理或是通知告訴我們webView加載了多少, 所以這個進度條我決定用模擬進度-俗稱假進度(虛擬的方式來做,就是假裝知道加載了多少).
實現(xiàn)原理:
自定義一個UIView的加載進度條,添加到Nav標題欄下方,提供兩個方法:(開始加載/結束加載), 在網(wǎng)頁加載適當?shù)臅r候使用.
Step1. 自定義加載進度條WebviewProgressLine:
1、startLoadingAnimation 開始加載
開始加載,先動畫模擬一個0.4s的加載,加載寬度為0.6倍屏幕寬度,動畫結束,接著0.4s實現(xiàn),共0.8倍的屏幕寬度。
- (void)startLoadingAnimation {
self.hidden = NO;
self.width = 0.0;
__weak UIView *weakSelf = self;
[UIView animateWithDuration:0.4 animations:^{
weakSelf.width = UI_View_Width * 0.6;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.4 animations:^{
weakSelf.width = UI_View_Width * 0.8;
}];
}];
}
2、endLoadingAnimation 結束加載
結束動畫,動畫模擬1.0倍數(shù)的屏幕寬度,實現(xiàn)全部加載完成,并最后隱藏進度條。
- (void)endLoadingAnimation {
__weak UIView *weakSelf = self;
[UIView animateWithDuration:0.2 animations:^{
weakSelf.width = UI_View_Width;
} completion:^(BOOL finished) {
weakSelf.hidden = YES;
}];
}
3、自定義線條顏色
// 進度條顏色
@property (nonatomic,strong) UIColor *lineColor;
- (void)setLineColor:(UIColor *)lineColor {
_lineColor = lineColor;
self.backgroundColor = lineColor;
}
Step2. web頁面使用進度條方法:
1、初始化進度條
self.progressLine = [[WebviewProgressLine alloc] initWithFrame:CGRectMake(0, 64, UI_View_Width, 3)];
self.progressLine.lineColor = [UIColor blueColor];
[self.view addSubview:self.progressLine];
2、初始化網(wǎng)頁并使用代理
懶加載:
- (UIWebView *)web {
if (!_web) {
UIWebView *web = [[UIWebView alloc] initWithFrame:self.view.bounds];
// UIWebView加載過程中,在頁面沒有加載完畢前,會顯示一片空白。為解決這個問題,方法如下:讓UIWebView背景透明。
web.backgroundColor = [UIColor clearColor];
web.opaque = NO;
[web setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"webbg.png"]]];
[self.view addSubview:web];
_web = web;
}
return _web;
}
獲取網(wǎng)址并加載:
NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
[self.web loadRequest:[NSURLRequest requestWithURL:url]];
self.web.delegate = self;
使用代理UIWebViewDelegate:
// 網(wǎng)頁開始加載
- (void)webViewDidStartLoad:(UIWebView *)webView {
// [MBProgressHUD showMessage:@"稍等,玩命加載中"];
[self.progressLine startLoadingAnimation];
}
// 網(wǎng)頁完成加載
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// [MBProgressHUD hideHUD];
[self.progressLine endLoadingAnimation];
}
// 網(wǎng)頁加載失敗
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
// [MBProgressHUD hideHUD];
[self.progressLine endLoadingAnimation];
}
這時候測試一下效果圖:

可根據(jù)自己項目自定義進度條顏色! 希望對您有所幫助!