iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎨

Changing UIColor based on UI hierarchy

に公開

Setting UIColor.systemBackground changes the color depending on the modal hierarchy.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground
    }
}

The following screenshots show a ViewController with its background color set to systemBackground, and the same one presented modally.

Before Transition After Transition

To implement this behavior yourself, refer to userInterfaceLevel.
In a modally presented ViewController, it becomes .elevated.

extension UIColor {
    static var appBackground: UIColor = UIColor { traitCollection in
        switch traitCollection.userInterfaceLevel {
        case .base:
            return .orange
        case .elevated:
            return .red
        }
    }
}
...

view.backgroundColor = .appBackground
Before Transition After Transition

Discussion