Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a string property to a UIButton in Swift

How can I associate a string property with a UIButton in Swift? I don't want the string to appear as the button text, simply to be assigned to the button as an identifier or a key. Here is what I have so far:

func createAnswerButtons() {

    var index:Int
    for index = 0; index < self.currentQuestion?.answers.count; index++ {

        // Create an answer button view
        var answer:AnswerButtonView = AnswerButtonView()
        selection.setTranslatesAutoresizingMaskIntoConstraints(false)

        // Place into content view
        self.scrollViewContentView.addSubview(answer)

        // Add a tapped gesture recognizer to the button
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("answerTapped:"))
        answer.addGestureRecognizer(tapGesture)

        // Add constraints etc

        // Set the answer button text
        let answerText = self.currentQuestion!.answers[index]
        answer.setAnswerText(answerText)

        // Set the identifier for each answer button
        self.identifier = self.currentQuestion!.answerIdentifier[index]

        // Add to the selection button array
        self.answerButtonArray.append(answer)
}

So I think I need something after

// Set the identifier for each answer
        self.identifier = self.currentQuestion!.answerIdentifier[index]

To assign the identifier to the button.

The reason for this is I'm trying to implement a decision tree logic so that I can keep track of each answer button that is tapped to generate a code string that will correspond to a final result.

like image 830
brad88 Avatar asked May 13 '15 12:05

brad88


People also ask

How do you make a UIButton multiline?

To make a multi-line text in UIButton, you insert a new line character ( \n ) wherever you want in button title and set lineBreakMode to byWordWrapping . You can adjust text alignment with . textAlignment .

What is UIButton Swift?

A control that executes your custom code in response to user interactions.


2 Answers

Use

button.accessibilityIdentifier = "some text"

istead of tag.

like image 81
Emre AYDIN Avatar answered Oct 23 '22 14:10

Emre AYDIN


You can use accessibilityIdentifier property of UIButton.

@IBOutlet weak var button: UIButton!
button.accessibilityIdentifier = "Some useful text"
like image 44
ujjwal Avatar answered Oct 23 '22 12:10

ujjwal