Skip to content

Instantly share code, notes, and snippets.

@foxicode
Last active July 29, 2023 13:14
Show Gist options
  • Select an option

  • Save foxicode/8ff7362c782e0f1503d6c36f45467c58 to your computer and use it in GitHub Desktop.

Select an option

Save foxicode/8ff7362c782e0f1503d6c36f45467c58 to your computer and use it in GitHub Desktop.
String to UIColor conversion in Swift
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