Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send string data to UIButton tag?

Is there any way of sending string value to UIButton tag? I know tag is Int type but I need to send string value.

let myButton: UIButton = {
    let button = UIButton()
    button.tag = "123"
    return button
}()

I need to send button.tag as a string

like image 912
Habin Lama Avatar asked Apr 09 '19 06:04

Habin Lama


4 Answers

Create a custom class of UIButton and create one String type property like customTag

class CustomButton: UIButton {
    var customTag:String = ""
}

Assign the custom class to your UIButton and use String type tag by following code.

let myButton: CustomButton = {
    let button = CustomButton()
    button.customTag = "ABC"
    return button
}()
like image 186
AtulParmar Avatar answered Oct 23 '22 07:10

AtulParmar


Instead of tag you can do it using accessibilityLabel.

btn.accessibilityLabel = "ABC"
like image 42
Darshan Kunjadiya Avatar answered Oct 23 '22 08:10

Darshan Kunjadiya


One more answer.

Instead of accessibilityLabel / accessibilityIdentifier or any other related to accessibility , let us go for layer.name

Button.layer.name = "abc123"

@IBAction func wasPressed(_ sender: UIButton) {
   print("was Pressed     \(sender.layer.name)")
}

Reason:

Incase, we are in need to set accessibility for each and every screen, at that time it might affect.

But, if we are in need to add another layer for UIButton, it will not affect

like image 25
McDonal_11 Avatar answered Oct 23 '22 08:10

McDonal_11


Unfortunatly, the tag is just an integer value. What you could do is:

  • Subclass UIButton and add your own property
  • Use associated objects, like in https://gist.github.com/mjjimenez/7956352
  • Use enums for the tag; maybe add an extension to access them
  • (Mis)use the accessibilityIdentifier
like image 27
Andreas Oetjen Avatar answered Oct 23 '22 08:10

Andreas Oetjen