Created
July 17, 2019 10:10
-
-
Save octover/5889b2cb12b97f311ae8452891b30608 to your computer and use it in GitHub Desktop.
UIColor to SwiftUI.Color extension
This file contains 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 { | |
func color(with colorScheme: ColorScheme) -> Color { | |
var red: CGFloat = 0 | |
var blue: CGFloat = 0 | |
var green: CGFloat = 0 | |
var alpha: CGFloat = 0 | |
let trait: UITraitCollection = { | |
switch colorScheme { | |
case .light: | |
return UITraitCollection(userInterfaceStyle: .light) | |
case .dark: | |
return UITraitCollection(userInterfaceStyle: .dark) | |
@unknown default: | |
return UITraitCollection(userInterfaceStyle: .light) | |
} | |
}() | |
resolvedColor(with: trait).getRed(&red, green: &green, blue: &blue, alpha: &alpha) | |
return Color(red: Double(red), green: Double(green), blue: Double(blue)).opacity(Double(alpha)) | |
} | |
} | |
// To use add this to your View struct | |
@Environment(\.colorScheme) var colorScheme: ColorScheme | |
// then this is usable and responds to changing the color scheme from light to dark | |
UIColor.tertiarySystemBackground.color(with: colorScheme) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Came up with this with the help of a coworker.