-1

I'm creating a fitness app in Xcode where different activities are worth different points and the user has a total points on the homepage. I am trying to convert the UILabel (which I have specified the points for each challenge) to an Integer so I can calculate the users total points when they have chosen that challenge.

I believe that I need to do this using Swift and have connected the UILabel to an outlet and given the calculating button an action, however I cannot figure out how to get an Int Value from the UILabel in order to do the calculation.

Please can anyone help with how to do this, or if you can think of a better way of doing so.

Thanks in advance

I've got this, no errors but nothing happens when button is pressed. I'm aiming to add the new points to the current points but trying to get this part working first.

@IBAction func Calculate(_ sender: Any) {

    if let NewPointsText = NewPoints.text,
        let NewPointsValue = Int(NewPointsText){
        print(NewPointsValue)
    } else{
        print("Not Worked")
    }

    if let CurrentPointsText = CurrentPoints.text,
        let CurrentPointsValue = Int(CurrentPointsText){
        print(CurrentPointsValue)
    }else{
        print("Current Points Not Worked")
    }

}

}

user1655326
  • 1
  • 1
  • 3

2 Answers2

2

You need to first get the text from UILabel, and the convert it to Int value using the initializer.

    if let text = self.label.text, let value = Int(text) {
        //Write your code here
    }

The initializer returns nil if the string cannot be converted into an Int value and non-nil Int value otherwise, i.e.

  1. Int("hello") returns nil
  2. Int("10") returns 10.
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • 1
    You sir have been much more helpful than any others. I have been looking for a solution for days and haven't found anything that works until finding this. May seem like a simple line of code but it's been the only thing that works from the hundreds of answers I've found on Stackoverflow. – Superlative Dec 30 '19 at 11:47
0

Using if let you can easily try to extract the value:

@IBOutlet var label: UILabel!

@IBAction func calculateStuff(sender: UIButton) {
    // do stuff

    if let labelText = label.text,
        let intValue = Int(labelText) {

        // use intValue as you want
    } else {
        // if label did not contain an integer, you can react here
    }
}
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90