UIMenuItem #selector method crash in wkwebview

2019-06-26 08:41发布

问题:

UIMenuItem selector method crashes in iOS 11 beta SDK.

-[WKContentView highlightText]: unrecognized selector sent to instance 0x7f85df8f3200

Method Definition:

func highlightText() 
{
  //
}

I try to add UIMenuItem in WKWebView,

let menuItemHighlight = UIMenuItem.init(title: "Highlight", action: #selector(ContentWebkitView.highlightText))
UIMenuController.shared.menuItems = [menuItemHighlight]

回答1:

I was also getting this error when I was overriding canPerformAction and checking for my custom selector. In my case I wanted to remove all menu items except for my custom one and the following made this work for me.

class ViewController: UIViewController {

    @IBOutlet weak var webView: MyWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        loadWebView()
        setupCustomMenu()
    }

    func loadWebView() {
        let url = URL(string: "http://www.google.com")
        let request = URLRequest(url: url!)
        webView.load(request)
    }

    func setupCustomMenu() {
        let customMenuItem = UIMenuItem(title: "Foo", action:
            #selector(ViewController.customMenuTapped))
        UIMenuController.shared.menuItems = [customMenuItem]
        UIMenuController.shared.update()
    }

    @objc func customMenuTapped() {
        let yay = "