How can we use Assets Catalog Color Sets?

后端 未结 9 1528
遇见更好的自我
遇见更好的自我 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: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).

提交回复
热议问题