[英]Add a custom palette to IB that propagates if a color changes iOS
我想在 IB 中創建一個自定義調色板,您可以在其中設置顏色,如果該調色板中的顏色發生變化,它會通過視圖傳播。 我已經在http://natashatherobot.com/xcode-color-palette/看到了這種方法,但是如果將來調色板的顏色發生變化,您必須轉到項目的每個視圖並更改該顏色。 我也試過做一個 @IBInspectable 但你不能有枚舉(所以你可以將枚舉映射到顏色)。 我知道我可以通過代碼定義顏色,然后有一個出口,但問題是我有大量的視圖,我需要子類化只是為了改變這樣的顏色:
class TestCommonView: CommonView {
@IBOutlet weak var borderView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
borderView.backgroundColor = Colors.fabrica.pastel
}
}
有任何想法嗎?
重新考慮這個聲明:
我也試過做一個 @IBInspectable 但你不能有枚舉(所以你可以將枚舉映射到顏色)。
您可以通過以下方式使用Int
橋接@IBInspectable
enum
:
enum ColorPalette:Int {
case clear = 0
case teal = 1
case plum = 2
case foam = 3
}
var tincture:ColorPalette = .clear
在code 中,訪問self.tincture
,這是您所追求的enum
。 在界面生成器,使用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純英文字符串。
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 的其他詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.