如何使用NSUserDefault在Swift中存储UISwitch状态

时间:2015-09-18 08:31:05

标签: xcode swift

我有一个名为InGameMusicOnOff的Global Bool,其密钥名为InGameMusicKey。此Bool确定打开应用程序时UIswitch将向左或向右的天气。但它没有工作,换句话说Bool值没有保存到NSUser默认值。所以加班我一个我的应用程序状态与它原来完全相同,即使我通过点击它改变其状态。我只需要保存布尔值。我在swift中使用Xcode 6.4。

代码:

 import AVFoundation
 import Foundation
 import SpriteKit
 import GameKit
 import UIKit
 import iAd

var InGameMusicOnOff = Bool()
var InGameMusicKey = "InGameMusicOnOff"

class SoundController: UIViewController {
 override func viewDidLoad()  {
    super.viewDidLoad()




    if InGameMusicOnOff == true {
        InGameMusicOnOff = true
        NSUserDefaults.standardUserDefaults().objectForKey("InGameMusicOnOff") as! Bool!
    }
    if InGameMusicOnOff == false{
       self.SwitchMain.on = false
       InGameMusicOnOff = false
        NSUserDefaults.standardUserDefaults().objectForKey("InGameMusicOnOff") as! Bool!

    }
  }
     func SwitchMainOnOff() {
    if SwitchMain.on {
        println("SwitchMain is on")
        InGameMusicOnOff = true
        NSUserDefaults.standardUserDefaults().objectForKey("InGameMusicOnOff") as! Bool!

    }
     if SwitchMain.on == false {
        println("SwitchMain is off")
        InGameMusicOnOff = false
         NSUserDefaults.standardUserDefaults().objectForKey("InGameMusicOnOff") as! Bool!           
      }


     @IBAction func SwitchMain(sender: AnyObject) {
         SwitchMainOnOff()


      }
    }

1 个答案:

答案 0 :(得分:1)

这是你可以在用户默认值中保存/获取BOOL(UISwitch状态为bool)的方法:

[[NSUserDefaults standardUserDefaults] setBool:ButtonState forKey:@"buttonState"];
[[NSUserDefaults standardUserDefaults] boolForKey:@"buttonState"];

迅捷方式:

NSUserDefaults.standardUserDefaults().setObject(Bool(false), forKey:"buttonState")
let buttonState = NSUserDefaults.standardUserDefaults().objectForKey("buttonState") as! Bool

if buttonState == true {

}