Created
June 15, 2023 14:31
-
-
Save acosmicflamingo/8315479521743070dd1c9cd7cb94b5d7 to your computer and use it in GitHub Desktop.
UIColor Convenience Initializer for Supporting High-Contrast
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
import UIKit | |
extension UIColor { | |
/// Instantiate UIColor with support for high contrast mode | |
/// - Parameters: | |
/// - light: color to use when userInterfaceStyle is light and normal contrast | |
/// - dark: color to use when userInterfaceStyle is dark and normal contrast | |
/// - lightHC: color to use when userInterfaceStyle is light and high contrast | |
/// - darkHC: color to use when userInterfaceStyle is dark and high contrast | |
public convenience init( | |
light: UIColor, | |
dark: UIColor, | |
lightHC lightHighContrast: UIColor? = nil, | |
darkHC darkHighContrast: UIColor? = nil | |
) { | |
self.init { trait -> UIColor in | |
let lightHC = lightHighContrast ?? light | |
let darkHC = darkHighContrast ?? dark | |
switch (trait.accessibilityContrast, trait.userInterfaceStyle) { | |
case (.high, .dark): | |
return darkHC.resolvedColor(with: trait) | |
case (.high, _): | |
return lightHC.resolvedColor(with: trait) | |
case (_, .dark): | |
return dark.resolvedColor(with: trait) | |
default: | |
return light.resolvedColor(with: trait) | |
} | |
} | |
} | |
/// Instantiate UIColor with support for high contrast mode | |
/// - Parameters: | |
/// - any: color to use in normal contrast | |
/// - anyHC: color to use in high contrast | |
/// - interfaceStyle: interface style to use for color | |
public convenience init( | |
any: UIColor, | |
anyHC anyHighContrast: UIColor | |
) { | |
self.init(light: any, dark: any, lightHC: anyHighContrast, darkHC: anyHighContrast) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment