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

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

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

第一种方法:
  1. //创建UIWebView
  2. WebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 320, 400)];
  3. [WebView setUserInteractionEnabled:NO];
  4. [WebView setBackgroundColor:[UIColor clearColor]];
  5. [WebView setDelegate:self];
  6. [WebView setOpaque:NO]; //使网页透明

  7. NSString *path = @"http://www.baidu.com";
  8. NSURL *url = [NSURL URLWithString:path];
  9. [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
  1. //加载网页动画
  2. - (void)webViewDidStartLoad:(UIWebView *)webView{
  3. if (myAlert==nil){
  4. myAlert = [[UIAlertView alloc] initWithTitle:nil
  5. message: @"正在加载数据,请稍候..."
  6. delegate: self
  7. cancelButtonTitle: nil f
  8. otherButtonTitles: nil];
  9. 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. }


    推荐阅读