Call a method by clicking a button in a UIWebView

2020-06-17 06:00发布

I want to generate some HTML content and put this into a UIWebView. The HTML contains some buttons. Is it possible to define actions for these buttons? I want to call a method (e.g. firstButtonPressed) in my objective-c code when someone presses this button in the UIWebView.

Thanks you for helping me.

3条回答
Evening l夕情丶
2楼-- · 2020-06-17 06:46

This link http://davinc.me/post/45670387932/call-ios-method-for-html-button-click help me to resolve the same problem.

For button

<a href="didTap://button1"><img src="button1.jpg" /></a>

Then become delegate of

UIWebView

and then use

    - (BOOL)webView:(UIWebView*)aWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *absoluteUrl = [[request URL] absoluteString];
    if ([absoluteUrl isEqualToString:@"didTap://button1"]) {
        [self didTapButton1];
        return NO;
    }
    return YES;
}
查看更多
地球回转人心会变
3楼-- · 2020-06-17 06:47

Take a look at the phonegap project: www.phonegap.com

It is designed to do this kind of thing and more. If anything you will be able to get an idea how to code this as the project is open source.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-06-17 06:56

Just to follow up on this, it is possible, and not to difficult to connect HTML/javascript events to objective-c methods.

Damien Berrigaud came up with a good example of how to do that by using file:// links

// Map links starting with file://
//            ending with #action
// with the action of the controller if it exists.
//
// Open other links in Safari.
- (BOOL)webView: (UIWebView*)webView shouldStartLoadWithRequest: (NSURLRequest*)request navigationType: (UIWebViewNavigationType)navigationType {
  NSString *fragment, *scheme;

  if (navigationType == UIWebViewNavigationTypeLinkClicked) {
    [webView stopLoading];
    fragment = [[request URL] fragment];
    scheme = [[request URL] scheme];

    if ([scheme isEqualToString: @"file"] && [self respondsToSelector: NSSelectorFromString(fragment)]) {
      [self performSelector: NSSelectorFromString(fragment)];
      return NO;
    }

    [[UIApplication sharedApplication] openURL: [request URL]];
  }

  return YES;
}
查看更多
登录 后发表回答