iOS7 UIWebview加載進度條實現


不同於WKWebview,wk是有自己的加載進度值的,我們可以直接通過kvo檢測到,並顯示到進度條內。

 

但如果我們為了適配ios7,只能使用UIWebview了,這里的加載進度,就比較尷尬了

 

所以我們的實現方式就是:模擬進度-俗稱假進度。

 

實現原理:

自定義一個UIView的進度條,添加到Nav下方,給予兩個方法:

1、startLoadingAnimation  開始加載

2、endLoadingAnimation  結束加載

 

開始加載,先動畫模擬一個0.4s的加載,加載寬度為0.6倍屏幕寬度,動畫結束,再0.4s實現,總共0.8倍的屏幕寬度。

結束動畫,動畫模擬1.0倍數的屏幕寬度,實現全部加載完成,並最后隱藏掉進度條。

 

代碼:

.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了,直接貼代碼,大家可以試一下~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM