How can we use Assets Catalog Colors Sets

左心房为你撑大大i 提交于 2019-11-27 09:00:26
user2421361
UIColor(named: "myColor") 

Source: WWDC 2017 Session 237 —— What's New in MapKit


Caveat: Your project's Deployment Target needs to be set to iOS 11.0.

(short answer to the question update: there is UIColor(named: "MyColor") in Xcode 9.0)

Answering the original question:

  1. you create your color set

  1. you find your color among your snippets and you drag-n-drop it

  1. it will translate to a color literal when looking at the source code:

    #colorLiteral(red: 0, green: 0.6378085017, blue: 0.8846047521, alpha: 1)

You notice how the values of red, green and blue are different? It's because I defined them using Color Space Display P3, but the colorLiteral is using Color Space sRGB.

Short Version

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").

Full Instructions

  1. In the asset catalog viewer, click the plus button at the bottom right of the main panel and choose New Color Set

  2. Click on the white square, and select the Attributes Inspector (right-most icon in the right pane)

  3. From there you can name and choose your colour.

  4. 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 seperatorColor
   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: "appRad")
    case .seperatorColor:
        return UIColor(named: "appSeperatorColor")
    case .green:
        return UIColor(named: "appGreen") 
    }
}

You can use it like this

userNameTextField.textColor = UIColor.appColor(.gray)
Ashish
 // iOS
 let color = UIColor(named: "SillyBlue")

 // macOS
 let color = NSColor(named: "SillyBlue")

You can use this way for simple accessing (swift 4)

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)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!