Search code examples
iosswiftuimenucontrolleruimenuitem

How to Remove UIMenuController Default Items In Swift


I'm trying to remove the items Look Up & Share... from the UIMenuController. How would I specifically remove the two and keep my custom one. Here is what I've achieved so far:

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        // add two custom menu items to the context menu of UIWebView (assuming in contenteditable mode)


        let menuItem1 = UIMenuItem(title: "My Button", action: #selector(myButtonSel))
        UIMenuController.shared.menuItems = [menuItem1]

    }

Here is the canPerformAction I have:

  override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {

        //let shareSelector: Selector = NSSelectorFromString("_share:")

        if webView?.superview != nil {
            if action == #selector(myButtonSel){
                return true
            }
        }

        return super.canPerformAction(action, withSender: sender)
    }

Also for some odd reason, when I try to remove all the default items and keep only my custom, it does not work. Here is the code I attempted for that:

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {

    //let shareSelector: Selector = NSSelectorFromString("_share:")

    if webView?.superview != nil {
        if action == #selector(myButtonSel){
            return true
        }
        else {

            return false
        }
    }

    return super.canPerformAction(action, withSender: sender)
}

Even when I try to remove all of the other items and keep my custom, I'm not able to do so. All I'm able to do is add my custom item.


Solution

  • I tried this but it worked for my by subclassing the WebView and overriding canPerformAction method, inside which I manually removed the default options.

    override func canPerformAction(_ action: Selector, withSender sender: AnyObject?) -> Bool {
        if action == #selector(cut(_:)) {
          return false
        }
        if action == #selector(paste(_:)) {
          return false
        }
        if action == #selector(select(_:)) {
          return false
        }
        if action == #selector(selectAll(_:)) {
          return false
        }
        ...
    
        return super.canPerformAction(action, withSender: sender)
      }
    

    I referred to this answer by Ike10 and it had worked for me. Give it a shot.