Reputation: 3961
I have an array of 5 different button outlets. When any of the buttons are pressed, that button should FIRST be selected, and then every other button in the array should be deselected.
Here's my progress so far:
func toggleButton(select:UIButton) {
select.isSelected = true
let buttons = [button1, button2, button3, button4, button5]
for button in buttons as! [UIButton] {
if button.isSelected == true{
button.isSelected = true
} else {
button.isSelected = false
}
}
}
I first select the button (with select.isSelected = true
), and then iterate over the button array to determine if it's selected. If it's not selected (meaning it wasn't pressed), then it should change isSelected to false.
The issue is every button that gets pressed changes to selected, and then remains selected once other buttons are pressed.
How can I set up the toggle so that tapped button FIRST gets selected, and then all other buttons (besides the selected button) get deselected? Note: It's important that it's in that order due to an animation that runs.
Upvotes: 1
Views: 1233
Reputation: 12208
You can skip the button if its same instance as select
using !== operator, and there are multiple ways
1) Within the for-in loop
func toggleButton (select: UIButton) {
select.isSelected = true
let buttons: [UIButton] = [button1, button2, button3, button4, button5]
for button in buttons {
if button.isSelected && button !== select {
button.isSelected = false
}
}
}
2) filter desired buttons in array
func toggleButton (select: UIButton) {
select.isSelected = true
let buttons: [UIButton] = [button1, button2, button3, button4, button5]
buttons.filter({ $0.isSelected && $0 !== select }).forEach { $0.isSelected = false }
}
Upvotes: 2