Created
June 17, 2024 11:42
-
-
Save cemolcay/a8b24b3e71638bb34abfc11a940da2ec to your computer and use it in GitHub Desktop.
Change text color based on the background
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
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