Reputation: 13
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
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
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