Skip to content

Instantly share code, notes, and snippets.

@surakamy
Created July 16, 2019 19:33
Show Gist options
  • Save surakamy/c802884894c44deec8d635eb4acf7fb2 to your computer and use it in GitHub Desktop.
Save surakamy/c802884894c44deec8d635eb4acf7fb2 to your computer and use it in GitHub Desktop.
Dynamic colors for Dark and Light modes.
// Examples
UIColor.red.tweaked
UIColor.blue.lighter
extension UIColor {
/// Color gets darker in Light mode and lighter in Dark mode.
@objc var tweaked: UIColor {
if #available(iOS 13.0, *) {
switch UIApplication.userInterfaceStyle {
case .dark:
return self.lighter
case .light:
return self.darker
default:
return self
}
}
return self
}
}
// Helpers
extension UIApplication {
static var traitCollection: UITraitCollection? {
return UIApplication.shared.keyWindow?.traitCollection
}
@available(iOS 12.0, *)
static var userInterfaceStyle: UIUserInterfaceStyle {
return UIApplication.traitCollection?.userInterfaceStyle ?? .unspecified
}
}
extension UIColor {
@objc var lighter: UIColor {
return self.changedBrightness(by: 1.25)
}
@objc var darker: UIColor {
return self.changedBrightness(by: 0.75)
}
func changedBrightness(by amount: CGFloat) -> UIColor {
var h: CGFloat = 0; var s: CGFloat = 0
var b: CGFloat = 0; var a: CGFloat = 0
guard self.getHue(&h, saturation: &s, brightness: &b, alpha: &a) else { return self }
return UIColor(hue: h, saturation: s, brightness: b * amount, alpha: a)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment