1、使用UIWebView加载网页
运行XCode 4.3,新建一个Single View Application,命名为WebViewDemo。
2、加载WebView
在ViewController.h添加WebView成员变量和在ViewController.m添加实现
#import <UIKit/UIKit.h>@interface ViewController : UIViewController { UIWebView *webView; } @end ViewController.m - (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]; }
手机的网络环境是实时变化的,网络慢的时候,怎么提示用户网页正在打开呢?在网页打开出错的时候怎么提示用户呢?这时候我们就需要知道网页什么时候打开的,
什么时候加载完成,什么时候出错了。那么我们需要实现这个<UIWebViewDelegate>协议
3、实现协议,在ViewController.h修改如下:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIWebViewDelegate> { UIWebView *webView; } @end
4、UIWebView主要有下面几个委托方法:
1、- (void)webViewDidStartLoad:(UIWebView *)webView;开始加载的时候执行该方法。
2、- (void)webViewDidFinishLoad:(UIWebView *)webView;加载完成的时候执行该方法。
3、- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;加载出错的时候执行该方法。
我们可以将activityIndicatorView放置到前面两个委托方法中。
- (void)webViewDidStartLoad:(UIWebView *)webView { [activityIndicatorView startAnimating] ; } - (void)webViewDidFinishLoad:(UIWebView *)webView { [activityIndicatorView stopAnimating]; }
- (IBAction)buttonPress:(id) sender { [textField resignFirstResponder]; [self loadWebPageWithString:textField.text]; }
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alterview show]; [alterview release]; }
<strong>- (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]; </strong>
<strong>- (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]; </strong>
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。