Repaz Kung Repaz Kung - 2 months ago 7
Objective-C Question

Activate action by reaching a score

How can I set an action by reaching a specific score? for example a pop up or an animation.

import UIKit

class ViewController: UIViewController {

@IBOutlet var ScoreLabel: UILabel!

var taps = 0
var highscore = 200

override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
if let storedTaps = defaults.objectForKey("key") as? Int {
self.taps = storedTaps
setLabel(storedTaps)
}
}

@IBAction func ScoreButton(sender: UIButton) {

taps += 1
setLabel(taps)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(taps, forKey: "key")

}

func setLabel(taps:Int) {
ScoreLabel.text = "Taps: \(taps)"
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.


}
}

Answer

What you can do is implement didSet for the taps variable, which fires every time you set the value of taps, and then check what value it was set to.

Like this:

var taps = 0 {
   didSet {
      if taps == 5 {
          print("You have reaches 5 taps !!")
      }
   }
}
Comments