不一樣於WKWebview,wk是有本身的加載進度值的,咱們能夠直接經過kvo檢測到,並顯示到進度條內。ios
但若是咱們爲了適配ios7,只能使用UIWebview了,這裏的加載進度,就比較尷尬了web
因此咱們的實現方式就是:模擬進度-俗稱假進度。動畫
實現原理:atom
自定義一個UIView的進度條,添加到Nav下方,給予兩個方法:url
一、startLoadingAnimation 開始加載spa
二、endLoadingAnimation 結束加載code
開始加載,先動畫模擬一個0.4s的加載,加載寬度爲0.6倍屏幕寬度,動畫結束,再0.4s實現,總共0.8倍的屏幕寬度。blog
結束動畫,動畫模擬1.0倍數的屏幕寬度,實現所有加載完成,並最後隱藏掉進度條。webview
代碼:animation
.h文件
#import <UIKit/UIKit.h> @interface WebviewProgressLine : UIView //進度條顏色 @property (nonatomic,strong) UIColor *lineColor; //開始加載 -(void)startLoadingAnimation; //結束加載 -(void)endLoadingAnimation; @end
.m文件
#import "WebviewProgressLine.h" @implementation WebviewProgressLine -(instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { self.hidden = YES; self.backgroundColor = [UIColor whiteColor]; } return self; } -(void)setLineColor:(UIColor *)lineColor{ _lineColor = lineColor; self.backgroundColor = lineColor; } -(void)startLoadingAnimation{ self.hidden = NO; self.width = 0.0; __weak UIView *weakSelf = self; [UIView animateWithDuration:0.4 animations:^{ weakSelf.width = KScreenWidth * 0.6; } completion:^(BOOL finished) { [UIView animateWithDuration:0.4 animations:^{ weakSelf.width = KScreenWidth * 0.8; }]; }]; } -(void)endLoadingAnimation{ __weak UIView *weakSelf = self; [UIView animateWithDuration:0.2 animations:^{ weakSelf.width = KScreenWidth; } completion:^(BOOL finished) { weakSelf.hidden = YES; }]; } @end
webview頁面使用:
#import "webviewViewController.h" #import "WebviewProgressLine.h" @interface webviewViewController ()<UIWebViewDelegate> @property (nonatomic,strong) UIWebView *webview; @property (nonatomic,strong) WebviewProgressLine *progressLine; @end @implementation webviewViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; self.webview = [[UIWebView alloc] initWithFrame:self.view.frame]; self.webview.delegate = self; [self.view addSubview:self.webview]; self.progressLine = [[WebviewProgressLine alloc] initWithFrame:CGRectMake(0, 64, KScreenWidth, 3)]; self.progressLine.lineColor = [UIColor redColor]; [self.view addSubview:self.progressLine]; NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"]; [self.webview loadRequest:[NSURLRequest requestWithURL:url]]; } -(void)webViewDidStartLoad:(UIWebView *)webView{ [self.progressLine startLoadingAnimation]; } -(void)webViewDidFinishLoad:(UIWebView *)webView{ [self.progressLine endLoadingAnimation]; } -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{ [self.progressLine endLoadingAnimation]; }
因爲內容比較簡單,就不放Demo了,直接貼代碼,你們能夠試一下~