UIMenuController无法显示多选项:长按仅显示Copy不显示Delete
Hey there! Let's troubleshoot why only the Copy option is showing up in your UIMenuController when long-pressing your message label. Here are the key fixes you need to apply:
1. Implement canPerformAction(_:withSender:)
UIMenuController checks this method to determine which menu items should be visible. You need to explicitly return true for both your Copy and Delete actions:
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { // Allow both Copy and Delete actions to appear if action == #selector(copyTapped) || action == #selector(deleteTapped) { return true } // Fall back to superclass behavior for other actions return super.canPerformAction(action, withSender: sender) }
2. Confirm deleteTapped is exposed to Objective-C
Since UIMenuController relies on Objective-C selectors, make sure your delete method is marked with @objc (just like your copy method):
@objc func deleteTapped() { // Add your delete logic here (e.g., remove the message from your data source) print("Delete action triggered!") }
3. Ensure your view can become first responder
Your view needs to be eligible to become the first responder for the menu controller to attach to it. Add this override:
override var canBecomeFirstResponder: Bool { return true }
4. Assign both menu items to the controller
In your existing longPressLabel method, make sure you're setting both menu items to the shared UIMenuController. You might have missed this critical line:
@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 = .down menu.setTargetRect(bounds, in: self) // Add this line to include both Copy and Delete menu.menuItems = [copyMenuItem, deleteMenuItem] menu.setMenuVisible(true, animated: true) }
Putting all these pieces together should make both options appear when you long-press your message label.
内容的提问来源于stack exchange,提问作者BlueSeph

