Home > Back-end >  Is it ok to use UIButton's .tag property for myself?
Is it ok to use UIButton's .tag property for myself?

Time:03-17

I realize that I can create a subclass of UIButton to add custom properties:

class myButton: UIButton {
    var viewBounds          : CGRect = .zero

    ...
}

However, at this moment I only need each button to store an Int, I am not using storyboards, and a lot of postings say that it's alright to use the tag property.

My question is, is this actually safe? Given possible future changes. etc. etc.? "Many postings" is not the same as an official answer, which I can't seem to find an answer to in the official documentation.

CodePudding user response:

It depends on what you're looking to use the tag property for. From the UIView.tag docs, which you have likely seen:

An integer that you can use to identify view objects in your application.

</snip>

You can set the value of this tag and use that value to identify the view later.

The purpose of tag is to be an arbitrary user-settable property that you can use to differentiate between different views of the same type when you don't otherwise have a named reference to them.

UIKit itself will never set tag because the property is meant to be set by you, the app developer; however, that doesn't mean that some 3rd-party framework you're using is guaranteed not to stomp on tag values. Because tag lives in a "global" namespace of sorts (all code has equal access/knowledge to tag, unlike a property you might add yourself), different people might try to use tag for different things.

If you're creating view objects yourself, and managing the view hierarchy directly, then it's relatively safe to use tag. On the other hand, if you're getting views from another framework, or allowing another framework to manage views for you, it may use tag for its own purposes.

From your question, it appears the former is likely the case, but if you need stronger guarantees, you're better off adding another property which more directly identifies the views you'd like to be using.


You also haven't specified what you want to use tag for, necessarily, but if you just need to store an Int that's completely unrelated to identifying the button, I'd advise against using tag and instead add a semantic property that describes what you're trying to store. (Tags are also meant to be unique, which arbitrary data might not be.)

  • Related