iOS学习之WebView的使用

来源:互联网 发布:tpo小站模考软件mac 编辑:程序博客网 时间:2024/05/21 10:09

1、初始化WebView

- (void)viewDidLoad
{
    [super viewDidLoad];
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
    [self.view addSubview: webView];
    [webView loadRequest:request];
}

2、

实现协议,在ViewController.h修改如下

#import <UIKit/UIKit.h>


@interface ViewController : UIViewController<UIWebViewDelegate>
{
    UIWebView *webView;
}
@end

UIWebView中几个重要的函数
1.- (void )webViewDidStartLoad:(UIWebView  *)webView   网页开始加载的时候调用
2.- (void )webViewDidFinishLoad:(UIWebView  *)webView  网页加载完成的时候调用
3.- (void)webView:(UIWebView *)webView  didFailLoadWithError:(NSError *)error 网页加载错误的时候调用

先在viewDidLoad 的webView实例化下面加上

    [webView setDelegate:self];设置代理。这样上面的三个方法才能得到回调。


3、加载等待页面

- (void) webViewDidStartLoad:(UIWebView *)webView
{
    //创建UIActivityIndicatorView背底半透明View     
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];  
    [view setTag:108];  
    [view setBackgroundColor:[UIColor blackColor]];  
    [view setAlpha:0.5];  
    [self.view addSubview:view];  
    
    activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];  
    [activityIndicator setCenter:view.center];  
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];  
    [view addSubview:activityIndicator];  


    [activityIndicator startAnimating];
}

加载完成或失败时,去掉loading效果

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    [activityIndicator stopAnimating];
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];
    NSLog(@"webViewDidFinishLoad");


}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [activityIndicator stopAnimating];
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];

}


著作权声明:本文由http://blog.csdn.net/yangchen9931原创,欢迎转载分享。请尊重作者劳动,转载时保留该声明和作者博客链接,谢谢


0 0