Daniel.P
Daniel.P

Reputation: 75

Swift 4 save from the background color that was consulted in the App

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.

Upvotes: 0

Views: 112

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

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

Upvotes: 1

Related Questions