Search code examples
iosiphoneswiftswift4uimenucontroller

Can't show more than one option to UIMenuController


I want to make a longPress to a message and show two options in UIMenuController

Delete and Copy

but only Copy is showing

@objc func longPressLabel(sender: AnyObject?) {
   becomeFirstResponder()

   let copyMenuItem = UIMenuItem(title: “Copy”.localized, action: #selector(copyTapped))
   let deleteMenuItem = UIMenuItem(title: “Delete”.localized, action: #selector(deleteTapped))

   let menu = UIMenuController.shared

   menu.arrowDirection = UIMenuControllerArrowDirection.down
   menu.setTargetRect(bounds, in: self)
   menu.menuItems = [copyMenuItem, deleteMenuItem]

   menu.setMenuVisible(true, animated: true)

}

Also If I delete all UIMenuItems and I make a empty menu this show me a copy option, it's like it's showing a template and not the options I add

I'm using IOS 11.1 and Swift4.1

Here is an Example


Solution

  • I added this method

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
           if action == #selector(deleteTapped(_:)) || action == #selector(copyTapped(_:)) {
               return true
           }
           return false
       }
    

    This helps to say what events are defined. if the action is deleteTapped or Copytapped It will return true and will show it.