Skip to content

Instantly share code, notes, and snippets.

@S-Shimotori
Last active October 29, 2019 13:03
Show Gist options
  • Save S-Shimotori/93da32dfb74939eb0b4972bd38f921dc to your computer and use it in GitHub Desktop.
Save S-Shimotori/93da32dfb74939eb0b4972bd38f921dc to your computer and use it in GitHub Desktop.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// static images
let lightImage = UIImage(named: "LightImage")!
let darkImage = UIImage(named: "DarkImage")!
// https://developer.apple.com/documentation/uikit/uitraitcollection/1651062-init
let lightCollection = UITraitCollection(userInterfaceStyle: .light)
let darkCollection = UITraitCollection(userInterfaceStyle: .dark)
let imageAsset = UIImageAsset()
// https://developer.apple.com/documentation/uikit/uiimageasset/1624974-register
imageAsset.register(lightImage, with: lightCollection)
imageAsset.register(darkImage, with: darkCollection)
let imageView = UIImageView()
// dynamic image
// https://developer.apple.com/documentation/uikit/uiimageasset/1624976-image
imageView.image = imageAsset.image(with: UITraitCollection.current)
imageView.frame = CGRect.init(x: 0, y: 0, width: 400, height: 400)
view.addSubview(imageView)
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// static images
let image0 = UIImage(named: "Image0")!
let image1 = UIImage(named: "Image1")!
let lightCollection = UITraitCollection(userInterfaceStyle: .light)
let darkCollection = UITraitCollection(userInterfaceStyle: .dark)
// You can also use `traitCollection` from `UITraitEnvironment`.
let imageAsset0 = UIImageAsset()
imageAsset0.register(image0, with: lightCollection)
imageAsset0.register(image1, with: darkCollection)
let dynamicImage0 = imageAsset0.image(with: self.traitCollection)
let imageAsset1 = UIImageAsset()
imageAsset1.register(image1, with: lightCollection)
imageAsset1.register(image0, with: darkCollection)
let dynamicImage1 = imageAsset1.image(with: self.traitCollection)
let button = UIButton()
button.frame = CGRect(x: 0, y: 300, width: 400, height: 400)
button.setBackgroundImage(dynamicImage0, for: .normal)
button.setBackgroundImage(dynamicImage1, for: .highlighted)
button.addTarget(self, action: #selector(tapped(_:)), for: .touchUpInside)
view.addSubview(button)
}
@objc private func tapped(_ sender: UIButton) {
switch overrideUserInterfaceStyle {
case .dark:
overrideUserInterfaceStyle = .light
default:
overrideUserInterfaceStyle = .dark
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment