iOS学习之WebView的使用
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修改如下
@interface ViewController : UIViewController<UIWebViewDelegate>
{
UIWebView *webView;
}
@end
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原创,欢迎转载分享。请尊重作者劳动,转载时保留该声明和作者博客链接,谢谢
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。