Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have an array fruit = ["Apple", "Orange", "Pear", "Kiwi"] that has Entity FOOD and is presented in an UItableView. Is there a way to make some content undeletable. For example, can I make "Kiwi" undeletable.

Something like, let i = fruit.index(where: "Kiwi") let IArr = [0...fruit.count] IArr = IArr.filter{$0 != i} //deletes the index of 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()}

However, this doesn't work because indexPath cannot take array types. How can I do this?

like image 685
Dan.code Avatar asked Jul 27 '17 21:07

Dan.code


1 Answers

You can test that the row at the index path is not 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 */
    }
}
like image 88
Code Different Avatar answered Sep 30 '22 01:09

Code Different