Search code examples
swiftuitableviewcellios-darkmode

Default tableview cells don't respond to dark mode


Using a custom cell I'm able to get dark mode/normal mode to work properly. But when using the default framework cell Apple has provided it remains white regardless of what mode I enable. I read here

ios13 Dark Mode change not recognized by tableview Cell?

about the same problem. The answer tells me to use this:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)

    if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
        removeAndReaddGradientIfNeeded()
    }
}

But I'm unsure how exactly I'm supposed to use this and how it relates to my cells. My code right now for my cells is this:

if #available(iOS 13, *) {
    cell.backgroundColor = UIColor.systemBackground
    cell.textLabel?.textColor = UIColor(named: "MainLabelColor")
    cell.detailTextLabel?.textColor = UIColor(named: "SubLabelColor")
}

I use system color and custom colors in assets with two modes, one for light and one for dark. Now, this works fine in custom cell, but not in default.

Could anyone show me how to use the delegate function with cells?


Solution

  • Did you try to change the contentView background color? because the content view sits on top of the cell.

    if #available(iOS 13, *) {
        cell.contentView.backgroundColor = UIColor.systemBackground
    //For named color you have to resolve it.
     cell.textLabel?.textColor = UIColor(named: "MainLabelColor")?.resolvedColor(with: self.traitCollection)
     cell.detailTextLabel?.textColor = UIColor(named: "SubLabelColor")?.resolvedColor(with: self.traitCollection)
    
     //MARK:- Even If your Viewcontroller disabled dark mode, tableView cell will be enabled.
        self.overrideUserInterfaceStyle = .unspecified
    }
    

    To Support Dark Mode make sure you removed following overrides:-

    UserInterfaceStyle default value is unspecified . So, You might have enabled userInterfaceStyle to light in somewhere in your code or list file.

    In Plist file check for following key-value and remove them:-

    <key>UIUserInterfaceStyle</key>
        <string>light</string>
    

    In Code check for the following the line and remove them.

    i) If the key window is overridden to light mode, your entire app will be forced to light mode.

      UIApplication.shared.keyWindow?.overrideUserInterfaceStyle = .light
    

    ii) If View Controller is overridden to light mode, your entire ViewController will be forced to light mode.

     self.overrideUserInterfaceStyle = .light