In Swift you probably know how anoying it is to change the state of all your UIButtons when something happens in the state your app. Let’s say the user pressed the save-button. On that action you’re not only going to save something (obviously), but you probably want to change the .isEnabled-state of several other buttons. Soon enough you’ll be ending up with something like this and you get the same ‘row of missery’ over and over again.
1 2 3 4 5 6 7 8 |
submitBtnLabel.isEnabled = true removeBtn.isEnabled = false endBtnLabel.isEnabled = true startBtnLabel.isEnabled = false resetButton.isEnabled = false editBtn.isEnabled = false |
An easier way to handle the UIButtons
However, fortunately there are better ways! I use the code beneath to keep things cleaner and more compact.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
func disAndEnableMultipleButtons(buttons: [UIButton], dissAble: [Bool]) { for (index, button) in buttons.enumerated() { switch dissAble[index] { case true: button.isEnabled = false button.alpha = 0.3 case false: button.isEnabled = true button.alpha = 1.0 } } } |
As you can see I’ve created one function to set all UIButton-states. We can put them in an array of buttons we want to change the state of. And an array of bools which we can use to say if the button should be enabled or disabled. For this to work I enumerate over the array of buttons and use the index to set the button-states with a switch. It works fine, the trap is you have make sure you don’t make mistakes with the orders of both array’s. Both parameters obviously have to be in order, so you will you disable and enable the right UIButtons!
Works for me, hope it does for you!