I have a collection view which shows time slots in the app. In the dark mode, it seems the UILabel is not showing the black text color on white background.
In the storyboard, I have set the color as Black (also tried the Default color) for the label.
In the code, when user select the cell,
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? TimeCell{
cell.timeLabel.toggleTheme(true)
}
}
and I have the UILabel extension:
extension UILabel{
func toggleTheme(_ selected : Bool){
if selected{
if #available(iOS 13.0, *) {
if self.traitCollection.userInterfaceStyle == .dark{
self.textColor = UIColor.black
self.backgroundColor = UIColor.white
}else{
self.textColor = UIColor.white
self.backgroundColor = UIColor.black
}
} else {
self.textColor = UIColor.white
self.backgroundColor = UIColor.black
}
}else{
if #available(iOS 13.0, *) {
if self.traitCollection.userInterfaceStyle == .dark{
self.textColor = UIColor.white
self.backgroundColor = UIColor.black
}else{
self.textColor = UIColor.black
self.backgroundColor = UIColor.white
}
} else {
self.textColor = UIColor.black
self.backgroundColor = UIColor.white
}
}
}
}
and the result is:
There are 2 solutions to ensure the UILabel
color is displayed in .dark
mode:
Set the Table color to UIColor.labelColor
. This will adopt automatically based on device theme dark or light
The other option is to define color in xcassets and provide color variants for different themes. You need to select Appearance as Any, Dark to get option to provide multiple colours. Refer below image. With defined you do NOT need to check for theme as you are doing in below snippet:
if #available(iOS 13.0, *) {
if self.traitCollection.userInterfaceStyle == .dark {
self.textColor = UIColor.black
self.backgroundColor = UIColor.white
} else {
self.textColor = UIColor.white
self.backgroundColor = UIColor.black
}
} else {
self.textColor = UIColor.white
self.backgroundColor = UIColor.black
}
Alternatively you can simply set self.textColor = UIColor(named: "MyBlackColor")
Hope this will help.
Somehow the label in collection view is not working as expected. I tried different configurations and none worked. I ended up using button instead and it worked in my case. I will update my answer once I get this working with a label.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With