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?
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?
Supporting 7 Hex color types
There are 7 hex color formats: ""#FF0000","0xFF0000", "FF0000", "F00", "red", 0x00FF00 , 16711935
CAUTION: This isn't a "one-file-solution", there are some dependencies, but hunting them down may be faster than researching this from scratch.
https://github.com/eonist/swift-utils/blob/2882002682c4d2a3dc7cb3045c45f66ed59d566d/geom/color/NSColorParser.swift
Permalink:
https://github.com/eonist/Element/wiki/Progress#supporting-7-hex-color-types
The Swift 4 version looks like this:
Hex with validation
Deatails
Xcode 10.0, Swift 4.2
Solution
Usage
Swift 4 UIColor extension:
Usage:
Swift 2.x version:
RGBA Version Swift 3/4
I like @Luca's answer as i think it's the most elegant.
However I don't want my colours specified in ARGB. I'd rather RGBA + also i needed to hack in the case of dealing with strings that specify 1 character for each of the channels "#FFFA".
This version also adds error throwing + strips the '#' character if it's included in the string. Here is my modified form for Swift.
#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.