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

5

我有一个数组fruit = ["Apple", "Orange", "Pear", "Kiwi"],它属于实体FOOD并在UItableView中显示。是否有一种方法使某些内容不可删除?例如,我能否使"Kiwi"不可删除。

类似这样的代码: let i = fruit.index(where: "Kiwi") let IArr = [0...fruit.count] IArr = IArr.filter{$0 != 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时,您可以简单地禁止删除操作:let FRUIT = fruit[indexPath.row]; if editingStyle == .delete && FRUIT != "Kiwi" { /* delete */ } - Code Different
那是一个简单的答案!谢谢! - Dan.code
你能在答案中发布任何内容,这样我就可以将你的答案标记为正确吗? - Dan.code
我已将其添加为答案。 - Code Different
2个回答

4
您可以测试索引路径处的行是否不是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 */
    }
}

0
如果您在向左滑动时不显示编辑部分,可以使用这个。
 func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

     let FRUIT = fruit[indexPath.row]

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

     return false

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接