0

I want you to be the selected background color in the App.

I made that... the background color is changed but it's not saved.

 @IBAction func ButtonColor(_ sender: UIButton) {


    let colorTag = sender.tag

        if  (colorTag == 1){
        self.view.backgroundColor = #colorLiteral(red: 0.8156862745, green: 0.9725490196, blue: 0.9215686275, alpha: 1)
        print ("colorTag 1")

    }else if (colorTag == 2){
        self.view.backgroundColor = #colorLiteral(red: 0.8156862745, green: 0.8, blue: 0.9215686275, alpha: 1)
        print ("colorTag 2")
    }else if (colorTag == 3){
        self.view.backgroundColor = #colorLiteral(red: 0.3254901961, green: 0.9019607843, blue: 0.9803921569, alpha: 1)
        print ("colorTag 3")
    }else if (colorTag == 4){
        self.view.backgroundColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)
        print ("colorTag 4")
        } else if (colorTag == 0){
        self.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
    }

}

Now I don't know any more. What I have to do with this is to make the selected color saved.

jscs
  • 63,694
  • 13
  • 151
  • 195
Daniel.P
  • 75
  • 1
  • 8

1 Answers1

1

First create any array of the colors

let arr = [#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0),
           #colorLiteral(red: 0.8156862745, green: 0.9725490196, blue: 0.9215686275, alpha: 1),
           #colorLiteral(red: 0.8156862745, green: 0.8, blue: 0.9215686275, alpha: 1),
           #colorLiteral(red: 0.3254901961, green: 0.9019607843, blue: 0.9803921569 alpha: 1),
           #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)]

@IBAction func ButtonColor(_ sender: UIButton) { 
    self.view.backgroundColor = arr[sender.tag]
    UserDefaults.standard.set(arr[sender.tag], forKey: "SavedColor")
}

When you open the app again inside viewDidLoad

self.view.backgroundColor = UserDefaults.standard.color(forKey: "SavedColor") ?? UIColor.red

with this https://stackoverflow.com/a/30576832/5820010

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87