我想在 IB 中创建一个自定义调色板,您可以在其中设置颜色,并且如果该调色板中的颜色发生变化,它会通过 View 传播。我见过这种方法http://natashatherobot.com/xcode-color-palette/ ,但是如果将来调色板的颜色发生变化,您必须转到项目的每个 View 并更改该颜色。我也尝试做一个 @IBInspectable 但你不能有枚举(所以你可以将枚举映射到颜色)。我知道我可以通过代码定义颜色,然后有一个导出,但问题是我有大量的 View ,我需要子类化只是为了更改这样的颜色:
class TestCommonView: CommonView {
@IBOutlet weak var borderView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
borderView.backgroundColor = Colors.fabrica.pastel
}
}
有什么想法吗?
最佳答案
重新考虑此声明:
I tried also doing an @IBInspectable but you can't have enums (so you can map an enum to a color).
您可以通过以下方式使用 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
类扩展中可能会很有用。使用桥接方法,您还可以使用@Donamite plain-English IB 中的字符串。
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
}
}
}
}
界面生成器
使您的自定义 View 成为 ColorSwatchView
的 subview 。
以编程方式
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 的更多详细信息.
关于ios - 将自定义调色板添加到 IB,该调色板会在颜色更改 iOS 时传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31702193/