I usually use custom UIColors on iOS using extensions with Swift, but now with iOS 11/ Xcode 9 we can create Colors Sets. How can we use them?
Update - Tip
You can use this way for simple accessing (swift 4 & swift 5)
enum AssetsColor: String {
case backgroundGray
case blue
case colorAccent
case colorPrimary
case darkBlue
case yellow
}
extension UIColor {
static func appColor(_ name: AssetsColor) -> UIColor? {
return UIColor(named: name.rawValue)
}
}
Add a colour set to an asset catalog, name it and set your colour in the attributes inspector, then call it in your code with UIColor(named: "MyColor")
.
In the asset catalog viewer, click the plus button at the bottom right of the main panel and choose New Color Set
Click on the white square, and select the Attributes Inspector (right-most icon in the right pane)
From there you can name and choose your colour.
To use it in your code, call it with UIColor(named: "MyColor")
. This returns an optional, so you'll need to unwrap it in most cases (this is probably one of the few cases where a force unwrap is acceptable, given you know the colour exists in your asset catalog).
You need to use UIColor(named: "appBlue").
And you can create a function in UIColor extension for simple access.
enum AssetsColor {
case yellow
case black
case blue
case gray
case green
case lightGray
case separatorColor
case red
}
extension UIColor {
static func appColor(_ name: AssetsColor) -> UIColor? {
switch name {
case .yellow:
return UIColor(named: "appYellow")
case .black:
return UIColor(named: "appBlack")
case .blue:
return UIColor(named: "appBlue")
case .gray:
return UIColor(named: "appGray")
case .lightGray:
return UIColor(named: "appLightGray")
case .red:
return UIColor(named: "appRed")
case .separatorColor:
return UIColor(named: "appSeparatorColor")
case .green:
return UIColor(named: "appGreen")
}
}
}
You can use it like this:
userNameTextField.textColor = UIColor.appColor(.gray)