In android there is an XML file as res/values/colors.xml
that lets you organize all of your colors used in your app. Like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#e60012</color>
<color name="blue">#33b5e5</color>
...
</resources>
Is there something like this in iOS? If not, what is the best way to organize colors that are used throughout the app?
I would like to ultimately be able to replace things like [UIColor greenColor]
with [MyColor greenColor]
.
As of Xcode 9 you can define colors in Asset Catalogs:
Create or use an existing Asset Catalog and click on the plus button on the bottom left of the editor and select "New Color Set":
You will see a new color called, "Color."
Click on it, then click to show the attributes inspector:
Here you can define your color and a lot of other options.
Double click on the name to change the name of the color.
Design tools like Sketch and Zeplin will allow you to export colors from your design strait into color assets for Xcode:
https://blog.zeplin.io/asset-catalog-colors-on-xcode-9-c4fdccc0381a
Better later than never...
For Swift:
Create a new class: MyColors.swift that is an extension of UIColor class:
Having in another class (maybe Utils.swift) this func:
You can use it like this
(note the brackets after UIColor):I have not come across a default file like this. You could create your own custom .plist file which holds the values and you load that when the app starts. Another option is to create a Category for
UIColor
which has a bunch of class methods returning the colors you want.You could create something that looks like this:
UIColor+CustomColors.h
:UIColor+CustomColors.m
:Then where you set the background you could have something like this:
ViewController.m
: