Search code examples
iosswiftcocoa-touchnsuserdefaults

Saving custom background color with userDefaults


I created a grid with some buttons, each button is associated to a certain color and changes the view's background color:

 @IBOutlet weak var backgroundSelectionView: UIView!
 override func viewDidLoad() {
        super.viewDidLoad()

      backgroundSelectionView.isHidden = true
        backgroundSelectionView.isUserInteractionEnabled = false
        backgroundGrid()
    }
@IBAction func backgroundColor(_ sender: Any) {
        if backgroundSelectionView.isHidden == true {
            backgroundSelectionView.isHidden = false
            backgroundSelectionView.isUserInteractionEnabled = true
        } else {
            backgroundSelectionView.isHidden = true
            backgroundSelectionView.isUserInteractionEnabled = false
        }
    }
    func backgroundGrid(){
       blackButtonOutlet.layer.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        blackButtonOutlet.layer.borderWidth = 1
        blackButtonOutlet.layer.borderColor = UIColor.black.cgColor
    }
    @IBOutlet weak var blackButtonOutlet: UIButton!

    @IBAction func blackButton(_ sender: Any) {
       view.layer.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)

    }

Right now it works fine, if I press the button it sets the background and everything looks nice. The only problem is that when I navigate in the app or leave it, the background becomes white(default) again. I'd like to set it with userDefaults, how do I do it?


Solution

  • I don't see the other buttons and where you change the background color but let's assume you are using an HeX represantation of a color ypu could save the background color in shared preferences and always use the shared state to set the background.

    When you want to save the color to user prefs: UserDefaults.standard.set("#FF2200", forKey: "background_color_hex")

    To retrieve the HEX represantation of background color from prefs: let hexBackgroundColor = UserDefaults.standard.string(forKey: “background_color_hex”) ?? “#FFFFFF”.

    Then to use it you can have an extension to get a UIColor based on its hex represantation like explained in many articles online, take for example this one https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor like this: view.backgroundColor = UIColor(hex: hexBackgroundColor)

    There can be a lot of other solutions I guess, this one is the quickest that came to mind.