Get an Int out of an UILabel Swift

2019-02-25 01:40发布

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
}

6条回答
老娘就宠你
2楼-- · 2019-02-25 02:17

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)
     }

 }
查看更多
Summer. ? 凉城
3楼-- · 2019-02-25 02:24

You should make sure that the text exists

var input:Int = (sender.titleLabel.text! as NSString).integerValue
查看更多
疯言疯语
4楼-- · 2019-02-25 02:29

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.

查看更多
男人必须洒脱
5楼-- · 2019-02-25 02:30

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.

查看更多
Rolldiameter
6楼-- · 2019-02-25 02:33

Another way to convert a label in swift:

let num = getIntFromLabel(labelView)

查看更多
狗以群分
7楼-- · 2019-02-25 02:39

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

var input : Int? = sender.titleLabel.text?.toInt()
查看更多
登录 后发表回答