1

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.

Joe
  • 3,772
  • 3
  • 33
  • 64
  • `func toggleButton` ins't a `selector` function, how you is calling the handler of when yours buttons are tapped? – Augusto Mar 31 '19 at 19:09
  • @LeoDabus The last part of my question states the order must go from *first* setting the selected button to true and *then* deselecting all non-selected. Not the other way around. – Joe Mar 31 '19 at 20:47
  • @Joe Yes I just saw the animation part – Leo Dabus Mar 31 '19 at 20:48

1 Answers1

2

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 }
}
AamirR
  • 11,672
  • 4
  • 59
  • 73
  • 1
    You can also add a where clause to your for loop `for button in buttons where button.isSelected && button !== select {` `button.isSelected = false` `}` – Leo Dabus Mar 31 '19 at 20:55