Search code examples
swiftios13xcode11ios-darkmode

iOS UILabel textColor not updating in dark mode


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:

enter image description here enter image description here


Solution

  • 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.