Matt Jacquet Matt Jacquet - 3 months ago 10
iOS Question

enabling button in swift code

I begin swift and i'm making an app ( a little game).
The buttons of levels 2,... are not enabled because the user dont yet win the level 1 when the user install the application. then I want these buttons enabled everytime the user won the level. I wrote this in a file:

class levelList: UIViewController {
@IBOutlet var blvl1: UIButton!
@IBOutlet var blvl2: UIButton!
@IBOutlet var blvl3: UIButton!

var lvlWon1: Bool = false {
didSet {
blvl2?.enabled = lvlWon1

}
}

var lvlWon2: Bool = false {
didSet {
blvl3?.enabled = lvlWon2
}
}
let lvl1Default = NSUserDefaults.standardUserDefaults()
let lvl2Default = NSUserDefaults.standardUserDefaults()


override func viewDidLoad() {

if (lvl1Default.objectForKey("lvlWon1") != nil){
lvl1Default.setBool(true, forKey: "lvlWon1")
lvlWon1 = lvl1Default.valueForKey("lvlWon1") as! Bool!
}
else{
lvl1Default.setBool(false, forKey: "lvlWon1")
lvlWon1 = lvl1Default.valueForKey("lvlWon1") as! Bool!
}

//
if (lvl2Default.objectForKey("lvlWon2") != nil){
lvl2Default.setBool(true, forKey: "lvlWon2")
lvlWon2 = lvl2Default.valueForKey("lvlWon2") as! Bool!
}
else{
lvl2Default.setBool(false, forKey: "lvlWon2")
lvlWon2 = lvl2Default.valueForKey("lvlWon2") as! Bool!
}

}
}


and this in an other file:

class lvl1: UIViewController {

var levelList = levelList()
@IBOutlet var bNext: UIButton!
@IBAction func nextlvl(sender: UIButton) {
levelList.lvlWon1 = true
levelList.lvlWon1 = levelList.lvl1Default.valueForKey("lvlWon1") as! Bool!
let lvl1Default = NSUserDefaults.standardUserDefaults()
lvl1Default.setValue(listeNiveaux.lvlWon1, forKey:"lvlWon1")
lvl1Default.synchronize()
}


//my problem is that all work finely when I wrote:

var lvlWon1: Bool = false {
didSet {
blvl2?.enabled = lvlWon1

}
}


so when i won the
lvl 1
, the
level2 button
is enabled, but when i add

var lvlWon2: Bool = false {
didSet {
blvl3?.enabled = lvlWon2
}
}


when I win the
level1
, the
blvl2
and the
blvl3
are enabled, I don't know why

I think it's because i save the data of all
blvl
but i'm not sure.
thanks in advance and really sorry for my english, it's not my first language.

Answer

I finally found the solution :

 import UIKit

class ViewController: UIViewController {

 var defaults = NSUserDefaults.standardUserDefaults()

 @IBOutlet weak var startSecondLevelButton: UIButton!

 override func viewDidLoad() {
super.viewDidLoad()

self.checkLevelsStatuses()
    }

 func checkLevelsStatuses() {

startSecondLevelButton.enabled = false

if let lvlWon1 = defaults.objectForKey("lvlWon1") as? Bool {
    // if true - level finished
    if (lvlWon1) {
        startSecondLevelButton.enabled = true
    }
}else {
    defaults.setBool(false, forKey: "lvlWon1")
}

if let lvlWon2 = defaults.objectForKey("lvlWon2") as? Bool {

} else {
    defaults.setBool(false, forKey: "lvlWon2")
}

}

that was because the viewDidLoad was wrong.