Created
March 23, 2020 20:03
-
-
Save SpectralDragon/025700c7d80b8bb4c97c46eeb03db8d3 to your computer and use it in GitHub Desktop.
Get red/blue/green from SwiftUI Color
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
extension UIColor { | |
// default implementaion of hex parsing | |
public convenience init?(hex: String) { | |
let r, g, b, a: CGFloat | |
if hex.hasPrefix("#") { | |
let start = hex.index(hex.startIndex, offsetBy: 1) | |
let hexColor = String(hex[start...]) | |
if hexColor.count == 8 { | |
let scanner = Scanner(string: hexColor) | |
var hexNumber: UInt64 = 0 | |
if scanner.scanHexInt64(&hexNumber) { | |
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 | |
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 | |
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 | |
a = CGFloat(hexNumber & 0x000000ff) / 255 | |
self.init(red: r, green: g, blue: b, alpha: a) | |
return | |
} | |
} | |
} | |
return nil | |
} | |
} | |
extension Color { | |
var uiColor: UIColor? { | |
switch self { | |
case .black: return .black | |
case .white: return .white | |
case .clear: return .clear | |
case .blue: return .blue | |
case .yellow: return .yellow | |
case .gray: return .gray | |
case .green: return .green | |
case .pink: return .systemPink | |
case .secondary: return .secondarySystemFill | |
case .orange: return .orange | |
case .purple: return .purple | |
case .red: return .red | |
default: | |
// Description returns hex representation of color if color is custom | |
return UIColor(hex: self.description) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment