通过iOS中的按钮来触发html文件中按钮所触发的函数
2015-08-04 11:07 甘雨路 阅读(326) 评论(0) 编辑 收藏 举报html文件的代码
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>标题</title> 5 </head> 6 7 <body> 8 <input type="button" class="inputBut" name="test" value="send massage" 9 onClick="myFunction()"> 10 </body> 11 12 <script type="text/javascript"> 13 function myFunction() 14 { 15 alert("Hello World!"); 16 } 17 </script> 18 </html>
iOS 工程的代码
#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
1 #import "AppDelegate.h" 2 #import "RootViewController.h" 3 @interface AppDelegate () 4 5 @end 6 7 @implementation AppDelegate 8 9 10 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 11 self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 12 // Override point for customization after application launch. 13 self.window.backgroundColor = [UIColor whiteColor]; 14 15 self.window.rootViewController = [[RootViewController alloc] init]; 16 17 [self.window makeKeyAndVisible]; 18 return YES; 19 } 20 21 @end
#import <UIKit/UIKit.h> @interface RootViewController : UIViewController @end
1 #import "RootViewController.h" 2 3 @interface RootViewController () 4 5 @property (nonatomic, strong)UIWebView *webView; 6 7 @end 8 9 @implementation RootViewController 10 11 - (void)viewDidLoad { 12 [super viewDidLoad]; 13 self.webView = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 14 [self.view addSubview:self.webView]; 15 // self.webView.hidden = YES; 16 17 // 加载本地HTML文件 18 NSString *path = [[NSBundle mainBundle] pathForResource:@"button" ofType:@"html"]; 19 NSURL *url = [NSURL URLWithString:path]; 20 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 21 [self.webView loadRequest:request]; 22 23 // 添加按钮 24 UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 25 btn.frame = CGRectMake(100, 100, 80, 50); 26 btn.backgroundColor = [UIColor redColor]; 27 [btn setTitle:@"触发js按钮" forState:0]; 28 [btn addTarget:self action:@selector(callJavaScriptFunction:) forControlEvents:UIControlEventTouchUpInside]; 29 [self.view addSubview:btn]; 30 31 32 } 33 34 - (void)callJavaScriptFunction:(UIButton *)sender 35 { 36 NSString *aString = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunction();"]; 37 NSLog(@"=== %@",aString); 38 } 39 40 @end