iOS-仿支付宝加载web网页添加进度条

来源:互联网 发布:茶叶网络营销策划目的 编辑:程序博客网 时间:2024/05/22 10:43

目前市场上APP常会嵌入不少的h5页面,参照支付宝显示web页面的方式, 做了一个导航栏下的加载进度条. 因为项目最低支持iOS7,所以不能使用WKWebView来加载网页, 只能使用 UIWebView, 但是查看 UIWebView的API, 并没有代理或是通知告诉我们webView加载了多少, 所以这个进度条我决定用模拟进度-俗称假进度(虚拟的方式来做,就是假装知道加载了多少).

一、压缩文件及项目截图

压缩文件截图:
压缩文件截图
项目截图:
项目截图

二、代码实现

实现原理:
自定义一个UIView的加载进度条,添加到Nav标题栏下方,提供两个方法:(开始加载/结束加载), 在网页加载适当的时候使用.

Step1. 自定义加载进度条WebviewProgressLine:

1、startLoadingAnimation 开始加载

开始加载,先动画模拟一个0.4s的加载,加载宽度为0.6倍屏幕宽度,动画结束,接着0.4s实现,共0.8倍的屏幕宽度。

  1. - (void)startLoadingAnimation {
  2. self.hidden = NO;
  3. self.width = 0.0;
  4. __weak UIView *weakSelf = self;
  5. [UIView animateWithDuration:0.4 animations:^{
  6. weakSelf.width = UI_View_Width * 0.6;
  7. } completion:^(BOOL finished) {
  8. [UIView animateWithDuration:0.4 animations:^{
  9. weakSelf.width = UI_View_Width * 0.8;
  10. }];
  11. }];
  12. }

2、endLoadingAnimation 结束加载

结束动画,动画模拟1.0倍数的屏幕宽度,实现全部加载完成,并最后隐藏进度条。

  1. - (void)endLoadingAnimation {
  2. __weak UIView *weakSelf = self;
  3. [UIView animateWithDuration:0.2 animations:^{
  4. weakSelf.width = UI_View_Width;
  5. } completion:^(BOOL finished) {
  6. weakSelf.hidden = YES;
  7. }];
  8. }

3、自定义线条颜色

  1. // 进度条颜色
  2. @property (nonatomic,strong) UIColor *lineColor;
  1. - (void)setLineColor:(UIColor *)lineColor {
  2. _lineColor = lineColor;
  3. self.backgroundColor = lineColor;
  4. }

Step2. web页面使用进度条方法:

1、初始化进度条

  1. self.progressLine = [[WebviewProgressLine alloc] initWithFrame:CGRectMake(0, 64, UI_View_Width, 3)];
  2. self.progressLine.lineColor = [UIColor blueColor];
  3. [self.view addSubview:self.progressLine];

2、初始化网页并使用代理

懒加载:

  1. - (UIWebView *)web {
  2. if (!_web) {
  3. UIWebView *web = [[UIWebView alloc] initWithFrame:self.view.bounds];
  4. // UIWebView加载过程中,在页面没有加载完毕前,会显示一片空白。为解决这个问题,方法如下:让UIWebView背景透明。
  5. web.backgroundColor = [UIColor clearColor];
  6. web.opaque = NO;
  7. [web setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"webbg.png"]]];
  8. [self.view addSubview:web];
  9. _web = web;
  10. }
  11. return _web;
  12. }

获取网址并加载:

  1. NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
  2. [self.web loadRequest:[NSURLRequest requestWithURL:url]];
  3. self.web.delegate = self;

使用代理UIWebViewDelegate:

  1. // 网页开始加载
  2. - (void)webViewDidStartLoad:(UIWebView *)webView {
  3. // [MBProgressHUD showMessage:@"稍等,玩命加载中"];
  4. [self.progressLine startLoadingAnimation];
  5. }
  6. // 网页完成加载
  7. - (void)webViewDidFinishLoad:(UIWebView *)webView {
  8. // [MBProgressHUD hideHUD];
  9. [self.progressLine endLoadingAnimation];
  10. }
  11. // 网页加载失败
  12. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
  13. // [MBProgressHUD hideHUD];
  14. [self.progressLine endLoadingAnimation];
  15. }

三、运行效果

这时候测试一下效果图:

四、其他补充

可根据自己项目自定义进度条颜色, 具体可参考代码, 项目则能够直接运行!

如需看详情版,请到这里下载!

原创粉丝点击