SceneKit: supporting adaptive UIColor (dark mode)

Viewed 74

On an SCNScene you can easily set a background color using for example:

background.contents = UIColor.tertiarySystemGroupedBackground

However, some UIColor like the one in the example can have multiple appearances so when the user switches between light and dark mode the color automatically adapts. SceneKit however does not update it's value when the TraitCollection changes (the user switches the appearance).

So the question is, how can you let SceneKit properly switch it's value when the appearance changes?

1 Answers

If you have a view controller that manages the SCNView / the scene, you can use the traitCollectionDidChange method to resolve the actual colors and update the scene accordingly. For example:

class Example3DViewController: UIViewController {

    // ...

    var sceneBackgroundColor: UIColor = .systemBackground {
        didSet {
            self.updateColors()
        }
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        self.updateColors()
    }
    
    func updateColors() {
        self.scene.background.contents = self.sceneBackgroundColor.resolvedColor(with: self.traitCollection)
    }

}
Related