UIWebView - 创建自定义上下文菜单?

时间:2011-09-08 10:27:41

标签: iphone css uiwebview contextmenu

我在我的应用程序中添加了UIWebView控件。

要禁用默认上下文菜单,我实现了webViewDidFinishLoad。

- (void) webViewDidFinishLoad:(UIWebView *)theWebView {
    NSString *varMySheet = @"var mySheet = document.styleSheet[0];";
    NSString *addCSSRule = @"function addCSSRule(selector, newRule) {"
        "if (mySheet.addRule) {"
        "mySheet.addRule(selector, newRule);"
        "} else {"
        "ruleIndex = mySheet.cssRules.length;"
        "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex;"
        "}"
        "}";
    ...
    NSString *insertRule = @"addCSSRule('body', '-webkit-touch-callout: none;')";

    [webView stringByEvaluatingJavaScriptFromString:varMySheet];
    [webView stringByEvaluatingJavaScriptFromString:addCSSRule];
    [webView stringByEvaluatingJavaScriptFromString:insertRule];
    ...
}

但是webview的上下文菜单并没有消失。任何人都帮助我。

我也试过

[webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"];

它不起作用。 感谢。

2 个答案:

答案 0 :(得分:0)

你能解释为什么你要尝试使用这些javascript吗? 只是做以下事情对你来说还不够吗?

- (void) webViewDidFinishLoad:(UIWebView *) sender {
    // Disable the defaut actionSheet when doing a long press
    [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"];
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
}

答案 1 :(得分:0)

您只需要子类化UIWebView。在您的自定义视图中,只需实现方法canPerformAction:withSender,如下所示:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  return NO;
}

然后所有菜单项都会消失。如果您只想显示某些项目,则应为指定项目返回YES。

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  BOOL ret = NO;
  if (action == @selector(copy:)) ret = YES;
  return ret;
}

当您在视图中长按一个单词时,只能“复制”。

相关问题