3

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
}
André Kuhlmann
  • 4,378
  • 3
  • 23
  • 42

6 Answers6

4

If you want to do this, you can convert the string to an Int by using string.toInt() such as:

if let input = sender.titleLabel?.text?.toInt() {
    // do something with input
} else {
    // The label couldn't be parsed into an int
}

However, I'd suggest either using UIView.tag or subclassing UIButton and adding an Int property to it to accomplish this, in case you ever change the display of your labels.

Matt Bridges
  • 48,277
  • 7
  • 47
  • 61
3

You should make sure that the text exists

var input:Int = (sender.titleLabel.text! as NSString).integerValue
Marius Fanu
  • 6,589
  • 1
  • 17
  • 19
0

You can't convert a UILabel to an Int. I think you want this instead:

var input : Int? = sender.titleLabel.text?.toInt()
SnoopyProtocol
  • 911
  • 8
  • 10
  • Now its an **Int?** but now i can't do anything with this, or?! (calculations) – André Kuhlmann Mar 27 '15 at 17:10
  • I think what you want to do is connect each button in the interface builder to that IBAction method you have. Then you can create if statements to execute different actions depending on the button number. – SnoopyProtocol Mar 27 '15 at 18:22
0

Another way to convert a label in swift:

let num = getIntFromLabel(labelView)

Natasha
  • 54
  • 6
0

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.

 var num : Int {
     get { 
         return Int(something!)!
     }
     set {
         something.text = Int(newValue)
     }

 }
Muhammad
  • 109
  • 1
  • 9
0

For Swift 3, what you can do is to directly convert it from an String input to an integer, like this

Int(input.text!)

And then, if for any reason, if you wish to print it out or return is as a String again, you can do

String(Int(input.text!)!)

The exclamation mark shows that it is an optional.

haxgad
  • 387
  • 4
  • 9