重新考虑这个声明:
我也试过做一个@IBInspectable,但你不能有枚举(所以你可以将一个枚举映射到一种颜色)。
您可以通过这种方式使用Int 桥接@IBInspectable enum:
enum ColorPalette:Int {
case clear = 0
case teal = 1
case plum = 2
case foam = 3
}
var tincture:ColorPalette = .clear
在代码中,访问self.tincture,也就是您要的enum。
在Interface Builder中,使用tinctureAdapter,它是一个Int,因此实际上是一个枚举类型的@IBInspectable。
// Stored IB property
@available(*, unavailable, message="Use tincture programmatically")
@IBInspectable var tinctureAdapter:Int {
get {
return self.tincture.rawValue
}
set {
self.tincture = ColorPalette:Int(rawValue: newValue) ?? .clear
}
}
将此代码放在UIColor 类扩展中可能很有用。使用桥接方法,您还可以在 IB 中使用 @Donamite plain-English 字符串。
Swift 3 示例
@IBDesignable class ColorSwatchView: UIView {
enum ColorPalette: String {
case Thistle = "thistle"
case Plum = "plum"
case Olive = "olive"
case Iris = "iris"
case Clear = "clear"
}
let namedColors = [
"thistle": UIColor(red: 216/255, green: 191/255, blue: 216/255, alpha: 1),
"plum" : UIColor(red: 221/255, green: 160/255, blue: 221/255, alpha: 1),
"olive" : UIColor(red: 128/255, green: 128/255, blue: 0/255, alpha: 1),
"iris" : UIColor(red: 3/255, green: 180/255, blue: 200/255, alpha: 1)
]
var tincture:ColorPalette = .Clear
// Stored IB property
@available(*, unavailable, message: "Use tincture programmatically")
@IBInspectable var tinctureName: String? {
willSet {
if let color = ColorPalette(rawValue: newValue?.lowercased() ?? "") {
tincture = color
}
}
}
}
界面构建器
让您的自定义视图成为ColorSwatchView的子视图。
以编程方式
override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
ctx?.saveGState()
let uiColor = namedColors[tincture.rawValue] ?? UIColor.clear
ctx?.setFillColor(uiColor.cgColor)
ctx?.fill(bounds)
ctx?.restoreGState()
}
► 在GitHub 上查找此解决方案,在Swift Recipes 上查找更多详细信息。