本例子是为了让大家能快速开发出OC调用JS功能的一个简单的例子。
1、准备一个本地化的html网页,如jsIOS.html 1 2 3 4 5 6 7 8 9 10 11 12 13 | <meta http-equiv= "content-type" content= "text/html;charset=utf-8" >
<title>js调用oc</title>
<script type= "text/javaScript" >
function postStr(){
return document.getElementById( "text1" ).value;
}
</script>
<p><input type= "text" id= "text1" value= "返回值" ></p>
|
2、将此html文件放到项目代码目录里面,如图:
3、拖一个UIWebView控件和UIButton控件到xxxViewController对应的.xib或.storyboard视图的UIView上; 在xxxViewController的.h文件中分别声明UIWebView类型变量和UIButton类型的变量,以及一个按钮点击事件(并且跟视图里面的控件连线), 并且添加一个UIWebViewDelegate类型的委托。<喎?"http://www./kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+eHh4Vmlld0NvbnRyb2xsZXIuaM7EvP7E2sjdyOfPwqO6PC9wPgo8cD48L3A+CjxwIGNsYXNzPQ=="p1"> 1 2 3 4 5 6 7 | # import <uikit uikit.h= "" >
@interface ViewController : UIViewController <uiwebviewdelegate>
@property (nonatomic,retain) IBOutlet UIWebView *webview;
@property (nonatomic,retain) IBOutlet UIButton *button;
-(IBAction)IOS_JS:(id)sender;
@end </uiwebviewdelegate></uikit>
|
4、在xxxViewController.m文件中实现通过点击事件,调用javaScript的方法并取得返回值。代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | # import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize webview;
- ( void )viewDidLoad
{
[ super viewDidLoad];
webview.backgroundColor = [UIColor clearColor];
webview.delegate =self;
NSString *basePath = [[NSBundle mainBundle]bundlePath];
NSString *helpHtmlPath = [basePath stringByAppendingPathComponent:@ "jsIOS.html" ];
NSURL *url = [NSURL fileURLWithPath:helpHtmlPath];
[webview loadRequest:[NSURLRequest requestWithURL:url]];
}
-(IBAction)IOS_JS:(id)sender
{
NSString *str = [self.webview stringByEvaluatingJavaScriptFromString:@ "postStr();" ];
NSLog(@ "JS返回值:%@" ,str);
}
- ( void )didReceiveMemoryWarning
{
[ super didReceiveMemoryWarning];
}
@end
|
|