仅在 UITableView 中删除某些行 [Swift 3.0 - Xcode 8]

Making only some rows deletable in a UITableView [Swift 3.0 - Xcode 8]

我有一个数组 fruit = ["Apple", "Orange", "Pear", "Kiwi"],它包含实体 FOOD 并显示在 UItableView 中。有没有办法让一些内容不可删除。例如,我可以让 "Kiwi" 不可删除吗?

有点像, let i = fruit.index(where: "Kiwi") let IArr = [0...fruit.count] IArr = IArr.filter{[=15=] != i} //删除Kiwi的索引

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IArr) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    if editingStyle == .delete{
        let FRUIT = fruit[indexPath.row]
        context.delete(FRUIT)

        appDelegate.saveContext()
        do {
            fruit = try context.fetch(FOOD.fetchRequest())
        }
        catch
        {
            print("did not fetch")}
        }
        tableView.reloadData()}

但是,这不起作用,因为 indexPath 不能采用数组类型。 我该怎么做?

您可以测试索引路径处的行不是 Kiwi:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IArr) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext {

    let FRUIT = fruit[indexPath.row]

    if editingStyle == .delete && FRUIT != "Kiwi" {
        /* delete */
    }
}

如果向左滑动时不显示编辑部分。你可以用这个。

 func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

     let FRUIT = fruit[indexPath.row]

     if (FRUIT != "Kiwi") {
        return true
     }

     return false

    }