person101 person101 - 4 months ago 13
iOS Question

How Can I Make the Score Go Up One Point When a Button is Clicked on XCode using Swift

Sorry for the easy question I am very new to IOS developing. What I would like to do is make the UILabel which is set to 0 go up by 1 every time a button is tapped on. Here is the default code given On the ViewController.swift and I have created an Outlet for the Label and Action for the Button.

import UIKit

class ViewController: UIViewController {
@IBOutlet var score: UILabel!

@IBAction func button(sender: UIButton) {


}

override func viewDidLoad() {
super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}


}

Answer
CHANGE LABEL NAME TO BE MORE DESCRIPTIVE
CREATE SCORE VARIABLE AND START IT AT 0 SO YOU HAVE A SCORE TO PRESENT FROM THE START
MAKE IT BEAUTIFUL



import UIKit

class ViewController: UIViewController {
@IBOutlet var scoreLabel: UILabel!
private var score = 0

@IBAction func button(sender: UIButton) {
    score += 1
    scoreLabel.text = "\(score)"
}

override func viewDidLoad() {
    super.viewDidLoad()
        scoreLabel.text = "\(score)"
        scoreLabel.backgroundColor = UIColor.pinkColor()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}


}
Comments