如何使用Swift保存背景颜色?

时间:2018-12-10 16:17:32

标签: ios swift

当您关闭应用程序并重新启动时,我想保存背景色。我就是不知道。

我这样写:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    if self.view.backgroundColor == .blue{
        self.view.backgroundColor = .red


    } else if self.view.backgroundColor == .red {
        self.view.backgroundColor = .blue


    }
}

我只是不知道如何在加载视图时保存它。

2 个答案:

答案 0 :(得分:0)

// MARK: - UIColor
extension UIColor {
    convenience init(red: Int, green: Int, blue: Int) {
        precondition(red >= 0 && red <= 255)
        precondition(green >= 0 && green <= 255)
        precondition(blue >= 0 && blue <= 255)

        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
    }

    convenience init(rgb: Int) {
        self.init(
            red: (rgb >> 16) & 0xFF,
            green: (rgb >> 8) & 0xFF,
            blue: rgb & 0xFF
        )
}


let myColorKey = "myColorKey"
let myColorForSaveAsHex = 0xFFff12
self.view.backgroundColor = UIColor(rgb: myColorForSaveAsHex)

// For save color
UserDefaults.standard.set(myColorForSaveAsHex, forKey: myColorKey)

// For load color
if let myLoadedColor = UserDefaults.standard.value(forKey: myColorKey) as? Int {
    self.view.backgroundColor = UIColor(rgb: myLoadedColor)
}

我认为您可以做到!

let myColor = UIColor.red
UserDefaults.standard.set(myColor, forKey: "MyKey")

if let loadedColor = UserDefaults.standard.value(forKey: "MyKey") as? UIColor {
    // loadedColor
}

答案 1 :(得分:0)

在这种情况下,请使用didSet属性观察者声明一个Bool属性,并将此Bool值保存到UserDefaults。该值仅在更改后才保存。

var backgroundColorIsBlue = false {
   didSet {
      self.view.backgroundColor = backgroundColorIsBlue ? .blue : .red
      if backgroundColorIsBlue != oldValue { UserDefaults.standard.set(backgroundColorIsBlue, forKey: "backgroundColor") }
   }
}

viewDidLoad中加载值

func viewDidLoad() {
    super.viewDidLoad()
    backgroundColorIsBlue = UserDefaults.standard.bool(forKey: "backgroundColor")
}

touchesBegan中,只需切换backgroundColorIsBlue

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    backgroundColorIsBlue.toggle()
}