Get an Int out of an UILabel Swift

后端 未结 6 1824
执笔经年
执笔经年 2021-01-20 17:22

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

相关标签:
6条回答
  • 2021-01-20 17:59

    You should make sure that the text exists

    var input:Int = (sender.titleLabel.text! as NSString).integerValue
    
    0 讨论(0)
  • 2021-01-20 18:01

    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)
         }
    
     }
    
    0 讨论(0)
  • 2021-01-20 18:08

    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.

    0 讨论(0)
  • 2021-01-20 18:16

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

    var input : Int? = sender.titleLabel.text?.toInt()
    
    0 讨论(0)
  • 2021-01-20 18:19

    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.

    0 讨论(0)
  • 2021-01-20 18:20

    Another way to convert a label in swift:

    let num = getIntFromLabel(labelView)

    0 讨论(0)
提交回复
热议问题