Another way to handle subview’s actions and states using Enum

Vitalii Zaitcev
2 min readJun 12, 2020

Why use Enum?
• Code becomes more structural and readable
• All logic related to the subview is in one place
• You can pass values
• You will not skip a case, Xcode will highlight this place for you
• Why not?

So let’s get started with building any view you want. In my case, I’ve built some basic EventsView which has three buttons: Button 1, Button 2, and (you not gonna believe it) Button 3.
When it’s done (Layout is set and you know what kind of output and input you expect from your beautiful view), we can start defining enums for Events and States.

Events first, since I have 3 buttons I expect the same amount of events:

After that let’s define what exactly can be changed in the view from outside:

Look’s pretty nice, right? All the logic related to outputs and inputs in one place, under one extension:

I used closure to pass the event, you can use delegate protocol to do that (I included that code also).

Now, when we defined everything, let’s add this view on a ViewController (I will not include code how to do that: you can use a storyboard or define layout programmatically, up to you).

The whole implementation looks like this:

When “Button 1” is pressed, we will update the state of the view — change “Button 1” title to “New Button 1”. When “Button 2” is pressed, we will update its color from systemBlue to red. When “Button 3” is pressed, we will just log the message.

That’s it, now we have a pretty simple, well-structured way of handling view’s output events and its state using enumeration.

Thank you for reading, if you have any questions don’t hesitate to ask them :)

--

--