原作者github链接:https://github.com/ninjinkun/NJKWebViewProgress
效果如下图:
#import <UIKit/UIKit.h>
#import "NJKWebViewProgress.h"
#import "NJKWebViewProgressView.h"
@interface ViewController : UIViewController<UIWebViewDelegate, NJKWebViewProgressDelegate>
@end
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIWebView *webV;
@end
@implementation ViewController
{
NJKWebViewProgressView *_progressView;
NJKWebViewProgress *_progressProxy;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"商城";
//关闭NavgationBar的自适应64高度
self.automaticallyAdjustsScrollViewInsets = NO;
//初始化webView
self.webV = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64)];
[self.view addSubview:_webV];
//初始化进度条
_progressProxy = [[NJKWebViewProgress alloc] init];
_webV.delegate = _progressProxy;
_progressProxy.webViewProxyDelegate = self;
_progressProxy.progressDelegate = self;
//进度条高度
CGFloat progressBarHeight = 2.f;
CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
//进度条的frame
CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
_progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
//设置进度条颜色
_progressView.progressBarView.backgroundColor = [UIColor redColor];
_progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
[_progressView setProgress:0 animated:YES];
//开始请求网络
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"www.baidu.com"]];
[self.webV loadRequest:req];
}
#pragma mark - NJKWebViewProgressDelegate
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress{
[_progressView setProgress:progress animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController.navigationBar addSubview:_progressView];
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[_progressView removeFromSuperview];
}