liangdapang
liangdapang

Reputation: 312

can I set UIButton a tag with letter?

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

enter image description here

Upvotes: 0

Views: 100

Answers (2)

Imran0001
Imran0001

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

Raja Kishan
Raja Kishan

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)
        }
    }
}

enter image description here

Upvotes: 4

Related Questions