Have you ever noticed colors not matching up the way you expect? This is especially apparent when setting some colors in the storyboard and other colors in code.
Here I’m setting the top half and the bottom half of this view to the exact same RGB value. So what’s going on?
Changes in iOS 10
An easily missed change in iOS 10 is the way UIColor works. From the Apple docs:
The color information represented by this object is in an RGB colorspace. On applications linked for iOS 10 or later, the color is specified in an extended range sRGB color space. On earlier versions of iOS, the color is specified in a device RGB colorspace.
When creating a color in code it is using the “sRGB” color space, however the storyboard defaults to the “Generic RGB” color space. You can see the color profile (and change it) by clicking the gear icon in the color picker window.
Once you switch the Color Profile to “sRGB IEC61966-2.1” you can see that the RGB values change. The color you see stays the same, so the RGB values update to how that color you see is represented in the sRGB color space. This is why the color doesn’t match the color set in code. You thought you were setting it to (84, 124, 224), but it was being set to the equivalent of (102, 146, 230).
After switching to “sRGB IEC61966-2.1”, the RGB values can be updated to what you would normally use in code and it will match.
Set colors in code
The easiest solution — make it a practice to always set your colors in code and you won’t ever have to worry about this quirk. I wouldn’t want to have to remember to change the color space every time I add a new UI component. Setting colors in code has the added benefit of being able to define a template of colors to be used throughout the app, so if you change your actionColor it will change on all views. It also makes it easier to provide users with different themes.
Color Assets
If for some reason you are dead set on setting colors in the storyboard, you can make things easier with Color Assets. You can add colors to your asset catalog that can be given a name and then used in both storyboards and code.
The color space only needs to be set to sRGB once for each color you add, then you can safely use that color in all your views without worrying about it using the wrong color space.
Further reading
While trying to research more information to better explain the cause of this issue I came across this post by Pablo Villar, Working efficiently with colors in Xcode, that goes into extreme detail. It is a great read for anyone interested in learning more about this issue.