0

I would like to save the backgroundcolor when you close the app and start it up again. I just don't know how.

I have written it like this:

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


    }
}

I just don't know how to save it when view loads.

  • See [Save/Get UIColor from UserDefaults](https://stackoverflow.com/questions/52999953/save-get-uicolor-from-userdefaults?s=1|126.6132) – rmaddy Dec 10 '18 at 16:18
  • Or, since you only seem to choose between two, save a simple `Bool`. – rmaddy Dec 10 '18 at 16:19

2 Answers2

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)
}

I think you can do that to!

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

if let loadedColor = UserDefaults.standard.value(forKey: "MyKey") as? UIColor {
    // loadedColor
}
A. Amini
  • 521
  • 8
  • 15
  • Sorry I don't understand what you mean in the comment where you say loadedcolor. Can you please explain? –  Dec 10 '18 at 18:18
0

In this particular case declare a Bool property with didSet property observer and save this Bool value to UserDefaults. The value is only saved if it changed.

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

In viewDidLoad load the value

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

In touchesBegan just toggle backgroundColorIsBlue

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    backgroundColorIsBlue.toggle()
}
vadian
  • 274,689
  • 30
  • 353
  • 361