How to delete Tableviewcell as a Swift Dictionary

Asked

Viewed 180 times

2

I’m trying to rule out a TableViewCell using Swipe to delete style, but I cannot delete Cells. Cells are being created by a dictionary that creates each with the key as title and value as details.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    //Cria as cells pelo dicionário favDict
    for (key, value) in favDict{
        cell.textLabel?.text = key
        cell.detailTextLabel?.text = value
    }

    return cell
}

func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    return true
}

func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        favDict.removeAtIndex(indexPath!.row) //Linha em que esta dando o erro, aparece que Int não é convertido para [String: String]
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}

2 answers

0

The problem is that you are removing an item from Dictionary in the wrong way.

First, you are passing an integer to a method that does not accept integer:

The method removeAtIndex, in the case demonstrated, expects a parameter of the type DictionaryIndex<String, String> which can be obtained using the indexForKey.

Second, the dictionary is a relationship Key -> Value, so, to delete an item, you need to enter the key related to that value.

So, to be able to delete an item from your dictionary, you first need to find the key related to that position in the table.

let keyArray = Array(favDict.keys)
let key = keyArray[indexPath.row]
favDict.removeValueForKey(key)

0

The problem will be access to indexPath. He’s forcing you to do optional Unboxing with the !. In defining the method, indexPath: NSIndexPath! is already automatically doing Unboxing so just have to use it normally:

Example:

lista.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.