本例子是为了让大家能快速开发出OC调用JS功能的一个简单的例子。
1、准备一个本地化的html网页,如jsIOS.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>js调用oc</title>
<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>
</head>
<body>
<p><input type="text" id="text1" value="实参1"/></p>
<p><input type="text" id="text2" value="实参2"/></p>
<p><input type="text" id="text3" value="返回值"/></p>
</body>
</html>2、将此html文件放到项目代码目录里面,如图:
3、拖一个UIWebView控件和UIButton控件到xxxViewController对应的.xib或.storyboard视图的UIView上;
在xxxViewController的.h文件中分别声明UIWebView类型变量和UIButton类型的变量,以及一个按钮点击事件(并且跟视图里面的控件连线),
并且添加一个UIWebViewDelegate类型的委托。
xxxViewController.h文件内容如下:
#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
代码如下:
//
// 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
原文:http://blog.csdn.net/wanggsx918/article/details/19921629