Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView and UIMenuController

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?

Update: I've filed this as radar 18487289.

like image 281
Tom Hamming Avatar asked Sep 25 '14 19:09

Tom Hamming


People also ask

What is a WKWebView?

A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.

What browser does WKWebView use?

WKWebView uses the Nitro JavaScript engine, also used by mobile Safari, which comes with significant performance improvements over UIWebView's older JavaScript engine.

How do I import WKWebView into Objective C?

You can implement WKWebView in Objective-C, here is simple example to initiate a WKWebView : WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init]; WKWebView *webView = [[WKWebView alloc] initWithFrame:self. view. frame configuration:theConfiguration]; webView.


1 Answers

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

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))!
)

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

like image 72
Jonny Avatar answered Oct 05 '22 22:10

Jonny