paul4tune paul4tune - 3 months ago 28
Swift Question

Custom toggle in iOS

I have 3

Buttons
that need to be toggles i.e.. when I click on one, if any of the other are selected they will be deselected so only one
Button
can be selected at any one time .

Basically update an integer with that particular button selected. I'm not even sure where to start.

Answer

For that batter approach is segmentedControl but if you want this with button then you can create one more instance of UIButton like this and then use it like this way.

var selectedButton: UIButton = UIButton()

Now if you have common method for all 3 button you can try like this

@IBOutlet func buttonClicked(sender: UIButton) {
    self.selectedButton.selected = false
    self.selectedButton = sender
    self.selectedButton.selected = true        
}

If you have 3 different IBAction then create one function like this and call that function from all 3 Button action.

func setSelectedButton(sender: UIButton) {
    self.selectedButton.selected = false
    self.selectedButton = sender
    self.selectedButton.selected = true        
}

Now call this function from all 3 action method like this way.

self.setSelectedButton(sender)
Comments