Skip to content

Instantly share code, notes, and snippets.

@cemolcay
Created June 17, 2024 11:42
Show Gist options
  • Save cemolcay/a8b24b3e71638bb34abfc11a940da2ec to your computer and use it in GitHub Desktop.
Save cemolcay/a8b24b3e71638bb34abfc11a940da2ec to your computer and use it in GitHub Desktop.
Change text color based on the background
class TitleColorLabel: UILabel {
var lightTitleColor: UIColor = .white { didSet { updateTitleColor() }}
var darkTitleColor: UIColor = .black { didSet { updateTitleColor() }}
override var backgroundColor: UIColor? {
didSet {
updateTitleColor()
}
}
func updateTitleColor() {
textColor = backgroundColor?.isLight() == true ? lightTitleColor : darkTitleColor
}
}
extension UIColor {
var isLight: Bool {
var white: CGFloat = 0
getWhite(&white, alpha: nil)
return white > 0.5
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment