UIColor initialization using HEX value and Alpha value.
- Authors: Kobe
Introduction
In this proposal, we introduce an initializer for UIColor that includes Hex values and alpha values, allowing for easy conversion of a given HEX string value into a UIColor.
Motivation
- When creating an app, picking a specific color with a color picker often results in a HEX value. It was always a hassle to convert these HEX values back into RGB values.
- When UI/UX designers provide specific colors in HEX values, it's cumbersome to convert each HEX value into RGB values and store them in an enum or create separate Assets ColorSets.
- Managing colors becomes difficult when there are too many ColorSets in Assets.
- I also tried extending UIColor separately, but it was inconvenient to have to extend it every time I made an app and to use the same repetitive code.
- I even distributed and used my own library called UIKobeKit, but I felt it was unnecessary to use a library for this purpose and thought it would be really convenient if it was included in UIColor from the beginning.
- Using a library also meant the hassle of importing it wherever needed.
Detailed design
I implemented an extension of UIColor as follows:
import UIKit
extension UIColor {
public convenience init(hexCode: String, alpha: CGFloat) {
var hexFormatted: String = hexCode.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if hexFormatted.hasPrefix(“#”) {
hexFormatted = String(hexFormatted.dropFirst())
}
assert(hexFormatted.count == 6, ColorError.invalidHEXCode.localizedDescription)
var rgbColorValue: UInt64 = 0
Scanner(string: hexFormatted).scanHexInt64(&rgbColorValue)
self.init(
red: CGFloat((rgbColorValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbColorValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbColorValue & 0x0000FF) / 255.0,
alpha: alpha
)
}
}
enum ColorError: LocalizedError {
case invalidHEXCode
var errorDescription: String? {
switch self {
case .invalidHEXCode:
return "Use of invalid HEX CODE value."
}
}
}
Source compatibility
As the code design utilizes a "convenience init," there is no risk of damaging the source.
It is implemented in a way that developers can use it if they wish, ensuring compatibility.
Effect on ABI stability
This proposal has no impact on ABI stability.