简体   繁体   中英

Swift - Adding UserDefaults to NotificationCenter

I implemented a NotificationCenter whenever you tap on a specific TableViewCell to perform that notification inside another ViewController , for this example the other ViewController background colour turns pink which works fine, but my question is how do I save the state of the pink colour being the same inside that ViewController using UserDefaults ?

To clarify this much better:

  • ViewController #2 contains the TableViewCell that performs the action when pressed

  • ViewController #1 is the view where the colour changes to Pink.

What I want to achieve?

Save the state of the pink colour in ViewController #1 using UserDefaults

ViewController #1 Code

- viewDidLoad

override func viewDidLoad()
{
    NotificationCenter.default.addObserver(self, selector: #selector(BrandTableViewController.testNotifcation(notification:)), name:NSNotification.Name(rawValue: "refresh"), object: nil);
}

- TestNotification Function

@objc func testNotifcation(notification: NSNotification) { 

    table.backgroundColor = UIColor.systemPink

    print("This is a message to say it is working")
}

ViewController #2 Code

didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if indexPath.row == 0
    {

        if traitCollection.userInterfaceStyle == .light
        {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil, userInfo: nil)
            self.dismiss(animated: true, completion: nil)
        }
        else if traitCollection.userInterfaceStyle == .dark
        {
            ...
        }
    }
}

You can set color in UserDefaults when you notification method called. So, updated your code as follow in ViewController1 :

@objc func testNotifcation(notification: NSNotification) { 

    table.backgroundColor = UIColor.systemPink

    let colorData = NSKeyedArchiver.archivedData(withRootObject: UIColor.systemPink)
    UserDefaults.standard.set(colorData, forKey: "savedColor")
    UserDefaults.standard.synchronize()

    print("This is a message to say it is working")
}

Then, In view did load, you need to add code to fetch saved color and set it as background. So update code in viewDidLoad in ViewController1 .

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(BrandTableViewController.testNotifcation(notification:)), name:NSNotification.Name(rawValue: "refresh"), object: nil);

    if let colorData = UserDefaults.standard.value(forKey: "savedColor") as? Data,
        let savedColor = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
    {
        table.backgroundColor = savedColor
    }
}

I hope this will help you.

If you want to save UIColor in UserDefaults , you can not directly achieve that as UserDefaults can not save the value of type UIColor BUT I have achieved same thing but with different manner

  • First You have to create an Array of Rob values of the UIColor you want to save , then you can save that array in UserDefaults and use it anywhere

For That Firstly you have to get rob values of your UIColor

extension UIColor {

func rgb() -> (red:Int, green:Int, blue:Int, alpha:Int)? {
    var fRed : CGFloat = 0
    var fGreen : CGFloat = 0
    var fBlue : CGFloat = 0
    var fAlpha: CGFloat = 0
    if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
        let iRed = Int(fRed * 255.0)
        let iGreen = Int(fGreen * 255.0)
        let iBlue = Int(fBlue * 255.0)
        let iAlpha = Int(fAlpha)

        let rgb = (iAlpha << 24) + (iRed << 16) + (iGreen << 8) + iBlue
        return (red:iRed, green:iGreen, blue:iBlue, alpha:iAlpha)
    } else {
        // Could not extract RGBA components:
        return nil
    }
}}
  • With above rob() function you can get rob value of any color as below

    let currcol = YourColor.rgb()! let arrayOfRGB = [currcol.red , currcol.green , currcol.blue] UserDefaults.standard.set(arrayOfRGB, forKey: "rgbofcolor")
  • That will save the array of rgb value of your desired color and then in any ViewController you can use it as below

     let preColor = UserDefaults.standard.array(forKey: "rgbofcolor") as? [Int] print("color RGB \\n\\(String(describing: preColor))\\n") if preColor == nil { print("Color is not saved in Userdefaults") } else { let YourDesiredColor = UIColor(red: CGFloat(Double(preColor![0])/255.0), green: CGFloat(Double(preColor![1])/255.0), blue: CGFloat(Double(preColor![2])/255.0), alpha: 1) print("Color was saved successfully in UserDedaults") }

Hope it helps.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM