How can we use Assets Catalog Color Sets?

后端 未结 9 1504
遇见更好的自我
遇见更好的自我 2020-11-29 06:57

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

相关标签:
9条回答
  • 2020-11-29 07:51

    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)
        }
    }
    
    0 讨论(0)
  • 2020-11-29 07:52

    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

      New Color Set menu

    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.

      enter image description here

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

    0 讨论(0)
  • 2020-11-29 07:52

    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)
    
    0 讨论(0)
提交回复
热议问题