CableGuy
CableGuy

Reputation: 87

Light and dark mode in swift

I created images assets for dark and light mode called myImage. Set the image assets appearance to Any, Dark.

The problem this code gets the same image even if the mode is light or dark.

How can I get the code to select the correct image depending on light or dark mode?

Thanks for your help.

let image = UIImage(named: "image")
let asset = image?.imageAsset
let resolvedImage =    asset?.image(with: traitCollection)

If let image = resolvedImage {
  myButton.setImage(image, for:     .normal)
}

Upvotes: 2

Views: 3565

Answers (2)

Gereon
Gereon

Reputation: 17844

let image = UIImage(named: "image") is usually all that is needed, if you setup your asset correctly. Make sure to have "Appearances" set to "Any, Dark", then add your images in the appropriate slots:

enter image description here

Upvotes: 12

FrugalResolution
FrugalResolution

Reputation: 655

Find out the current used dark/light mode with:

if traitCollection.userInterfaceStyle == .light {
    print("Light mode")
} else {
    print("Dark mode")
}

Then I'd access the light/dark Images with different name: UIImage:(named: "myImageLightMode") and UIImage:(named: "myImageDarkMode")

Keep in mind that you can tint images like button images in the desired color like the following, when you don't want to create each icon on a different color:

if let originalImage = UIImage(named: "yourButtonImage") {
    let tintedImage = originalImage.withRenderingMode(.alwaysTemplate)
    customButton.setImage(tintedImage, for: .normal)
    customButton.tintColor = UIColor.red
} else {
    print("Image not found.")
}

The same can be done on UIImageView's with the extension:

extension UIImageView {
    func setImageAndColor(image: UIImage, color: UIColor) {
        let templateImage = image.withRenderingMode(.alwaysTemplate)
        self.image = templateImage
        self.tintColor = color
    }
}

access this with:

let imageView = UIImageView()
imageView.setImageAndColor(image: UIImage(named: "yourImage"), color: .red)

Upvotes: 0

Related Questions