Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an extension of UIView with a variable string parameter in Swift? [duplicate]

Tags:

ios

swift

I want all my views have a property stored like a tag, but it has to be type of String. So I tried using an extension for it.

But I got the error saying extensions my not contain stored properties.

The question is, how to store a string in each UIView in my app like a tag?

Thanks!

like image 714
Jacob Smith Avatar asked Nov 24 '25 11:11

Jacob Smith


1 Answers

You can use the setAssociatedObject and getAssociatedObject defined in the objective c runtime to achieve this.

import ObjectiveC

var AssociatedObjectKey: UInt8 = 7
extension UIView
{
    var myOwnTag: String?
    {
        get
        {
            return getAssociatedObject(self, associativeKey: &AssociatedObjectKey) as? String ?? ""
        }

        set
        {
            var propertyVal : String? = nil
            if let value = newValue
            {
                propertyVal = value
            }
            setAssociatedObject(self, value: propertyVal, associativeKey: &AssociatedObjectKey, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

You can refer this blog for more details.

like image 182
Midhun MP Avatar answered Nov 26 '25 01:11

Midhun MP