Reputation: 312
I encountered a puzzle. I have many buttons. I want to set tag for them respectively, but it seems that tag can only be set as a number, which is inconvenient for me to read the code. I want to set a name similar to “abc”. Is there any way or other way
Upvotes: 0
Views: 100
Reputation: 628
No, tag is integer type
var tag: Int { get set }
But there is alternative way to do this.
Firstly create a class -
class CustomButton: UIButton {
var customTag:String = ""
}
And then you can use it as -
let btn = CustomButton()
btn.customTag = "abcd"
btn.backgroundColor = .green
btn.setTitle("your title", for: .normal)
Upvotes: 2
Reputation: 18924
You can create your own property like this
extension UIButton {
private struct AssociatedKeys {
static var stringTag = "stringTag"
}
@IBInspectable var stringTag: String? {
get {
guard let stringTag = objc_getAssociatedObject(self, &AssociatedKeys.stringTag) as? String else {
return nil
}
return stringTag
}
set(value) {
objc_setAssociatedObject(self, &AssociatedKeys.stringTag, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
Upvotes: 4