I am trying to use hex color values in Swift, instead of the few standard ones that UIColor
allows you to use, but I have no idea how to do it.
Example: how would I use #ffffff
as a color?
iosswiftuicolor
I am trying to use hex color values in Swift, instead of the few standard ones that UIColor
allows you to use, but I have no idea how to do it.
Example: how would I use #ffffff
as a color?
Best Answer
#ffffff
are actually 3 color components in hexadecimal notation - redff
, greenff
and blueff
. You can write hexadecimal notation in Swift using0x
prefix, e.g0xFF
To simplify the conversion, let's create an initializer that takes integer (0 - 255) values:
Usage:
How to get alpha?
Depending on your use case, you can simply use the native
UIColor.withAlphaComponent
method, e.g.Or you can add an additional (optional) parameter to the above methods:
(we cannot name the parameter
alpha
because of a name collision with the existing initializer).Called as:
To get the alpha as an integer 0-255, we can
Called as
Or a combination of the previous methods. There is absolutely no need to use strings.