Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Created February 21, 2026 05:11
Show Gist options
  • Select an option

  • Save StewartLynch/e60e24bc6b98ebb6f2d84cf6ebce7bbe to your computer and use it in GitHub Desktop.

Select an option

Save StewartLynch/e60e24bc6b98ebb6f2d84cf6ebce7bbe to your computer and use it in GitHub Desktop.
UIColor Extension for GiftRegistry App.
//
//----------------------------------------------
// Original project: GiftRegistry
//
// Follow me on Mastodon: https://iosdev.space/@StewartLynch
// Follow me on Threads: https://www.threads.net/@stewartlynch
// Follow me on Bluesky: https://bsky.app/profile/stewartlynch.bsky.social
// Follow me on X: https://x.com/StewartLynch
// Follow me on LinkedIn: https://linkedin.com/in/StewartLynch
// Email: slynch@createchsol.com
// Subscribe on YouTube: https://youTube.com/@StewartLynch
// Buy me a ko-fi: https://ko-fi.com/StewartLynch
//----------------------------------------------
// Copyright © 2026 CreaTECH Solutions (Stewart Lynch). All rights reserved.
import UIKit
extension UIColor {
// Initializes a new UIColor instance from a hex string
convenience init?(hex: String) {
var hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if hexString.hasPrefix("#") {
hexString.removeFirst()
}
let scanner = Scanner(string: hexString)
var rgbValue: UInt64 = 0
guard scanner.scanHexInt64(&rgbValue) else {
return nil
}
var red, green, blue, alpha: UInt64
switch hexString.count {
case 6:
red = (rgbValue >> 16)
green = (rgbValue >> 8 & 0xFF)
blue = (rgbValue & 0xFF)
alpha = 255
case 8:
red = (rgbValue >> 16)
green = (rgbValue >> 8 & 0xFF)
blue = (rgbValue & 0xFF)
alpha = rgbValue >> 24
default:
return nil
}
self.init(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: CGFloat(alpha) / 255)
}
// Returns a hex string representation of the UIColor instance
func toHexString(includeAlpha: Bool = false) -> String? {
// Get the red, green, and blue components of the UIColor as floats between 0 and 1
guard let components = self.cgColor.components else {
// If the UIColor's color space doesn't support RGB components, return nil
return nil
}
// Convert the red, green, and blue components to integers between 0 and 255
let red = Int(components[0] * 255.0)
let green = Int(components[1] * 255.0)
let blue = Int(components[2] * 255.0)
// Create a hex string with the RGB values and, optionally, the alpha value
let hexString: String
if includeAlpha, let alpha = components.last {
let alphaValue = Int(alpha * 255.0)
hexString = String(format: "#%02X%02X%02X%02X", red, green, blue, alphaValue)
} else {
hexString = String(format: "#%02X%02X%02X", red, green, blue)
}
// Return the hex string
return hexString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment