如何在iOS 9.3的Xcode 10.2.1中存储颜色标签

时间:2019-07-12 04:46:28

标签: swift xcode userdefaults

我正在做一个游戏,我想保存一点,当我通过关卡时,按钮的背景会更改颜色。使用UserDefaults是否正确?

例如,“级别1”按钮的背景为灰色,当级别完成时颜色变为橙色,但是当我关闭应用程序时,“级别1”按钮返回其灰色。

完成关卡后,如何在这种情况下将按钮的颜色保存为橙色?

我尝试使用userDefaults,但是在定义它时告诉我“ UIColor无法转换为String”

@IBAction func continuarAccion(_ sender: Any) {  


    animateOut(desireView: vistaNivel1).  //Remove the view, in this case I have a blur, is where the level is shown

    botonNivel1.backgroundColor = UIColor.white

}

默认情况下,背景按钮“级别1”为白色 级别完成后,“级别1按钮”会将背景更改为橙色。

我想知道如何保存橙色,以便在我关闭应用程序时,“级别1”按钮的背景保持橙色。

使用Userefaults对我来说正确吗?

我正在使用xcode 10.1.2,与iOS 9.3兼容

1 个答案:

答案 0 :(得分:0)

将十六进制值保存为用户默认值:

 UserDefaults.standard.set( hexValue as? String, forKey: "color")

//获得价值

    let strColor = UserDefaults.standard.object(forKey: "color") as? String

//要将十六进制值转换为UIColor:

   func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
        return UIColor.gray
    }

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}