通过单击UIWebView中的按钮来调用方法

时间:2010-03-02 13:30:38

标签: objective-c cocoa-touch uiwebview action

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

感谢您帮助我。

3 个答案:

答案 0 :(得分:4)

为了跟进这一点,将HTML / javascript事件连接到objective-c方法是可能的,而不是很困难。

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

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

答案 1 :(得分:1)

此链接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;
}

答案 2 :(得分:0)

看一下phonegap项目:www.phonegap.com

它旨在做更多这样的事情。如果有什么,你将能够知道如何编写这个,因为项目是开源的。