---
title: "【转】在webview加加载数据时添加一个Loading...动画的两种方法"
author: "xinlanzero"
date: "2011-05-11T17:21:50Z"
tags: []
categories: ["移动开发"]
slug: "webview-loading"
draft: false
lastmod: "2011-05-11T17:21:50Z"
id: 1040275
url: "https://xinlanzero.iteye.com/blog/1040275"
---

【转】在webview加加载数据时添加一个Loading...动画的两种方法

 

大家使用iPhone/iPod浏览网页时，一定见过浏览器加载网页时，总会出现一个Loading动画，其实这是实现起来是非常简单的。下面就是两种不同的实现方法：

**第一种方法：**

01. //创建UIWebView
02. WebView = \[\[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 320, 400)];
03. \[WebView setUserInteractionEnabled:NO];
04. \[WebView setBackgroundColor:\[UIColor clearColor]];
05. \[WebView setDelegate:self];
06. \[WebView setOpaque:NO];//使网页透明
07. NSString \*path = @"http://www.baidu.com";
08. NSURL \*url = \[NSURL URLWithString:path];
09. \[WebView loadRequest:\[NSURLRequest requestWithURL:url]];
10. //创建UIActivityIndicatorView背底半透明View
11. UIView \*view = \[\[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
12. \[view setTag:103];
13. \[view setBackgroundColor:\[UIColor blackColor]];
14. \[view setAlpha:0.8];
15. \[self.view addSubview:view];
16. activityIndicator = \[\[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
17. \[activityIndicator setCenter:view.center];
18. \[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
19. \[view addSubview:activityIndicator];
20. \[self.view addSubview:WebView];
21. \[view release];
22. \[WebView release];
23. //以下两个方法是UIWebView的delegate methods
24. //开始加载数据
25. \- (void)webViewDidStartLoad:(UIWebView \*)webView {
26. \[activityIndicator startAnimating];
27. }
28. //数据加载完
29. \- (void)webViewDidFinishLoad:(UIWebView \*)webView {
30. \[activityIndicator stopAnimating];
31. UIView \*view = (UIView \*)\[self.view viewWithTag:103];
32. \[view removeFromSuperview];
33. }

**第二种方法：在UIAlertView上添加一个UIActivityIndicatorView**

01. //加载网页动画
02. \- (void)webViewDidStartLoad:(UIWebView \*)webView{
03. if (myAlert==nil){
04. myAlert = \[\[UIAlertView alloc] initWithTitle:nil
05. message: @"正在加载数据，请稍候..."
06. delegate: self
07. cancelButtonTitle: nil f
08. otherButtonTitles: nil];
09. UIActivityIndicatorView \*activityView = \[\[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
10. activityView.frame = CGRectMake(120.f, 48.0f, 37.0f, 37.0f);
11. \[myAlert addSubview:activityView];
12. \[activityView startAnimating];
13. \[myAlert show];
14. }
15. }
16. \- (void)webViewDidFinishLoad:(UIWebView \*)webView{
17. \[myAlert dismissWithClickedButtonIndex:0 animated:YES];
18. }