swiftuiappearance

UIAppearance of UILabel whithin UICollectionViewCell - selected/unselected


I am currently working with UIAppearance for the colors of all my outlets on my project, which allowed me to create my own "DIY" version of a nightmode on my iOS app.

sample :

UILabel.appearance().textColor = colorScheme.primaryColor 
UILabel.appearance(whenContainedInInstancesOf: [MyController.self]).textColor = colorScheme.secondaryColor 
... 

Note: Colorscheme is just a struct with all my colors, that switch depending on the state .lightMode / .darkMode

I recently build a subclass of UICollectionViewCell with a UILabel inside, and I wanted to use the same method to define the colors within it. However I am troubling to figure out how to set a different color for the nested UILabel depending on the selected state of the Cell.

For instance :

// create a default UIView with specific backgroundColor 
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = colorScheme.selectedBackgroundColor

MyCollectionViewCell.appearance().backgroundColor = colorScheme.backgroundColor // default 
MyCollectionViewCell.appearance().selectedBackgroundView = selectedBackgroundView // set specific view used when cell is selected

This code above works fine when I want to set different background colors when MyCollectionViewCell is selected or not, however I want the nested UILabel to change its fontColor as well, depending if the cell is selected or not. Is there a propper way to achieve this with UIAppearance?


Solution

  • Finally found a Workaround for this issue. I post my solution it may help someone.

    first I define the color for both textColor and highlightedTextColor

    UILabel.appearance(whenContainedInInstancesOf: [MyCollectionViewCell.self]).textColor = colorScheme.color1
    UILabel.appearance(whenContainedInInstancesOf: [MyCollectionViewCell.self]).highlightedTextColor = colorScheme.color2
    

    Then in MyCollectionViewCell I "bind" the isSelected to UILabel isHighlighted :

    class MyCollectionViewCell: UICollectionViewCell {
    
        @IBOutlet weak var myLabel: UILabel!
    
        override var isSelected: Bool {
            didSet {
                self.myLabel.isHighlighted = isSelected
            }
        }
    }
    

    Works flawlessly.

    Hope this can help someone