Henrique Dourado
Henrique Dourado

Reputation: 320

I have a bug with a Swift table view cell action

I'm using editActionsForRowAtIndexPath with Swift to add a option to my app cells.

My app is a homework list app, where you can set its subject, its category, the date you need it ready for and add a description. Also, there is a option that when you swipe the cell to the left you will be able to set the homework as Done. To show that, I created a label and added it to the cell, that if the homework is pending, the label will be Pending. If it was set as done, it will be Concluded. The thing is that when I'm setting ONE cell as done, it is setting all the other cells, which is not what I want.

The code I'm using to say that I only want THIS cell to be set as done is this:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCellWithIdentifier("AtivCell") as? AtivCell {


        if !isPending {
            pendencia[indexPath.row] = false
            saveData()
        }

        cell.configureCell(materias[indexPath.row], data: datas[indexPath.row], descricao: descricoes[indexPath.row], pendencia: pendencia[indexPath.row], categoria: categorias[indexPath.row])


        return cell
    } else {
        return AtivCell()
    }
}

Here is the entire project, I really need help, I don't think I did anything wrong. I've tried deleting the app from my iPhone (where I'm testing), tried closing Xcode, tried everything, it just does not work!!!

Link: https://github.com/HenriqueDoura/Agenda/tree/master/agenda-app

Upvotes: 0

Views: 273

Answers (1)

Michael
Michael

Reputation: 9044

You should be using dequeueReusableCellWithIdentifier with the forIndexpath parameter, which always returns a cell. The one you've used requires you to test if it's nil and create one, which you are doing in the else clause and then not initialising it.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("AtivCell", forIndexPath: indexPath) as? AtivCell {

    cell.configureCell(materias[indexPath.row], data: datas[indexPath.row], descricao: descricoes[indexPath.row], pendencia: pendencia[indexPath.row], categoria: categorias[indexPath.row])

    return cell
}

You can use your current function if you want, but you need to declare cell as var, and create it if dequeue returns nil, and then set its values.

Also your !isPending code will not work properly. Within editActionsForRowAtIndexPath, you should be setting pendencia[indexPath.row] = false.

Upvotes: 1

Related Questions