The button functionality works, if the score passes 5 it works, and if I set the variable score equal to a number greater than it already is, it saves that high score, how do I get it to increment and save the high score when the button is clicked (if the button went higher than the high score)?
If I set score equal to 100 explicitly, and then reset it to a lower number, say 14, the screen will still display 100. How do I get this to use the button so I don't have to use the variable to set the number, let's say if the user clicks the button 120 times, the screen text will be 120, not 100?
Thank you.
var score = 0
class ViewController: UIViewController {
//0...n
@IBOutlet weak var textLabel: UILabel!
//image
@IBOutlet weak var image: UIImageView!
//adds 1
@IBAction func addButton(sender: AnyObject) {
++score
textLabel.text = String(score)
if textLabel.text >= "5" {
image.image = UIImage(named: "win")
}
}
func newScore() -> Int {
var highScore = NSUserDefaults.standardUserDefaults().integerForKey("highscore")
if score > highScore {
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
highScore = score
}
return highScore
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textLabel.text = String(newScore())
if textLabel.text >= "5" {
image.image = UIImage(named: "win")
}
textLabel.text = String(newScore())
}
Aucun commentaire:
Enregistrer un commentaire