benjiiiii
benjiiiii

Reputation: 478

Changing the colour of a row on button press - swift

I have the following code which makes two buttons appear when a UITableView Row is swiped left.

override func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
    let more = UITableViewRowAction(style: .normal, title: "Picked") { action, index in
        print("Stock Picked")

    }
    more.backgroundColor = .green

    let favorite = UITableViewRowAction(style: .normal, title: "Not Enough") { action, index in
        print("Not enough stock to pick")
    }
    favorite.backgroundColor = .orange



    return [favorite, more]
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

I'm now trying to make it so that if one of the buttons is pressed the row it appears on will change colour. I.e if a row is swiped left and the Picked button is pressed then the row colour will turn green.

I would also like it to set some kind of flag on the row which will only allow the application to move forward when all rows have the flag set to true.

Any advice greatly appreciated.

Upvotes: 2

Views: 1137

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

To change the cell color on edit action you should get the cell using the cellForRowAtIndexpath method of UITableView and change the background color to your desired color, this must be done inside of the action block provided by the UITableViewRowAction

override func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
    let more = UITableViewRowAction(style: .normal, title: "Picked") { action, index in
        print("Stock Picked")
        let cell = tableView.cellForRow(at: index) as? UITableViewCell
        cell?.backgroundColor = .green
    }
    more.backgroundColor = .green

    let favorite = UITableViewRowAction(style: .normal, title: "Not Enough") { action, index in
        print("Not enough stock to pick")
        let cell = tableView.cellForRow(at: index) as? UITableViewCell
        cell?.backgroundColor = .orange
    }
    favorite.backgroundColor = .orange


    return [favorite, more]
}

Upvotes: 3

Related Questions