Swift 5.0 cannot use the #ffffff
syntax directly. Here is the code I use for web-related projects. Supports alpha and three-digits.
Usage example (uppercase values are fine too):
let hex = "#FADE2B" // yellow
let color = UIColor(fromHex: hex)
Supported string formats:
"fff" // RGB
"#fff" // #RGB
"ffff" // RGBA
"#ffff" // #RGBA
"ffffff" // RRGGBB
"#ffffff" // #RRGGBB
"ffffffff" // RRGGBBAA
"#ffffffff" // #RRGGBBAA
The digits represent Red, Green, Blue and Alpha (like transparency).
IMPORTANT
This is written for iOS (UIKit). For MacOS (AppKit), replace UIColor
with NSColor
.
Alternatives:
You can remove the #
and store it as a 32-bit unsigned integer literal, denoted by a 0x
prefix thus: 0xffffff. You still need code to convert this to a colour though.
If you're wanting a non-programatic way to get the color: Open a colour selector dialog and switch to Colour Sliders > RGB Sliders and paste/enter the value into the 'Hex Color #' box. (Don't paste the # hash symbol.)
Caveat:
Hex colours originating from Android are usually in format AARRGGBB and will thus require reformatting. e.g. let newColor = color.suffix(6).prefix(4) + color.prefix(2)
Source:
https://gist.github.com/akingdom/75778998e0d435060d645c0be35f9c24
See https://stackoverflow.com/a/63443672/1419960 for details.