UIWebView的使用方法
- //1.创建、设置代理
- UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 320, 300)];
- webView.delegate = self;
- //2.加载网页
- NSURL *url=[NSURL URLWithString:@"http://www.google.com.hk"];
- NSURLRequest *request=[[NSURLRequest alloc] initWithURL:url];
- [webView loadRequest:request];
- //3.加载本地资源
- NSURL* url = [NSURL fileURLWithPath:filePath];
- NSURLRequest* request = [NSURLRequest requestWithURL:url];
- [webView loadRequest:request];
- //4.是否与用户交互(即用户能不能控制webview)
- [webView setUserInteractionEnabled:YES];
- //5.显示 UIWebView
- [self.view addSubview:webView];
- //6.导航
- [webView goBack];//返回
- [webView goForward];//向前
- [webView reload];//重新加载数据
- [webView stopLoading];//停止加载数据
- //7.自动对页面进行缩放以适应屏幕
- webView.scalesPageToFit = YES;
- //8.自动检测网页上的电话号码,单击可以拨打
- webView.detectsPhoneNumbers = YES;
- //9.UIWebView 还支持将一个NSString对象作为源来加载。你可以为其提供一个基础URL,来指导UIWebView对象如何跟随链接和加载远程资源
- [webView loadHTMLString:myHTML baseURL:[NSURL URLWithString:@"http://baidu.com"]];
- //10.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 nil];
- [alert show];
- }
- return NO;
- }
- return YES;
- }