跳转至
Structure

EnvironmentValues

A collection of environment values propagated through a view hierarchy.

Declaration

struct EnvironmentValues : CustomStringConvertible

Overview

SwiftUI exposes a collection of values to your app's views in an EnvironmentValues structure. To read a value from the structure, declare a property using the Environment property wrapper and specify the value's key path. For example, you can read the current locale:

@Environment(\.locale) var locale: Locale
Use the property you declare to dynamically control a view's layout. SwiftUI automatically sets or updates many environment values, like pixelLength, scenePhase, or locale, based on device characteristics, system state, or user settings. For others, like lineLimit, SwiftUI provides a reasonable default value.

You can set or override some values using the environment(_:_:) view modifier:

struct ContentView: View {
    var body: some View {
        Text("This is some long, multiline text 💬, that just keeps going")
            .frame(width: 200)
            .environment(\.lineLimit, 2)
    }
}
A white view containing text with a small frame width and an evironment modifier defining a line limit of two; the text displays as "This is some long multiline text 💬, that ju...".

The value that you set affects the environment for the view that you modify --- including its descendants in the view hierarchy --- but only up to the point where you apply a different environment modifier.

SwiftUI provides dedicated view modifiers for setting some values, which typically makes your code easier to read. For example, rather than setting the lineLimit value directly, as in the previous example, you should instead use the lineLimit(_:) modifier:

struct ContentView: View {
    var body: some View {
        Text("This is some long, multiline text 💬, that just keeps going")
            .frame(width: 200)
            .lineLimit(2)
    }
}
A white view containing text with a small frame width and a line limit of two; the text displays as "This is some long multiline text 💬, that ju...".

In some cases, using a dedicated view modifier provides additional functionality. For example, you must use the preferredColorScheme(_:) modifier rather than setting colorScheme directly to ensure that the new value propagates up to the presenting container when presenting a view like a popover:

struct ContentView: View {
    @State var isPopped = false

    var body: some View {
        Button("Tap me for dark mode! 🌚🌙") { isPopped = true }
            .popover(isPresented: $isPopped) {
                Text("This is some dark 🌠🌉🌌 text")
                    .preferredColorScheme(.dark)
            }
    }
}
A gif displaying a white view with a default style button reading "Tap me for dark mode! 🌚🌙", which when clicked results in the appearance of a popover view with the preferred color scheme .dark.

Create custom environment values by defining a type that conforms to the EnvironmentKey protocol, and then extending the environment values structure with a new property. Use your key to get and set the value, and provide a dedicated modifier for clients to use when setting the value:

private struct MyEnvironmentKey: EnvironmentKey {
    static let defaultValue: String = "Default value"
}

extension EnvironmentValues {
    var myCustomValue: String {
        get { self[MyEnvironmentKey.self] }
        set { self[MyEnvironmentKey.self] = newValue }
    }
}

extension View {
    func myCustomValue(\_ myCustomValue: String) -> some View {
        environment(\.myCustomValue, myCustomValue)
    }
}
Clients of your value then access the value in the usual way, reading it with the Environment property wrapper, and setting it with the myCustomValue view modifier.

Availability

iOS 13.0+

macOS 10.15+

tvOS 13.0+

watchOS 6.0+

Topics


Instance Property

accessibilityDifferentiateWithoutColor Whether the system preference for Differentiate without Color is enabled.

accessibilityEnabled A Boolean value that indicates whether the user has enabled an assistive technology.

accessibilityInvertColors Whether the system preference for Invert Colors is enabled.

accessibilityReduceMotion Whether the system preference for Reduce Motion is enabled.

accessibilityReduceTransparency Whether the system preference for Reduce Transparency is enabled.

accessibilityShowButtonShapes Whether the system preference for Show Button Shapes is enabled.

allowsTightening A Boolean value that indicates whether inter-character spacing should tighten to fit the text into the available space.

calendar The current calendar that views should use when handling dates.

colorScheme The color scheme of this environment.

colorSchemeContrast The contrast associated with the color scheme of this environment.

defaultMinListHeaderHeight The default minimum height of a header in a list.

defaultMinListRowHeight The default minimum height of a row in a list.

description A string that represents the contents of the environment values instance.

disableAutocorrection A Boolean value that determines whether the view hierarchy has auto-correction enabled.

displayScale The display scale of this environment.

editMode The mode indicating whether the user can edit the contents of a view associated with this environment.

font The default font of this environment.

horizontalSizeClass The horizontal size class of this environment.

imageScale The image scale for this environment.

isEnabled A Boolean value that indicates whether the view associated with this environment allows user interaction.

isFocused Returns whether the nearest focusable ancestor has focus.

layoutDirection The layout direction associated with the current environment.

legibilityWeight The font weight to apply to text.

lineLimit The maximum number of lines that text can occupy in a view.

lineSpacing The distance in points between the bottom of one line fragment and the top of the next.

locale The current locale that views should use.

managedObjectContext The object space that you use to manipulate and track changes to the environment values.

minimumScaleFactor The minimum permissible proportion to shrink the font size to fit the text into the available space.

multilineTextAlignment A value that indicates how text instance aligns its lines when the content wraps or contains newlines.

openURL Opens a URL using the appropriate system service.

pixelLength The size of a pixel on the screen.

presentationMode A binding to the current presentation mode of the view associated with this environment.

redactionReasons The current redaction reasons applied to the view hierarchy.

scenePhase The current phase of the scene.

sizeCategory The preferred size of the content.

textCase A stylistic override to transform the case of Text when displayed, using the environment's locale.

timeZone The current time zone that views should use when handling dates.

truncationMode A value that indicates how the layout truncates the last line of text to fit into the available space.

undoManager The undo manager used to register a view's undo operations.

verticalSizeClass The vertical size class of this environment.


Initializer

init() Creates an environment values instance.


Subscript

subscript(key:) Accesses the environment value associated with a custom key.