本例子是為了讓大家能快速開發出OC調用JS功能的一個簡單的例子。
1、准備一個本地化的html網頁,如jsIOS.html
js調用oc <script type="text/javaScript"> function postStr(str1,str2){ document.getElementById("text1").value=str1; document.getElementById("text2").value=str2; return document.getElementById("text3").value; //return "javaScript返回值啦"; } </script>
2、將此html文件放到項目代碼目錄裡面,如圖:
3、拖一個UIWebView控件和UIButton控件到xxxViewController對應的.xib或.storyboard視圖的UIView上;
在xxxViewController的.h文件中分別聲明UIWebView類型變量和UIButton類型的變量,以及一個按鈕點擊事件(並且跟視圖裡面的控件連線),
並且添加一個UIWebViewDelegate類型的委托。<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+eHh4Vmlld0NvbnRyb2xsZXIuaM7EvP7E2sjdyOfPwqO6PC9wPgo8cD48L3A+CjxwIGNsYXNzPQ=="p1">
#import@interface ViewController : UIViewController @property(nonatomic,retain) IBOutlet UIWebView *webview; @property(nonatomic,retain) IBOutlet UIButton *button; -(IBAction)IOS_JS:(id)sender; @end
代碼如下:
// // ViewController.m // IOS_JS_01 // // Created by IMAC on 14-2-25. // Copyright (c) 2014年 Wanggsx. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize webview; - (void)viewDidLoad { [super viewDidLoad]; //設置webView webview.backgroundColor = [UIColor clearColor]; //webview.scalesPageToFit =YES; webview.delegate =self; //找到jsIOS.html文件的路徑 NSString *basePath = [[NSBundle mainBundle]bundlePath]; NSString *helpHtmlPath = [basePath stringByAppendingPathComponent:@"jsIOS.html"]; NSURL *url = [NSURL fileURLWithPath:helpHtmlPath]; //加載本地html文件 [webview loadRequest:[NSURLRequest requestWithURL:url]]; } /* * 點擊事件 * 調用javaScript的方法postStr(str1,str2)並取得返回值 * 輸出返回值到控制台 */ -(IBAction)IOS_JS:(id)sender { //NSString *str = [self.webview stringByEvaluatingJavaScriptFromString:@"postStr();"]; //要傳遞的參數一 NSString *str1 = @"我來自於oc"; //要傳遞的參數二 NSString *str2 = @"我來自於地球"; NSString *str = [self.webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"postStr('%@','%@');",str1,str2]]; NSLog(@"JS返回值:%@",str); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end