user7346629
user7346629

Reputation:

How do I get the label to display an int?

I'm following a tutorial using Xcode 8.3 and Swift language. This tutorial we're making an app where you input a number (age of your cat) in the text field, press the button, it gets multiplied by 7 then it displays (cat age in cat years) on the label. I followed the instructions exactly but the label isn't changing or updating when I press the button. I'm sure that the label is connected, I'm use that I'm using the right variable names. I don't know what's wrong.

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var ageTextField: UITextField!
    @IBOutlet var ageLabel: UILabel!

    @IBAction func buttonTapped(_ sender: Any) {
        let ageInCatYears = Int(ageTextField.text!)! * 7

        ageLabel.text = String(ageInCatYears)
    }
}

Upvotes: 0

Views: 103

Answers (2)

Suhit Patil
Suhit Patil

Reputation: 12023

First check whether you have correctly hooked up IBOutlets and ABActions from Storyboard to your ViewController. Open Storyboard -> Select ViewController -> Open Assistant Editor -> Connect Outlets and IBAction.

One more thing use if let to unwrap your text

@IBAction func buttonTapped(_ sender: Any) {
   if let num = ageTextField.text, let age = Int(age) {
     let ageInCatYears = age * 7
     ageLabel.text = String(ageInCatYears)
   }
}

Connecting ButtonTapped Action via IBAction

Upvotes: 1

Woof
Woof

Reputation: 1393

  1. Click on your controller in the interface builder.

  2. Click on the connections inspector

  3. Check that all of your outlets and actions are connected

enter image description here

Upvotes: 0

Related Questions