webView 中的按钮执行 Objective C 方法

button in webView execute Objective C method

在一个UIWebview中有一个按钮,我需要实现点击这个按钮时跳转到另一个UIView的功能,即执行以下功能:[self performSegueWithIdentifier:@"homePage" sender:self];

我尝试使用 shouldStartLoadWithRequest 函数,但它不起作用。如果你能给我看一个小演示,你将不胜感激!谢谢

<!--index.html-->
<p>Hello World!</p>
<p><h1>Link</h1>
<a href='appintern://home'>Home</a>
</p>
<p>
<h1>Button</h1>
<form method="post" action="home">
    <button type="submit">Continue</button>
</form>
</p>

将 html 加载到网络视图中:

// html path
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
// html data
NSData *htmlData = [NSData dataWithContentsOfFile:htmlPath];
// load html in webview
[self.mainWebView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"utf-8" baseURL:nil];

在委托方法中:

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

    if (navigationType == UIWebViewNavigationTypeFormSubmitted) {
        NSString *destination = [request.URL lastPathComponent];
        if ([destination isEqualToString:@"home"]) {
            NSLog(@"go to home");
            //[self performSegueWithIdentifier:@"homePage" sender:self];
            return NO;
        }
    }
    else if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        // todo
    }

    return YES;
}

希望对您有所帮助。

您需要使用 URL 方案从您的 html 网页与 Obj C 通信:http://www.macstories.net/tutorials/guide-url-scheme-ios-drafts/

让您的提交按钮打开您将驱动您想要的结果的 URL 方案。提示:URL 方案实际上是 API 类调用。您要确保它们包含足够的识别信息,以便可以智能地添加更多方案。