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
CodePudding user response:
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)
}
}
}
CodePudding user response:
No, tag is integer type
var tag: Int { get set }
If you must want a string tag then you can use custom UIButton with extra variable that is string or character. Like this-
class CustomButton: UIButton {
var customTag:String = ""
}