skip to Main Content

Its possible to apply a custom tint color to SFSymbols image based on Appearance? By default it goes from black to white and viceversa, but I would like to customize those colors.
In short, this works as expected, switching from light to dark and viceversa, but I need the control of which tint to apply.

let image = UIImage(systemName: "car")
let imageView = UIImageView(image: image)

2

Answers


  1. private var image = UIImage(systemName: "car")?.withTintColor(.systemRed, renderingMode: .alwaysOriginal)
    private var imageView: UIImageView?
    
    private func changeImageTint() {
        let tintColor: UIColor = traitCollection.userInterfaceStyle == .dark ? .systemRed : .systemBlue
        image = image?.withTintColor(tintColor)
        imageView?.image = image
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        changeImageTint()
    }
    

    or create a custom color (2 colors) based on userInterfaceStyle and just use that:

    extension UIColor {
        static var mySymbolColor: UIColor { UIColor.init { $0.userInterfaceStyle == .dark ? .systemRed : .systemGreen } }
    }
    
    button.configuration?.image = UIImage(systemName: "car")?.withTintColor(.mySymbolColor, renderingMode: .alwaysOriginal)
    
    Login or Signup to reply.
  2. You can create an image instance with different appearances for dark and light mode by adding additional variants to the imageAsset. For example:

    let image = UIImage(systemName: "car")!
        .withTintColor(.systemRed, renderingMode: .alwaysOriginal)
    let darkImage = UIImage(systemName: "car")!
        .withTintColor(.systemBlue, renderingMode: .alwaysOriginal)
        
    image.imageAsset?.register(
        darkImage,
        with: .init(userInterfaceStyle: .dark)
    )
    

    Now image should be automatically rendered red in light mode and blue in dark mode.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search