Christoph Drescher
Christoph Drescher

Reputation: 67

Button is not changing a value?

I wrote a code to create a Button which should change the value of a label/textfield. I wanted to make a push-up App and every time you touch the button on the screen, the label '' Your Score: 0'' increase the score with 1, I have tried it as textfield too. But it's not working, nothing is happening! Can someone help me?

Label Code:

func setupHelloWorld() {
        helloworld.textAlignment = .center
        helloworld.text = "Your Score: \(score)"
        helloworld.textColor = .gray
        helloworld.font = .boldSystemFont(ofSize: 30)
        self.view.addSubview(helloworld)
        

...

Button code:

func setUpNetButton() {
        nextButton.backgroundColor = .blue
        nextButton.setTitleColor(.white, for: .normal)
        nextButton.setTitle("Tap!", for: .normal)
        
        nextButton.addTarget(self, action: #selector(nextButtonTapped), for: .touchUpInside)
        
        
        view.addSubview(nextButton)
        setUpNextButtonConstraints()
    }
    
    @objc func nextButtonTapped() {
        score += 1
}

Upvotes: 0

Views: 143

Answers (2)

Vadim Belyaev
Vadim Belyaev

Reputation: 2859

You have to manually update the text property of the label. Just because you initially set its text using the score variable, it will not automatically react to any changes of the variable's value afterward unless you explicitly set the new label text.

Change your code to something like this and it will work:

func setupHelloWorld() {
        helloworld.textAlignment = .center
        helloworld.textColor = .gray
        helloworld.font = .boldSystemFont(ofSize: 30)
        updateButtonText()
        self.view.addSubview(helloworld)
}
...
@objc func nextButtonTapped() {
        score += 1
        updateButtonText()
}

func updateButtonText() {
        helloworld.text = "Your Score: \(score)"
}

Alternatively, instead of calling the updateButtonText from the nextButtonTapped() method, you can add a didSet observer to your score property and change the label text each time it gets assigned a new value. However, you'll still need to update the label's text when you view has loaded because didSet won't be called during the initialization of the class. Something like this:

private var score: Int = 0 {
    didSet {
        updateButtonText()
    }
}

override func viewDidLoad() {
    ...
    updateButtonText()
    ...

Upvotes: 3

Paramveer Singh
Paramveer Singh

Reputation: 36

It is because you are not changing the value of helloworld assign the value to helloworld.text in @objc function nextButtonTapped() after the score is updated

Upvotes: 0

Related Questions