I have the problem, to have a high amount of buttons which have a number as their label, so i thought i could take the label as an integer instead of creating an action for every button?!
@IBAction func NumberInput(sender: UIButton) {
var input:Int = sender.titleLabel as Int
}
connect all your buttons to 1 IBAction. then create the following variable and the set/get methods based on how you will use it.
note: "something" is a UILabel. The variable I wrote below should help you do conversions easily and with cleaner syntax. "newValue" comes with all setter methods. It basically takes into account any value that could possibly used to set "num" to a new value.
You should make sure that the text exists
For Swift 3, what you can do is to directly convert it from an String input to an integer, like this
And then, if for any reason, if you wish to print it out or return is as a String again, you can do
The exclamation mark shows that it is an optional.
If you want to do this, you can convert the
string
to anInt
by usingstring.toInt()
such as:However, I'd suggest either using
UIView.tag
or subclassingUIButton
and adding anInt
property to it to accomplish this, in case you ever change the display of your labels.Another way to convert a label in swift:
let num = getIntFromLabel(labelView)
You can't convert a UILabel to an Int. I think you want this instead: