Search code examples
iosswiftuitableviewuitableviewrowaction

UITableView Cell not showing Delete Menu


Delete option in Menu not showing

UITableViewCell is not showing the "Delete" option in this popup menu. It goes to the delete condition in the code below, but it is not showing up in the menu.

func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {

    print(action)
    print(action == #selector(delete(_:)))

    if action == #selector(copy(_:)) {
        return true
    }
    if action == #selector(paste(_:)) {
        return true
    }
    if action == #selector(delete(_:)) {
        return true
    }


    return super.canPerformAction(action, withSender: sender)

}

Solution

  • You get cut/copy/paste by default (can block any of these by returning false in canPerformAction) but the other actions (of which you'll see a total of 20 including delete as well as other iOS standard system actions like "selectAll" and "makeTextWritingDirectionRightToLeft") are not included in a UITableViewCell's context menu by default.

    If you want any additional actions to show up you have to implement them in your UITableViewCell subclass.

    e.g. in your cell subclass just add:

    override func delete(_ sender: Any?) {
        print("delete")
    }
    

    And if you return true for the delete selector, you should see the delete item in the context menu for any such cell. performAction in the table view's delegate is still necessary, since otherwise it won't show the menu at all, but the actual handling of the action is in this cell subclass method.

    If you want to add custom actions you can add them to the shared UIMenuController items and also implement them in the UITableViewCell subclass as well. (Used this tutorial as a reference, as well as my own testing).

    e.g. in your view controller's viewDidLoad

    let menuController = UIMenuController.shared
    let item = UIMenuItem(title: "My Custom Action", action: #selector("youraction"))
    var items = menuController.menuItems ?? [UIMenuItem]()
    items.append(item)
    menuController.menuItems = items
    

    Then you'd need to implement "youraction" in your UITableViewCell subclass or else it won't show up.

    Note none of the standard 20 actions you see printed out in canPerformAction should need to be manually added to the shared menu controller, just looks like you need to add them to your cell subclass.