Search code examples
iosswiftuserdefaults

storing background images in userdefaults


I need to be able to set the background image for this button. I need to store this so after the app closes the background image is the same.

eventsFirstButton.backgroundColor = UIColor(patternImage: UIImage(named: "events")!)

Solution

  • You could just save the state:

    Correct answer:

    UserDefaults.standard.set(true, forKey: "TestAnswer1")
    //If the answer is incorrect set to false
    

    On load:

     if UserDefaults.standard.bool(forKey: "TestAnswer1") {
          view.backgroundColor = UIColor.green
          // or any other logic
     } else {
          view.backgroundColor = UIColor.red
          // or any other logic
     }