Last active
July 29, 2023 13:14
-
-
Save foxicode/8ff7362c782e0f1503d6c36f45467c58 to your computer and use it in GitHub Desktop.
String to UIColor conversion in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public extension String { | |
| var asUIColor: UIColor? { | |
| var cString = self.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() | |
| if cString.hasPrefix("#") { | |
| cString.remove(at: cString.startIndex) | |
| } | |
| let allowedCharacters = CharacterSet(charactersIn: "0123456789ABCDEF") | |
| if cString.rangeOfCharacter(from: allowedCharacters.inverted) != nil { | |
| return nil | |
| } | |
| switch cString.count { | |
| case 6: | |
| var rgbValue: UInt64 = 0 | |
| Scanner(string: cString).scanHexInt64(&rgbValue) | |
| return UIColor( | |
| red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, | |
| green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, | |
| blue: CGFloat(rgbValue & 0x0000FF) / 255.0, | |
| alpha: CGFloat(1.0) | |
| ) | |
| case 8: | |
| var argbValue: UInt64 = 0 | |
| Scanner(string: cString).scanHexInt64(&argbValue) | |
| return UIColor( | |
| red: CGFloat((argbValue & 0xFF0000) >> 16) / 255.0, | |
| green: CGFloat((argbValue & 0x00FF00) >> 8) / 255.0, | |
| blue: CGFloat(argbValue & 0x0000FF) / 255.0, | |
| alpha: CGFloat((argbValue & 0xFF000000) >> 24) / 255.0 | |
| ) | |
| default: | |
| return nil | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment