我正在制作一个游戏,我想在通过关卡时保存它,按钮的背景会改变颜色。使用用户默认值是否正确?
例如,按钮"级别 1">背景是灰色的,当级别完成时,颜色变为橙色,但当我关闭应用程序时,按钮"级别 1"恢复为灰色。
关卡完成后,在这种情况下,如何保存按钮的颜色为橙色?
我尝试使用userDefaults,但是在定义它时它告诉我"UIColor无法转换为字符串">
@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兼容
十六进制值保存到用户默认值:
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)
)
}