Skip to content

Instantly share code, notes, and snippets.

@geoffalday
Created April 9, 2025 01:20
Show Gist options
  • Save geoffalday/8b0f930fce5412cf1325c7a5b73929c1 to your computer and use it in GitHub Desktop.
Save geoffalday/8b0f930fce5412cf1325c7a5b73929c1 to your computer and use it in GitHub Desktop.
Handy Swift Stuff
/*
Extension to convert hex color to color that can be used with SwiftUI
Usage example:
let myColor = "#F8CC45"
RoundedRectangle(cornerRadius: 10)
.fill(Color(hex: myColor))
*/
extension Color {
init(hex: String) {
var cleanHexCode = hex.trimmingCharacters(in: .whitespacesAndNewlines)
cleanHexCode = cleanHexCode.replacingOccurrences(of: "#", with: "")
print(cleanHexCode)
var rgb: UInt64 = 0
Scanner(string: cleanHexCode).scanHexInt64(&rgb)
let redValue = Double((rgb >> 16) & 0xFF) / 255.0
let greenValue = Double((rgb >> 8) & 0xFF) / 255.0
let blueValue = Double(rgb & 0xFF) / 255.0
self.init(red: redValue, green: greenValue, blue: blueValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment