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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With