Initializer

init(_:bundle:)

Creates a color from a color set that you indicate by name.

Declaration 宣言

init(_ name: String, bundle: Bundle? = nil)

Parameters パラメータ

name

The name of the color resource to look up.

bundle

The bundle in which to search for the color resource. If you don’t indicate a bundle, the initializer looks in your app’s main bundle by default.

Discussion 議論

Use this initializer to load a color from a color set stored in an Asset Catalog. The system determines which color within the set to use based on the environment at render time. For example, you can provide light and dark versions for background and foreground colors:

A screenshot of color sets for foreground and background colors,

You can then instantiate colors by referencing the names of the assets:


struct Hello: View {
    var body: some View {
        ZStack {
            Color("background")
            Text("Hello, world!")
                .foregroundStyle(Color("foreground"))
        }
        .frame(width: 200, height: 100)
    }
}

SwiftUI renders the appropriate colors for each appearance:

A side by side comparison of light and dark appearance screenshots