UIWebView 加载进度控件 NJKWebViewProgress的使用

林彬
2023-12-01

加载UIWebView时为了显示加载状态达到良好的用户体验,一般有两种方式:

1、创建一个UIActivityIndicatorView在UIWebView的代理方法- (void)webViewDidStartLoad:(UIWebView )webView中startAnimating,加载完成后在- (void)webViewDidFinishLoad:(UIWebView )webView中stopAnimating。
但这种方式只能显示正在加载和加载完成两种状态,不能显示进度。

2、使用比较好用的第三方控件NJKWebViewProgress

//
//  MyWebViewController.m
//  UIWebViewProgressTest
//
//  Created by huxinguang on 16/5/3.
//  Copyright © 2016年 hxg. All rights reserved.
//

#import "MyWebViewController.h"
#import "NJKWebViewProgress.h"
#import "NJKWebViewProgressView.h"
@interface MyWebViewController ()<NJKWebViewProgressDelegate,UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (nonatomic ,strong)NJKWebViewProgress *progress;
@property (nonatomic ,strong)NJKWebViewProgressView *progressView;

@end

@implementation MyWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置代理
    _progress = [[NJKWebViewProgress alloc] init];
    _webView.delegate = _progress;
    _progress.webViewProxyDelegate = self;
    _progress.progressDelegate = self;

    //创建进度条NJKWebViewProgressView,设置frame、颜色
    CGRect navBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0,navBounds.size.height - 2,navBounds.size.width,2);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.progressBarView.backgroundColor = [UIColor redColor];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [_progressView setProgress:0 animated:YES];
    [self.navigationController.navigationBar addSubview:_progressView];

    //加载web页面
    [self loadWebView];

}

- (void)loadWebView{
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:request];
}

#pragma mark - NJKWebViewProgressDelegate
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress{
    [_progressView setProgress:progress animated:YES];
    self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];

}

//“将要加载” “开始加载” “加载完成” “加载失败” 几种状态下需要做什么可以在UIWebView代理方法中处理
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{

}
- (void)webViewDidFinishLoad:(UIWebView *)webView{

}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{

}

@end

最后,框架中NJKWebViewProgress和NJKWebViewProgressView是分开写的,如果项目需要,还可以自定义一个ProgressView。

 类似资料: