Created
July 16, 2019 19:33
-
-
Save surakamy/c802884894c44deec8d635eb4acf7fb2 to your computer and use it in GitHub Desktop.
Dynamic colors for Dark and Light modes.
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
// 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