How to enable and disable multiple UIButtons?

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.

 

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.

 

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!