Search code examples
swiftlightios-darkmode

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)
}

Solution

  • 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