Kevin Vugts Kevin Vugts - 1 month ago 18
Swift Question

Change button state if a row in tableView is selected

I have a tableView when a row is selected I would like to show a button on the bottom (outside of the tableView) to be shown (isEnabled = true) when I have no rows selected I want it to be set to disabled (isEnabled = false. How can I handle this the best?

Currently I have this logic but when I try to select multiple rows this gives me issues. Because the first select will enable it and the second will disable it.

Here is the code:

I store a true or false in a var on the top called: var someRowSelected = false

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

let selectedCell = tableView.cellForRow(at: indexPath)
selectedCell?.contentView.backgroundColor = UIColor(red: 84.0 / 255, green: 199.0 / 255, blue: 252.0 / 255, alpha: 1)


if(!someRowSelected){
self.someRowSelected = true
nextBtn.isEnabled = true
nextBtn.backgroundColor = UIColor(red: 84.0 / 255, green: 199.0 / 255, blue: 252.0 / 255, alpha: 1)
}else{
self.someRowSelected = false
nextBtn.isEnabled = false
nextBtn.backgroundColor = UIColor.darkGray
}

}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath)
selectedCell?.textLabel?.textColor = UIColor.darkGray

if(!someRowSelected){
self.someRowSelected = true
nextBtn.isEnabled = true
nextBtn.backgroundColor = UIColor(red: 84.0 / 255, green: 199.0 / 255, blue: 252.0 / 255, alpha: 1)
}else{
self.someRowSelected = false
nextBtn.isEnabled = false
nextBtn.backgroundColor = UIColor.darkGray
}
}


I am curious if someone can help me out.

Thank you! :)

Answer

Your code is fine however it will work if only one cell is selected, because what you are essentially doing is changing the value of the Bool to true is selected then false if deselected without checking the total number of selected rows.

The easiest way without changing a lot of your code is to add a new variable called

var rowsSelected = 0 

And in your didSelectRow add one to the rowsSelected += 1 Then in your if statement check if the value of

If rowsSelected is >= 1 { 
//enable and un hide your button
}

On the deselectRow do the opposite and subtract 1 from rowsSelected -= 1 then the If statement if rowsSelected == 0 { //hide the button and disable it}

I hope this helps.

Comments