Skip to content

Instantly share code, notes, and snippets.

@octover
Created July 17, 2019 10:10
Show Gist options
  • Save octover/5889b2cb12b97f311ae8452891b30608 to your computer and use it in GitHub Desktop.
Save octover/5889b2cb12b97f311ae8452891b30608 to your computer and use it in GitHub Desktop.
UIColor to SwiftUI.Color extension
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)
@octover
Copy link
Author

octover commented Jul 17, 2019

Came up with this with the help of a coworker.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment