You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UIMenuController无法显示多选项:长按仅显示Copy不显示Delete

Fixing Missing Delete Option in UIMenuController for Long Press

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:10:05