2012-07-22 10 views
0

我有一個UIWebView,它包含帶有JS函數的按鈕,但委託方法僅在加載頁面上調用,而不是在按下按鈕時調用,如我所願。javascript中的Objective-C方法不叫

什麼問題?

P.S.

我在模擬器上測試。

在.H

@interface MyViewController : UIViewController <UIWebViewDelegate>{ 
    UIWebView *webView; 
} 
@property (strong, nonatomic) IBOutlet UIWebView *webView; 

中的m:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSString *myHTML = @"<!DOCTYPE html><html><head><script type=\"text/javascript\"> 
    function myFunction(){document.location = \"myapp:\" + \"myfunction:\" 
    + param1 + \":\" + param2;}</script></head><body><button onclick=\ 
    "myFunction()\">Try it</button><p>By clicking the button above, 
    a function will be called.</p></body></html>"; 

    [webView loadHTMLString:myHTML baseURL:nil]; 
    webView.delegate = self; 
} 


- (BOOL)webView:(UIWebView *)webView2 
shouldStartLoadWithRequest:(NSURLRequest *)request 
navigationType:(UIWebViewNavigationType)navigationType { 

    NSString *requestString = [[request URL] absoluteString]; 
    NSArray *components = [requestString componentsSeparatedByString:@":"]; 

    if ([components count] > 1 && 
     [(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) { 
     if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"]) 
     { 

      NSLog([components objectAtIndex:2]); // param1 
      NSLog([components objectAtIndex:3]); // param2 
      // Call your method in Objective-C method using the above... 
     } 
     return NO; 
    } 

    return YES; // Return YES to make sure regular navigation works as expected. 
} 
+0

您是否已正確設置委託? – v1Axvw 2012-07-22 10:20:56

+0

嗨亨利,感謝您的及時迴應。看看viewDidLoad,是不是「webView.delegate = self」就夠了? – Luda 2012-07-22 10:24:14

+0

對不起,沒有看到! – v1Axvw 2012-07-22 13:12:46

回答

0

測試以這種方式,工作對我來說

NSString *myHTML = @"<!DOCTYPE html><html><head>" "<script type='text/javascript'>function myFunction(){alert('ciao');document.location = 'myapp:myfunction:param1:param2';} 
</script>" 
"</head><body><button onclick='myFunction()'>Try it</button>" 
"<p>By clicking the button above,a function will be called.</p></body></html>"; 

應該是你的錯誤,如下所示

document.location = \"myapp:\" + \"myfunction:\" + param1 + \":\" + param2; 

你應該寫,而不是

document.location =\"myapp:myfunction:param1:param2\"; 
+0

謝謝你,你的老虎! – Luda 2012-07-22 10:44:54