我知道如何使用此答案以编程方式执行此操作: Saving UIColor to and loading from NSUserDefaults
但是当我希望能够预先加载我在编辑器中创建的plist
(创建plist
文件并填充其字段 - 而不是通过编码)时,我有什么选择? Xcode
只会为您提供一些下拉菜单选项,例如string
dictionary
array
或number
。
有没有办法在编辑器中执行此操作? 我可以为r / g / b创建3个字段,然后用数字设置,但它看起来像是一个糟糕的设计
答案 0 :(得分:1)
如果你真的需要从你的代码中抽象出这些信息并且你不能使用一些静态常量,你可以尝试使用NSColor扩展来解析字符串值并将其存储在plist上。
这样的事情对我有用:
import AppKit
extension NSColor {
convenience init(hex:String) {
var cString:String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString = cString.substring(from: cString.characters.index(cString.startIndex, offsetBy: 1))
}
if ((cString.characters.count) != 6) {
self.init (red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)
} else {
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
self.init(red:CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0))
}
}
}
答案 1 :(得分:1)
步骤
读取.plist值
var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("colors", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}
if let dict = myDict {
// Use your dict here
}
获得十六进制颜色后,您可以将其转换为UIColor:Hex-to-UIColor
答案 2 :(得分:0)
不要将颜色存储在plist中,而应考虑将它们放在结构中:'UIColor + Styling.swift'
public extension UIColor {
struct AppName {
static let white = UIColor(hex: "#FFFFFF")
static let black = UIColor(hex: "#3D2C2A")
static let red = UIColor(hex: "#D84C3A")
static let darkRed = UIColor(hex: "#B84132")
static let green = UIColor(hex: "#6C9491")
}
}
然后你就可以像这样使用它们了:
backgroundColor = UIColor.AppName.green
要使用十六进制代码启动UIColor对象,请实现此扩展名:'UIColor + Hex.swift'
public extension UIColor {
/// You can pass a hex with or without # and with or without alpha
convenience init(hex: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
let cleanHex = hex.replacingOccurrences(of: "#", with: "")
let scanner = Scanner(string: cleanHex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
if cleanHex.characters.count == 6 {
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if cleanHex.characters.count == 8 {
alpha = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
red = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x000000FF) / 255.0
} else {
print("invalid rgb string, length should be 6 or 8", terminator: "")
}
} else {
print("scan hex error")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}