Please do NOT use View tags in your Swift project

Please?

Steven Curtis
4 min readOct 26, 2021

View Tags. Aren’t they great?

Photo by Paul Skorupskas on Unsplash

The code for this article is stored right HERE

Never use them

The compiler does not enforce the use of unique tags. Worse, some programmers use tags in order to reference arrays of data in their code.

You’re doing it wrong

You can add tags to views in the storyboard

or you can do it programatically

let view = UIView()
view.tag = 0

now (for this example’s sake) both have a tag of 0. One reason for choosing 0 for the example is that 0 is set in the storyboard if you do not choose to set any particular tag. That said, it is for this example only.

Discovering the tag in views.

This can be done programatically, and for each of these we print out the tag.

for subView in view.subviews {
print(subView.tag)
}

Now in my example App I’ve included two UIView on the storyboard. Now guess the output — what do you think will happen?

0
0

Both of the subviews in this case have the same tag. 0. We are relying on our programmer (or perhaps ourselves) to be…

--

--

Responses (3)