繁体   English   中英

Swift - 将 UserDefaults 添加到 NotificationCenter

[英]Swift - Adding UserDefaults to NotificationCenter

每当您点击特定的TableViewCell以在另一个ViewController内执行该通知时,我都实现了一个NotificationCenter ,对于这个示例,另一个ViewController背景颜色变为粉红色,这可以正常工作,但我的问题是如何保存粉红色的状态相同在那个ViewController 中使用UserDefaults

为了更好地澄清这一点:

  • ViewController #2包含按下时执行操作的 TableViewCell

  • ViewController #1是颜色变为粉红色的视图。

我想达到什么目标?

使用UserDefaultsViewController #1 中保存粉红色的状态

视图控制器 #1 代码

- viewDidLoad

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

- 测试通知功能

@objc func testNotifcation(notification: NSNotification) { 

    table.backgroundColor = UIColor.systemPink

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

视图控制器 #2 代码

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
        {
            ...
        }
    }
}

您可以在UserDefaults通知方法时在UserDefaults设置颜色。 因此,在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")
}

然后,在视图中加载,您需要添加代码来获取保存的颜色并将其设置为背景。 所以更新ViewController1viewDidLoad中的代码。

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
    }
}

我希望这能帮到您。

如果你想在UserDefaults保存UIColor ,你不能直接实现,因为UserDefaults不能保存UIColor类型的值但是我已经实现了同样的事情,但方式不同

  • 首先,您必须创建要保存的UIColor的 Rob 值Array ,然后您可以将该数组保存在UserDefaults并在任何地方使用它

为此首先,您必须获得UIColor rob 值

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
    }
}}
  • 使用上面的rob()函数,您可以获得任何color rob 值,如下所示

    let currcol = YourColor.rgb()! let arrayOfRGB = [currcol.red , currcol.green , currcol.blue] UserDefaults.standard.set(arrayOfRGB, forKey: "rgbofcolor")
  • 这将保存所需颜色的 rgb 值array ,然后在任何ViewController您可以使用它,如下所示

     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") }

希望能帮助到你.....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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