UITableView 单元格不显示删除菜单

UITableView Cell not showing Delete Menu

UITableViewCell 未在此弹出菜单中显示 "Delete" 选项。在下面的代码中进入了删除条件,但是在菜单中没有出现。

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)

}

默认情况下你得到 cut/copy/paste(可以通过 returning falsecanPerformAction 中阻止其中任何一个)但是其他操作(你会看到默认情况下,UITableViewCell 的上下文菜单中不包含总共 20 个,包括删除以及其他 iOS 标准系统操作,如 "selectAll" 和 "makeTextWritingDirectionRightToLeft")。 24=]

如果您想要显示任何其他操作,您必须在 UITableViewCell 子类中实现它们。

例如在您的单元格子类中只需添加:

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

如果您 return true 用于删除选择器,您应该会在任何此类单元格的上下文菜单中看到删除项。 table 视图的委托中的 performAction 仍然是必需的,否则它根本不会显示菜单,但实际的操作处理是在这个单元格子类方法中。

如果您想添加自定义操作,您可以将它们添加到共享的 UIMenuController 项中,并在 UITableViewCell 子类中实现它们。 (使用 this tutorial 作为参考,以及我自己的测试)。

例如在你的视图控制器中 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

然后你需要在你的 UITableViewCell 子类中实现 "youraction" 否则它不会出现。

注意 none 您在 canPerformAction 中看到的标准 20 个操作应该需要手动添加到共享菜单控制器,看起来您需要将它们添加到您的单元格子类.