Red de conocimiento informático - Material del sitio web - Cómo usar js para llamar directamente a métodos OC en la plataforma IOS

Cómo usar js para llamar directamente a métodos OC en la plataforma IOS

1. Prepare una página html localizada, como jsIOS.html

lt; script type="text/javaScript"gt;

function postStr(){

devolver document.value;

//return "valor de retorno de javaScript la";

}

lt;/scriptgt;

2. Coloque este archivo html en el directorio de código del proyecto, como se muestra en la figura:

3. Arrastre un control UIWebView y un control UIButton a xxxViewController, correspondiente a la vista .xib o .storyboard de UIView;

En el archivo .h de xxxViewController, declare el control UIWebView y el control UIButton respectivamente.

En el archivo .h de xxxViewController, declare las variables de tipo UIWebView y las variables de tipo UIButton respectivamente, y declare un evento de clic de botón en el archivo xxxViewController.h (y conéctelo al control en la vista),

Y agregue un delegado de tipo UIWebViewDelegate. lt; 喎? "/kf/ware/vc/" target = "_ blank" class = "keylink" gt; vcd4kpha ehh4vmlld0nvbnryb2xszxiuam7evp7e2sjdyofpwqo6pc9wpgo8cd48l3a cjxwignsyxnzpq ==

@interface ViewController:

@property(nonatomic, retener) IBOutlet UIWebView * webview;

@property(nonatomic, retener) IBOutlet UIButton *botón;

-(IBAction)IOS_JS: (id)sender;

@end

4. Implemente el evento de clic en el archivo xxxViewController.m, llame al método javaScript y obtenga la devolución. valor.

El código es el siguiente:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize webview;

- (void)viewDidLoad

{

[super viewDidLoad] ;

p>

//Establecer webView

webview.backgroundColor = [UIColor clearColor];

//webview.scalesPageToFit = YES;

webview.delegate = self;

//busca la ruta al archivo jsIOS.html

NSString * basePath = [[NSBundle mainBundle]bundlePath];

NSString *helpHtmlPath = [basePath stringByAppendingPathComponent:@"jsIOS.html"];

NSURL *url = [NSURL fileURLWithPath: helpHtmlPath]

//cargar local; archivo html

[webview loadRequest: [NSURLRequest requestWithURL: webview stringByEvaluatingJavaScriptFromString: @"postStr();"];

NSLog(@"Valor de retorno de JS: @", str);

}.

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

}

@end