一尘不染

如何使用UserDefaults保存UIColor?

swift

我正在尝试对代码进行编程,以便如果用户按下“夜间按钮”,则背景将变为黑色,并且如果用户关闭应用程序,则背景将保持黑色。(白天模式也是如此。)

请注意:我已经对按钮进行了编码,当他们按下按钮时,所有场景都会切换到该模式。

这是我的代码,需要保存背景色:(两个if语句都需要它)

if GlobalData.dayBool == true && GlobalData.night == false {
    backgroundColor = GlobalData.dayColor 
}

if GlobalData.nightBool == true && GlobalData.dayBool == false {
    backgroundColor = GlobalData.nightColor 
}

我的日夜颜色:

struct GlobalData {
    static var score = 0
    static var dayColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0)
    static var nightColor = UIColor(red:0.10, green:0.10, blue:0.10, alpha:1.0)  
    static var dayBool = true
    static var nightBool = true
}

阅读 327

收藏
2020-07-07

共1个答案

一尘不染

Swift 4.2或更高版本

请注意,这只会将RGBA
CGFloat值另存为属性列表中的“数据”。与NSKeyedUnarchiver(NSCoding)一起使用标准方法时,它将使用32个字节(原始数据),而不是所需的424个字节:

extension UserDefaults {
    func set(_ color: UIColor?, forKey defaultName: String) {
        var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
        guard let color = color, color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        else {
            removeObject(forKey: defaultName)
            return
        }
        let count = MemoryLayout<CGFloat>.size
        set(Data(bytes: &red,   count: count) +
            Data(bytes: &green, count: count) +
            Data(bytes: &blue,  count: count) +
            Data(bytes: &alpha, count: count), forKey: defaultName)
    }
    func color(forKey defaultName: String) -> UIColor? {
        guard let data = data(forKey: defaultName) else {
           return nil
        }
        let size = MemoryLayout<CGFloat>.size
        return UIColor(red:   data[size*0..<size*1].withUnsafeBytes{ $0.pointee },
                       green: data[size*1..<size*2].withUnsafeBytes{ $0.pointee },
                       blue:  data[size*2..<size*3].withUnsafeBytes{ $0.pointee },
                       alpha: data[size*3..<size*4].withUnsafeBytes{ $0.pointee })
    }
}

extension UserDefaults {
    var backgroundColor: UIColor? {
        get {
            return color(forKey: "backgroundColor")
        }
        set {
            set(newValue, forKey: "backgroundColor")
        }
    }
}

UserDefaults.standard.backgroundColor = .red
UserDefaults.standard.backgroundColor  // r 1.0 g 0.0 b 0.0 a 1.0
2020-07-07