我正在做一个游戏,我想保存它当我通过关卡时,按钮的背景会改变颜色。使用UserDefaults是正确的吗?
例如,按钮“级别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
}默认情况下,背景按钮"level 1“是白色的,当该级别完成时,"level 1”按钮将背景更改为橙色。
我想知道如何保存橙色,这样当我关闭应用程序时,"level 1“按钮的背景仍然是橙色的。
我可以使用Userefaults吗?
我使用的是Xcode10.1.2,它与iOS 9.3兼容
发布于 2019-07-12 14:15:38
将十六进制值保存到用户默认值:
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)
)
}https://stackoverflow.com/questions/57000331
复制相似问题