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.
}
您是否已正確設置委託? – v1Axvw 2012-07-22 10:20:56
嗨亨利,感謝您的及時迴應。看看viewDidLoad,是不是「webView.delegate = self」就夠了? – Luda 2012-07-22 10:24:14
對不起,沒有看到! – v1Axvw 2012-07-22 13:12:46