【问题标题】:Call a method by clicking a button in a UIWebView通过单击 UIWebView 中的按钮调用方法
【发布时间】:2025-12-12 22:00:01
【问题描述】:

我想生成一些 HTML 内容并将其放入 UIWebView。 HTML 包含一些按钮。是否可以为这些按钮定义操作?当有人在 UIWebView 中按下此按钮时,我想在我的 Objective-C 代码中调用一个方法(例如 firstButtonPressed)。

谢谢你帮助我。

【问题讨论】:

    标签: objective-c cocoa-touch uiwebview action


    【解决方案1】:

    看看phonegap项目:www.phonegap.com

    它被设计用来做这种事情,甚至更多。如果有的话,您将能够了解如何对其进行编码,因为该项目是开源的。

    【讨论】:

      【解决方案2】:

      只是跟进这一点,将 HTML/javascript 事件连接到 Objective-c 方法是可能的,而且并不困难。

      Damien Berrigaud 提出了一个 good example 如何通过使用 file:// 链接来做到这一点

      // 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;
      }
      

      【讨论】:

        【解决方案3】:

        此链接http://davinc.me/post/45670387932/call-ios-method-for-html-button-click 帮助我解决同样的问题。

        按钮

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

        然后成为

        的代表

        UIWebView

        然后使用

            - (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;
        }
        

        【讨论】: