UIWebView的用法
(1)创建
UIWebView *myWebView=[[UIWebViewalloc] initWithFrame:CGRectMake(0, 20, 320, 300)];
(2)加载网页
NSURL *url=[NSURLURLWithString:@"http://www.google.com.hk"];
NSURLRequest *request=[[NSURLRequestalloc] initWithURL:url];
[myWebView loadRequest:request];
(3)是否与用户交互(即用户能不能控制webview)
[myWebView setUserInteractionEnabled:YES];
(4)显示 UIWebView
[self.view addSubview:myWebView];
(5)导航
[webView goBack];//返回
[webView goForward];//向前
[webView reload];//重新加载数据
(6)委托
1.-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType;
-
web视图指示加载内容时通知。应该返回YES开始加载。导航提供的类型参数,是指请求的来源,可以是下列任何一个:
- 2.-(void)webViewDidStartLoad:(UIWebView *)webView;//当开始请求的时候被通知
- 3.-(void)webViewDidFinishLoad:(UIWebView *)webView;//当结束请求的时候被通知
- 4.-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;//当请求中出现错误时被通知
-
(7)UIWebView和JS交互
1》在Objective-C代码中调用JS使用stringByEvaluatingJavaScriptFromString方法,需要等到UIWebView中的页面加载完成之后去调用。-(void) webViewDidFinishLoad:(UIWebView *)webView{
[self.activityViewstopAnimating];
[myWebView stringByEvaluatingJavaScriptFromString:@"function test(){ alert(123123123)}"];
[myWebView stringByEvaluatingJavaScriptFromString:@"test();"];//调用
}2》在JS中调用Objective-C代码JS代码:- function sendCommand(cmd,param){
- var url="testapp:"+cmd+":"+param;
- document.location = url;
- }
- function clickLink(){
- sendCommand("alert","你好吗?");
- }
Objective-C代码:- - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
- NSString *requestString = [[request URL] absoluteString];
- NSArray *components = [requestString componentsSeparatedByString:@":"];
- if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"]) {
- if([(NSString *)[components objectAtIndex:1] isEqualToString:@"alert"])
- {
- UIAlertView *alert = [[UIAlertView alloc]
- initWithTitle:@"Alert from Cocoa Touch" message:[components objectAtIndex:2]
- delegate:self cancelButtonTitle:nil
- otherButtonTitles:@"OK", nil];
- [alert show];
- }
- return NO;
- }
- return YES;
- }