本文介绍了WKWebView和UIMenuController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 WKWebView 的应用程序。在这个应用程序中,我自定义 UIMenuController 中显示的选项。无论我做什么,Web视图似乎都会将复制和定义选项添加到菜单中。如果我将自己设置为第一响应者并为所有内容返回NO,我仍然可以获得复制和定义选项。我已经实现了自己的复制选项,根据用户的喜好和选择的内容做了特殊的事情。有没有办法删除这些额外的选项?

I have an app with a WKWebView in it. In this app, I customize the options presented in the UIMenuController. The web view seems to add Copy and Define options to the menu no matter what I do. If I set myself as first responder and return NO for everything, I still get copy and define options. And I've implemented my own copy option that does special things depending on user preferences and what exactly is selected. Is there a way to remove these extra options?

更新:我已经将其作为雷达18487289提交。

Update: I've filed this as radar 18487289.

推荐答案

对于iOS 11,只需子类 WKWebView 并覆盖 canPerformAction 返回 false

For iOS 11, simply subclass WKWebView and override canPerformAction to return false:

class WebView : WKWebView {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}

适用于iOS 10或更早,swizzle WKContentView canPerformAction 方法:

For iOS 10 or earlier, swizzle WKContentView's canPerformAction method:

@objc private extension UIResponder {
    func swizzle_canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}

guard let viewClass = NSClassFromString("WKContentView") as? UIView.Type else { return }
method_exchangeImplementations(
    class_getInstanceMethod(viewClass, #selector(UIResponder.canPerformAction))!,
    class_getInstanceMethod(UIResponder.self, #selector(UIResponder.swizzle_canPerformAction))!
)

删除这些网页视图的内置菜单项后,您可以添加自定义菜单项通过 UIMenuController.shared 正常。

After remove those web view's build-in menu items, you can add your custom menu items via UIMenuController.shared like normal.

这篇关于WKWebView和UIMenuController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 12:15