Rolexboy8008
Rolexboy8008

Reputation: 13

Button as a variable

I am trying to have a variable set to a buttons label. I have something like this:

@IBOutlet weak var myButton: UIButton!

var myVariable = String()

@IBAction func ButtonPressed(_ sender: Any) {
    myVariable = myButton.titleLabel
}

Can anyone tell my how I can make this work?

Upvotes: 0

Views: 94

Answers (2)

Chris Edgington
Chris Edgington

Reputation: 3236

You're nearly there, you're just missing the text property. Also you might want to set your variable as an optional.

@IBOutlet weak var myButton: UIButton!

var myVariable: String?

@IBAction func ButtonPressed(_ sender: Any) {
    myVariable = myButton.titleLabel?.text
}

Upvotes: 0

Milan Nosáľ
Milan Nosáľ

Reputation: 19737

titleLabel is an instance of UILabel. Your myVariable is a String property. That does not match typewise. You can access titleLabel directly, as in:

myVariable = myButton.titleLabel?.text ?? ""

But UIButton class defines a title(for:) method to access title of the button for various states.

Thus, in your case I would recommend using following:

@IBOutlet weak var myButton: UIButton!

var myVariable = String()

@IBAction func ButtonPressed(_ sender: Any) {
    myVariable = myButton.title(for: .normal) ?? ""
}

Upvotes: 2

Related Questions