34.UIWebView(做一个简易的浏览器)

来源:互联网 发布:剑三脸型数据是视频 编辑:程序博客网 时间:2024/05/21 15:05

UIWebView是iOS sdk中一个最常用的控件。是内置的浏览器控件,我们可以用它来浏览网页、打开文档等等。这篇文章我将使用这个控件,做一个简易的浏览器。

创建一个TextField和button 根据TextField输入的网址跳转网页

1.设置属性方便使用和遵守UIWebViewDelegate协议

@interface RootViewController ()< UIWebViewDelegate >

@property (nonatomic,retain)UITextField *textField;

@property (nonatomic,retain)UIWebView *webView;

2.创建一个TextField

self.textField = [[UITextField alloc] initWithFrame:CGRectMake(5, 25, 300, 50)];

self.textField.borderStyle = UITextBorderStyleRoundedRect;

[self.view addSubview:self.textField];

[_textField release];

1.创建一个Button

UIButton *goBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];

goBtn.backgroundColor = [UIColor redColor];

goBtn.frame = CGRectMake(310, 25, 50, 50);

[goBtn setTitle:@”Go” forState:(UIControlStateNormal)];

[goBtn addTarget:self action:@selector(goBtn:) forControlEvents:(UIControlEventTouchUpInside)];

[self.view addSubview:goBtn];

self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 75, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 75)];

self.webView.backgroundColor = [UIColor cyanColor];

[self.view addSubview:self.webView];

[self.webView release];

NSURL *url = [NSURL URLWithString:@”http://www.baidu.com“];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

[self.webView loadRequest:request];

[request autorelease];

适配

self.webView.scalesPageToFit = YES;

self.webView.delegate = self;

// 中断请求 [self.webView stopLoading];

实现点击方法

- (void)goBtn:(UIButton *)goBtn

{

NSString *text = self.textField.text;

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@”http://%@“,text]];

if (text != nil && self.webView.request.URL != url) {

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

[self.webView loadRequest:request];

[request release];

}

}

==========================
协议中的四种方法

加载完成的时候执行该方法

- (void)webViewDidFinishLoad:(UIWebView *)webView

{

NSLog(@”已经完成导入”);

}

加载出错的时候执行该方法

- (void)webView:(UIWebView )webView didFailLoadWithError:(NSError )error

{

NSLog(@”请求失败”);

}

开始加载的时候执行该方法

- (void)webViewDidStartLoad:(UIWebView *)webView

{

NSLog(@”已经开始导入”);

}

- (BOOL)webView:(UIWebView )webView shouldStartLoadWithRequest:(NSURLRequest )request navigationType:(UIWebViewNavigationType)navigationType

{

NSLog(@”应该导入开始的请求”);

NSLog(@”%@”,request);

return YES;

}

0 0
原创粉丝点击