1.8 MiB
https://developer.apple.com/documentation/swiftui/
Framework
SwiftUI
Declare the user interface and behavior for your app on every platform.
Overview
SwiftUI provides views, controls, and layout structures for declaring your app’s user interface. The framework provides event handlers for delivering taps, gestures, and other types of input to your app, and tools to manage the flow of data from your app’s models down to the views and controls that users see and interact with.
Define your app structure using the App protocol, and populate it with scenes that contain the views that make up your app’s user interface. Create your own custom views that conform to the View protocol, and compose them with SwiftUI views for displaying text, images, and custom shapes using stacks, lists, and more. Apply powerful modifiers to built-in views and your own views to customize their rendering and interactivity. Share code between apps on multiple platforms with views and controls that adapt to their context and presentation.
You can integrate SwiftUI views with objects from the UIKit, AppKit, and WatchKit frameworks to take further advantage of platform-specific functionality. You can also customize accessibility support in SwiftUI, and localize your app’s interface for different languages, countries, or cultural regions.
Featured samples
Topics
Essentials
Adopting Liquid Glass
Find out how to bring the new material to your app.
Learning SwiftUI
Discover tips and techniques for building multiplatform apps with this set of conceptual articles and sample code.
Exploring SwiftUI Sample Apps
Explore these SwiftUI samples using Swift Playgrounds on iPad or in Xcode to learn about defining user interfaces, responding to user interactions, and managing data flow.
SwiftUI updates
Learn about important changes to SwiftUI.
Landmarks: Building an app with Liquid Glass
Enhance your app experience with system-provided and custom Liquid Glass.
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
Data and storage
Manage the data that your app uses to drive its interface.
Share data throughout a view hierarchy using the environment.
Indicate configuration preferences from views to their container views.
Store data for use across sessions of your app.
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
View layout
Arrange views inside built-in layout containers like stacks and grids.
Make fine adjustments to alignment, spacing, padding, and other layout parameters.
Place views in custom arrangements and create animated transitions between layout types.
Display a structured, scrollable column of information.
Display selectable, sortable data arranged in rows and columns.
Present views in different kinds of purpose-driven containers, like forms or control groups.
Enable people to scroll to content that doesn’t fit in the current display.
Event handling
Define interactions from taps, clicks, and swipes to fine-grained gestures.
Respond to input from a hardware device, like a keyboard or a Touch Bar.
Enable people to move or duplicate items by issuing Copy and Paste commands.
Enable people to move or duplicate items by dragging them from one location to another.
Identify and control which visible object responds to user interaction.
React to system events, like opening a URL.
Accessibility
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Enhance the legibility of content in your app’s interface.
Improve access to actions that your app can undertake.
Describe interface elements to help people understand what they represent.
Enable users to navigate to specific user interface elements using rotors.
Framework integration
Add AppKit views to your SwiftUI app, or use SwiftUI views in your AppKit app.
Add UIKit views to your SwiftUI app, or use SwiftUI views in your UIKit app.
Add WatchKit views to your SwiftUI app, or use SwiftUI views in your WatchKit app.
Use SwiftUI views that other Apple frameworks provide.
Tool support
Generate dynamic, interactive previews of your custom views.
Expose custom views and modifiers in the Xcode library.
Measure and improve your app’s responsiveness.
https://developer.apple.com/documentation/swiftui
Framework
SwiftUI
Declare the user interface and behavior for your app on every platform.
Overview
SwiftUI provides views, controls, and layout structures for declaring your app’s user interface. The framework provides event handlers for delivering taps, gestures, and other types of input to your app, and tools to manage the flow of data from your app’s models down to the views and controls that users see and interact with.
Define your app structure using the App protocol, and populate it with scenes that contain the views that make up your app’s user interface. Create your own custom views that conform to the View protocol, and compose them with SwiftUI views for displaying text, images, and custom shapes using stacks, lists, and more. Apply powerful modifiers to built-in views and your own views to customize their rendering and interactivity. Share code between apps on multiple platforms with views and controls that adapt to their context and presentation.
You can integrate SwiftUI views with objects from the UIKit, AppKit, and WatchKit frameworks to take further advantage of platform-specific functionality. You can also customize accessibility support in SwiftUI, and localize your app’s interface for different languages, countries, or cultural regions.
Featured samples
Topics
Essentials
Adopting Liquid Glass
Find out how to bring the new material to your app.
Learning SwiftUI
Discover tips and techniques for building multiplatform apps with this set of conceptual articles and sample code.
Exploring SwiftUI Sample Apps
Explore these SwiftUI samples using Swift Playgrounds on iPad or in Xcode to learn about defining user interfaces, responding to user interactions, and managing data flow.
SwiftUI updates
Learn about important changes to SwiftUI.
Landmarks: Building an app with Liquid Glass
Enhance your app experience with system-provided and custom Liquid Glass.
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
Data and storage
Manage the data that your app uses to drive its interface.
Share data throughout a view hierarchy using the environment.
Indicate configuration preferences from views to their container views.
Store data for use across sessions of your app.
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
View layout
Arrange views inside built-in layout containers like stacks and grids.
Make fine adjustments to alignment, spacing, padding, and other layout parameters.
Place views in custom arrangements and create animated transitions between layout types.
Display a structured, scrollable column of information.
Display selectable, sortable data arranged in rows and columns.
Present views in different kinds of purpose-driven containers, like forms or control groups.
Enable people to scroll to content that doesn’t fit in the current display.
Event handling
Define interactions from taps, clicks, and swipes to fine-grained gestures.
Respond to input from a hardware device, like a keyboard or a Touch Bar.
Enable people to move or duplicate items by issuing Copy and Paste commands.
Enable people to move or duplicate items by dragging them from one location to another.
Identify and control which visible object responds to user interaction.
React to system events, like opening a URL.
Accessibility
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Enhance the legibility of content in your app’s interface.
Improve access to actions that your app can undertake.
Describe interface elements to help people understand what they represent.
Enable users to navigate to specific user interface elements using rotors.
Framework integration
Add AppKit views to your SwiftUI app, or use SwiftUI views in your AppKit app.
Add UIKit views to your SwiftUI app, or use SwiftUI views in your UIKit app.
Add WatchKit views to your SwiftUI app, or use SwiftUI views in your WatchKit app.
Use SwiftUI views that other Apple frameworks provide.
Tool support
Generate dynamic, interactive previews of your custom views.
Expose custom views and modifiers in the Xcode library.
Measure and improve your app’s responsiveness.
https://developer.apple.com/documentation/swiftui/app
- SwiftUI
- App
Protocol
App
A type that represents the structure and behavior of an app.
@MainActor @preconcurrency protocol App
Mentioned in
Migrating to the SwiftUI life cycle
Overview
Create an app by declaring a structure that conforms to the App protocol. Implement the required body computed property to define the app’s content:
@main struct MyApp: App { var body: some Scene { WindowGroup { Text("Hello, world!") } } }
Precede the structure’s declaration with the @main attribute to indicate that your custom App protocol conformer provides the entry point into your app. The protocol provides a default implementation of the main() method that the system calls to launch your app. You can have exactly one entry point among all of your app’s files.
Compose the app’s body from instances that conform to the Scene protocol. Each scene contains the root view of a view hierarchy and has a life cycle managed by the system. SwiftUI provides some concrete scene types to handle common scenarios, like for displaying documents or settings. You can also create custom scenes.
@main struct Mail: App { var body: some Scene { WindowGroup { MailViewer() } Settings { SettingsView() } } }
You can declare state in your app to share across all of its scenes. For example, you can use the StateObject attribute to initialize a data model, and then provide that model on a view input as an ObservedObject or through the environment as an EnvironmentObject to scenes in the app:
@main struct Mail: App { @StateObject private var model = MailModel()
var body: some Scene { WindowGroup { MailViewer() .environmentObject(model) // Passed through the environment. } Settings { SettingsView(model: model) // Passed as an observed object. } } }
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is included in the type’s base declaration:
struct MyCustomType: Transition {
// @preconcurrency @MainActor isolation by default
}
Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt out of main actor isolation:
extension MyCustomType: Transition {
// nonisolated by default
}
Topics
Implementing an app
var body: Self.Body
The content and behavior of the app.
Required
associatedtype Body : Scene
The type of scene representing the content of the app.
Running an app
init()
Creates an instance of the app using the body that you define for its content.
static func main()
Initializes and runs the app.
See Also
Creating an app
Destination Video
Leverage SwiftUI to build an immersive media experience in a multiplatform app.
Hello World
Use windows, volumes, and immersive spaces to teach people about the Earth.
Backyard Birds: Building an app with SwiftData and widgets
Create an app with persistent data, interactive widgets, and an all new in-app purchase experience.
Food Truck: Building a SwiftUI multiplatform app
Create a single codebase and app target for Mac, iPad, and iPhone.
Fruta: Building a Feature-Rich App with SwiftUI
Create a shared codebase to build a multiplatform app that offers widgets and an App Clip.
Use a scene-based life cycle in SwiftUI while keeping your existing codebase.
https://developer.apple.com/documentation/swiftui/view
- SwiftUI
- View
Protocol
View
A type that represents part of your app’s user interface and provides modifiers that you use to configure views.
@MainActor @preconcurrency protocol View
Mentioned in
Declaring a custom view
Configuring views
Reducing view modifier maintenance
Migrating to the SwiftUI life cycle
Displaying data in lists
Overview
You create custom views by declaring types that conform to the View protocol. Implement the required body computed property to provide the content for your custom view.
struct MyView: View { var body: some View { Text("Hello, World!") } }
Assemble the view’s body by combining one or more of the built-in views provided by SwiftUI, like the Text instance in the example above, plus other custom views that you define, into a hierarchy of views. For more information about creating custom views, see Declaring a custom view.
The View protocol provides a set of modifiers — protocol methods with default implementations — that you use to configure views in the layout of your app. Modifiers work by wrapping the view instance on which you call them in another view with the specified characteristics, as described in Configuring views. For example, adding the opacity(_:) modifier to a text view returns a new view with some amount of transparency:
Text("Hello, World!") .opacity(0.5) // Display partially transparent text.
The complete list of default modifiers provides a large set of controls for managing views. For example, you can fine tune Layout modifiers, add Accessibility modifiers information, and respond to Input and event modifiers. You can also collect groups of default modifiers into new, custom view modifiers for easy reuse.
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is declared in its original declaration. Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt-out the isolation.
Topics
Implementing a custom view
var body: Self.Body
The content and behavior of the view.
Required Default implementations provided.
associatedtype Body : View
The type of view representing the body of this view.
Required
Applies a modifier to a view and returns a new view.
Generate dynamic, interactive previews of your custom views.
Configuring view elements
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Configure a view’s foreground and background styles, controls, and visibility.
Manage the rendering, selection, and entry of text in your view.
Add and configure supporting views, like toolbars and context menus.
Configure charts that you declare with Swift Charts.
Drawing views
Apply built-in styles to different types of views.
Tell a view how to arrange itself within a view hierarchy by adjusting its size, position, alignment, padding, and so on.
Affect the way the system draws a view, for example by scaling or masking a view, or by applying graphical effects.
Providing interactivity
Supply actions for a view to perform in response to user input and system events.
Enable people to search for content in your app.
Define additional views for the view to present under specified conditions.
Access storage and provide child views with configuration data.
Deprecated modifiers
Review unsupported modifiers and their replacements.
Instance Methods
Adds multiple accessibility actions to the view with a specific category. Actions allow assistive technologies, such as VoiceOver, to interact with the view by invoking the action and are grouped by their category. When multiple action modifiers with an equal category are applied to the view, the actions are combined together.
Defines a region in which default accessibility focus is evaluated by assigning a value to a given accessibility focus state binding.
Beta
func accessibilityScrollStatus(_:isEnabled:)
Changes the announcement provided by accessibility technologies when a user scrolls a scroll view within this view.
The view modifier that can be applied to AccessoryWidgetGroup to specify the shape the three content views will be masked with. The value of style is set to .automatic, which is .circular by default.
Sets the button’s style.
Sets the style to be used by the button. (see PKAddPassButtonStyle).
Configures gestures in this view hierarchy to handle events that activate the containing window.
Constrains this view’s dimensions to the specified 3D aspect ratio.
Configures the view’s icon for purposes of navigation.
func attributedTextFormattingDefinition(_:)
Apply a text formatting definition to all nested editor views.
Presents a modal view that enables users to add devices to their organization.
Adds the background extension effect to the view. The view will be duplicated into mirrored copies which will be placed around the view on any edge with available safe area. Additionally, a blur effect will be applied on top to blur out the copies.
Ensures that the view is always visible to the user, even when other content is occluding it, like 3D models.
Displays a certificate sheet using the provided certificate trust.
func chart3DPose(_:) Beta
Sets the visibility of the z axis.
Configures the z-axis for 3D charts in the view.
func chartZAxisLabel(_:position:alignment:spacing:)
Adds z axis label for charts in the view. It effects 3D charts only.
Modally present UI which allows the user to select which contacts your app has access to.
Sets a particular container value of a view.
func contentToolbar(for:content:)
Populates the toolbar of the specified content view type with the views you provide.
A continuityDevicePicker should be used to discover and connect nearby continuity device through a button interface or other form of activation. On tvOS, this presents a fullscreen continuity device picker experience when selected. The modal view covers as much the screen of self as possible when a given condition is true.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Whether the alert or confirmation dialog prevents the app from being quit/terminated by the system or app termination menu item.
Adds to a DocumentLaunchView actions that accept a list of selected files as their parameter.
Configures a drag session.
A container with draggable views. The drag payload is based on the current selection.
func dragContainer(for:id:in:selection:_:)
A container with single item selection and draggable views. The drag payload is based on the current selection and provided identifiers.
A container with draggable views. The drag payload is identifiable. To form the payload, use the identifier of the dragged view inside the container.
func dragContainer(for:in:selection:_:)
A container with multiple selection and draggable views. The drag payload is identifiable and is based on the current selection.
Describes the way dragged previews are visually composed.
Activates this view as the source of a drag and drop operation. A view can be dragged separately, or as an element of a drag container.
Inside a drag container, activates this view as the source of a drag and drop operation. Supports lazy drag containers.
Activates this view as the source of a drag-and-drop operation.
Configures a drop session.
Defines the destination of a drag and drop operation that provides a drop operation proposal and handles the dropped content with a closure that you specify.
Describes the way previews for a drop are composed.
Sets the style for forms in a view hierarchy.
Presents a modal view while the game synced directory loads.
Fills the view’s background with a custom glass background effect and container-relative rounded rectangle shape.
Fills the view’s background with a custom glass background effect and a shape that you specify.
Applies the Liquid Glass effect to a view.
Associates an identity value to Liquid Glass effects defined within this view.
Associates a glass effect transition with any glass effects defined within this view.
Associates any Liquid Glass effects defined within this view to a union with the provided identifier.
Specifies how a view should be associated with the current SharePlay group activity.
Assigns a hand gesture shortcut to the modified control.
Sets the behavior of the hand pointer while the user is interacting with the view.
Specifies the game controllers events which should be delivered through the GameController framework when the view, or one of its descendants has focus.
Specifies the game controllers events which should be delivered through the GameController framework when the view or one of its descendants has focus.
Asynchronously requests permission to read a data type that requires per-object authorization (such as vision prescriptions).
Requests permission to read the specified HealthKit data types.
Requests permission to save and read the specified HealthKit data types.
Sets the generation style for an image playground.
Policy determining whether to support the usage of people in the playground or not.
Presents the system sheet to create images from the specified input.
Add menu items to open immersive spaces from a media player’s environment picker.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Presents a visual picker interface that contains events and images that a person can select to retrieve more information.
Set the spacing between the icon and title in labels.
Set the width reserved for icons in labels.
Sets a style for labeled content.
Controls the visibility of labels of any controls contained within this view.
A modifier for the default line height in the view hierarchy.
Sets the insets of rows in a list on the specified edges.
Changes the visibility of the list section index.
Set the section margins for the specific edges.
Applies a managed content style to the view.
Allows this view to be manipulated using common hand gestures.
Applies the given 3D affine transform to the view and allows it to be manipulated using common hand gestures.
Allows the view to be manipulated using a manipulation gesture attached to a different view.
Adds a manipulation gesture to this view without allowing this view to be manipulable itself.
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
Configures all Map controls in the environment to have the specified visibility
Configures all Map views in the associated environment to have standard size and position controls
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Specifies which map features should have selection disabled.
Presents a map item detail popover.
Presents a map item detail sheet.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies the map style to be used.
Identifies this view as the source of a navigation transition, such as a zoom transition.
Sets an explicit active appearance for materials in this view.
A modifier for the default text alignment strategy in the view hierarchy.
Configures whether navigation links show a disclosure indicator.
Sets the navigation transition style for this view.
Registers a handler to invoke in response to the specified app intent that your app receives.
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
func onCameraCaptureEvent(isEnabled:defaultSoundDisabled:action:)
Used to register an action triggered by system capture events.
func onCameraCaptureEvent(isEnabled:defaultSoundDisabled:primaryAction:secondaryAction:)
Used to register actions triggered by system capture events.
Specifies an action to perform on each update of an ongoing dragging operation activated by draggable(_:) or other drag modifiers.
Specifies an action to perform on each update of an ongoing drop operation activated by dropDestination(_:) or other drop modifiers.
func onGeometryChange3D(for:of:action:)
Returns a new view that arranges to call action(value) whenever the value computed by transform(proxy) changes, where proxy provides access to the view’s 3D geometry properties.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Sets an OpenURLAction that prefers opening URL with an in-app browser. It’s equivalent to calling .onOpenURL(_:)
func onWorldRecenter(action:)
Adds an action to perform when recentering the view with the digital crown.
Sets the action on the PayLaterView. See PKPayLaterAction.
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
Sets the features that should be allowed to show on the payment buttons.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Presents a popover tip on the modified view.
func postToPhotosSharedAlbumSheet(isPresented:items:photoLibrary:defaultAlbumIdentifier:completion:)
Presents an “Add to Shared Album” sheet that allows the user to post the given items to a shared album.
Selects a subscription offer to apply to a purchase that a customer makes from a subscription store view, a store view, or a product view.
func preferredWindowClippingMargins(_:_:)
Requests additional margins for drawing beyond the bounds of the window.
Changes the way the enclosing presentation breaks through content occluding it.
Whether a presentation prevents the app from being terminated/quit by the system or app termination menu item.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Adds gestures that control the position and direction of a virtual camera.
Controls the frame sizing and content alignment behavior for RealityView
Rotates a view with impacts to its frame in a containing layout
func rotation3DLayout(_:axis:)
func safeAreaBar(edge:alignment:spacing:content:)
Renders the provided content appropriately to be displayed as a custom bar.
Scales this view to fill its parent.
Scales this view to fit its parent.
Disables any scroll edge effects for scroll views within this hierarchy.
Configures the scroll edge effect style for scroll views within this hierarchy.
Enables or disables scrolling in scrollable views when using particular inputs.
Configures the behavior for search in the toolbar.
func sectionIndexLabel(_:)
Sets the label that is used in a section index to point to this section, typically only a single character long.
Sets the style used for displaying the control (see SignInWithAppleButton.Style).
Adds secondary views within the 3D bounds of this view.
Uses the specified preference value from the view to produce another view occupying the same 3D space of the first view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
Declares the view as dependent on a collection of In-App Purchase products and returns a modified view.
Selects the introductory offer eligibility preference to apply to a purchase a customer makes from a subscription store view.
Selects a promotional offer to apply to a purchase a customer makes from a subscription store view.
Deprecated
Declares the view as dependent on the status of an auto-renewable subscription group, and returns a modified view.
Configures subscription store view instances within a view to use the provided button label.
func subscriptionStoreControlBackground(_:)
Set a standard effect to use for the background of subscription store view controls within the view.
Sets a view to use to decorate individual subscription options within a subscription store view.
Sets the control style for subscription store views within a view.
Sets the control style and control placement for subscription store views within a view.
Sets the style subscription store views within this view use to display groups of subscription options.
Sets the background style for picker items of the subscription store view instances within a view.
Sets the background shape and style for subscription store view picker items within a view.
Configures a view as the destination for a policy button action in subscription store views.
Configures a URL as the destination for a policy button action in subscription store views.
Sets the style for the and buttons within a subscription store view.
Sets the primary and secondary style for the and buttons within a subscription store view.
Adds an action to perform when a person uses the sign-in button on a subscription store view within a view.
Sets the color rendering mode for symbol images.
Sets the variable value mode mode for symbol images within this view.
Sets the behavior for tab bar minimization.
Adds a tabletop game to a view.
Supplies a closure which returns a new interaction whenever needed.
func textContentType(_:)
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on macOS.
Define which system text formatting controls are available.
Returns a new view such that any text views within it will use renderer to draw themselves.
Sets the direction of a selection or cursor relative to a text character.
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
Sets the corner radius for an inline tip view.
Sets the size for a tip’s image.
Sets the style for a tip’s image.
Sets the given style for TipView within the view hierarchy.
Hides an individual view within a control group toolbar item.
Presents a picker that selects a collection of transactions.
Provides a task to perform before this view appears
Presents a translation popover when a given condition is true.
Adds a task to perform before this view appears or when the translation configuration changes.
Adds a task to perform before this view appears or when the specified source or target languages change.
Sets the style to be used by the button. (see PKIdentityButtonStyle).
Determines whether horizontal swipe gestures trigger backward and forward page navigation.
Specifies the visibility of the webpage’s natural background color within this view.
Adds an item-based context menu to a WebView, replacing the default set of context menu items.
Determines whether a web view can display content full screen.
Determines whether pressing a link displays a preview of the destination for the link.
Determines whether magnify gestures change the view’s magnification.
Adds an action to be performed when a value, created from a scroll geometry, changes.
Enables or disables scrolling in web views when using particular inputs.
Associates a binding to a scroll position with the web view.
Determines whether to allow people to select or otherwise interact with text.
Sets the window anchor point used when the size of the view changes such that the window must resize.
Configures the visibility of the window toolbar when the window enters full screen mode.
Presents a preview of the workout contents as a modal sheet
A modifier for the default text writing direction strategy in the view hierarchy.
Specifies whether the system should show the Writing Tools affordance for text input views affected by the environment.
Specifies the Writing Tools behavior for text and text input in the environment.
Relationships
Inherited By
DynamicViewContentInsettableShapeNSViewControllerRepresentableNSViewRepresentableShapeShapeViewUIViewControllerRepresentableUIViewRepresentableWKInterfaceObjectRepresentable
Conforming Types
-
AngularGradient -
AnyShape -
AnyView -
AsyncImage -
Button -
ButtonBorderShape -
ButtonStyleConfiguration.Label -
CanvasConforms whenSymbolsconforms toView. -
Capsule -
Circle -
Color -
ColorPicker -
ContainerRelativeShape -
ContentUnavailableView -
ControlGroup -
ControlGroupStyleConfiguration.Content -
ControlGroupStyleConfiguration.Label -
DatePicker -
DatePickerStyleConfiguration.Label -
DebugReplaceableView -
DefaultButtonLabel -
DefaultDateProgressLabel -
DefaultDocumentGroupLaunchActions -
DefaultSettingsLinkLabel -
DefaultShareLinkLabel -
DefaultTabLabel -
DefaultWindowVisibilityToggleLabel -
DisclosureGroup -
DisclosureGroupStyleConfiguration.Content -
DisclosureGroupStyleConfiguration.Label -
Divider -
DocumentLaunchView -
EditButton -
EditableCollectionContentConforms whenContentconforms toView,Dataconforms toCopyable, andDataconforms toEscapable. -
Ellipse -
EllipticalGradient -
EmptyView -
EquatableView -
FillShapeView -
ForEachConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable, andContentconforms toView. -
Form -
FormStyleConfiguration.Content -
Gauge -
GaugeStyleConfiguration.CurrentValueLabel -
GaugeStyleConfiguration.Label -
GaugeStyleConfiguration.MarkedValueLabel -
GaugeStyleConfiguration.MaximumValueLabel -
GaugeStyleConfiguration.MinimumValueLabel -
GeometryReader -
GeometryReader3D -
GlassBackgroundEffectConfiguration.Content -
GlassEffectContainer -
GridConforms whenContentconforms toView. -
GridRowConforms whenContentconforms toView. -
GroupConforms whenContentconforms toView. -
GroupBox -
GroupBoxStyleConfiguration.Content -
GroupBoxStyleConfiguration.Label -
GroupElementsOfContent -
GroupSectionsOfContent -
HSplitView -
HStack -
HelpLink -
Image -
KeyframeAnimator -
Label -
LabelStyleConfiguration.Icon -
LabelStyleConfiguration.Title -
LabeledContentConforms whenLabelconforms toViewandContentconforms toView. -
LabeledContentStyleConfiguration.Content -
LabeledContentStyleConfiguration.Label -
LabeledControlGroupContent -
LabeledToolbarItemGroupContent -
LazyHGrid -
LazyHStack -
LazyVGrid -
LazyVStack -
LinearGradient -
Link -
List -
Menu -
MenuButton -
MenuStyleConfiguration.Content -
MenuStyleConfiguration.Label -
MeshGradient -
ModifiedContentConforms whenContentconforms toViewandModifierconforms toViewModifier. -
MultiDatePicker -
NavigationLink -
NavigationSplitView -
NavigationStack -
NavigationView -
NewDocumentButton -
OffsetShape -
OutlineGroupConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable,Parentconforms toView,Leafconforms toView, andSubgroupconforms toView. -
OutlineSubgroupChildren -
PasteButton -
Path -
PhaseAnimator -
Picker -
PlaceholderContentView -
PresentedWindowContent -
PreviewModifierContent -
PrimitiveButtonStyleConfiguration.Label -
ProgressView -
ProgressViewStyleConfiguration.CurrentValueLabel -
ProgressViewStyleConfiguration.Label -
RadialGradient -
Rectangle -
RenameButton -
RotatedShape -
RoundedRectangle -
ScaledShape -
ScrollView -
ScrollViewReader -
SearchUnavailableContent.Actions -
SearchUnavailableContent.Description -
SearchUnavailableContent.Label -
SectionConforms whenParentconforms toView,Contentconforms toView, andFooterconforms toView. -
SectionConfiguration.Actions -
SecureField -
SettingsLink -
ShareLink -
Slider -
Spacer -
Stepper -
StrokeBorderShapeView -
StrokeShapeView -
SubscriptionView -
Subview -
SubviewsCollection -
SubviewsCollectionSlice -
TabContentBuilder.Content -
TabView -
Table -
Text -
TextEditor -
TextField -
TextFieldLink -
TimelineViewConforms whenScheduleconforms toTimelineScheduleandContentconforms toView. -
Toggle -
ToggleStyleConfiguration.Label -
TransformedShape -
TupleView -
UnevenRoundedRectangle -
VSplitView -
VStack -
ViewThatFits -
WindowVisibilityToggle -
ZStack -
ZStackContent3DConforms whenContentconforms toView.
See Also
Creating a view
Define views and assemble them into a view hierarchy.
struct ViewBuilder
A custom parameter attribute that constructs views from closures.
https://developer.apple.com/documentation/swiftui/landmarks-building-an-app-with-liquid-glass
- SwiftUI
- Landmarks: Building an app with Liquid Glass Beta
Sample Code
Landmarks: Building an app with Liquid Glass
Enhance your app experience with system-provided and custom Liquid Glass.
Download
Xcode 26.0+Beta
Overview
Landmarks is a SwifUI app that demonstrates how to use the new dynamic and expressive design feature, Liquid Glass. The Landmarks app lets people explore interesting sites around the world. Whether it’s a national park near their home or a far-flung location on a different continent, the app provides a way for people to organize and mark their adventures and receive custom activity badges along the way. Landmarks runs on iPad, iPhone, and Mac.
Landmarks uses a NavigationSplitView to organize and navigate to content in the app, and demonstrates several key concepts to optimize the use of Liquid Glass:
-
Stretching content behind the sidebar and inspector with the background extension effect.
-
Extending horizontal scroll views under a sidebar or inspector.
-
Leveraging the system-provided glass effect in toolbars.
-
Applying Liquid Glass effects to custom interface elements and animations.
-
Building a new app icon with Icon Composer.
The sample also demonstrates several techniques to use when changing window sizes, and for adding global search.
Apply a background extension effect
The sample applies a background extension effect to the featured landmark header in the top view, and the main image in the landmark detail view. This effect extends and blurs the image under the sidebar and inspector when they’re open, creating a full edge-to-edge experience.
To achieve this effect, the sample creates and configures an Image that extends to both the leading and trailing edges of the containing view, and applies the backgroundExtensionEffect() modifier to the image. For the featured image, the sample adds an overlay with a headline and button after the modifier, so that only the image extends under the sidebar and inspector.
For more information, see Landmarks: Applying a background extension effect.
Extend horizontal scrolling under the sidebar
Within each continent section in LandmarksView, an instance of LandmarkHorizontalListView shows a horizontally scrolling list of landmark views. When open, the landmark views can scroll underneath the sidebar or inspector.
To achieve this effect, the app aligns the scroll views next to the leading and trailing edges of the containing view.
For more information, see Landmarks: Extending horizontal scrolling under a sidebar or inspector.
Refine the Liquid Glass in the toolbar
In LandmarkDetailView, the sample adds toolbar items for:
-
sharing a landmark
-
adding or removing a landmark from a list of Favorites
-
adding or removing a landmark from Collections
-
showing or hiding the inspector
The system applies Liquid Glass to toolbar items automatically:
The sample also organizes the toolbar into related groups, instead of having all the buttons in one group. For more information, see Landmarks: Refining the system provided Liquid Glass effect in toolbars.
Display badges with Liquid Glass
Badges provide people with a visual indicator of the activities they’ve recorded in the Landmarks app. When a person completes all four activities for a landmark, they earn that landmark’s badge. The sample uses custom Liquid Glass elements with badges, and shows how to coordinate animations with Liquid Glass.
To create a custom Liquid Glass badge, Landmarks uses a view with an Image to display a system symbol image for the badge. The badge has a background hexagon Image filled with a custom color. The badge view uses the glassEffect(_:in:isEnabled:) modifier to apply Liquid Glass to the badge.
To demonstrate the morphing effect that the system provides with Liquid Glass animations, the sample organizes the badges and the toggle button into a GlassEffectContainer, and assigns each badge a unique glassEffectID(_:in:).
For more information, see Landmarks: Displaying custom activity badges. For information about building custom views with Liquid Glass, see Applying Liquid Glass to custom views.
Create the app icon with Icon Composer
Landmarks includes a dynamic and expressive app icon composed in Icon Composer. You build app icons with four layers that the system uses to produce specular highlights when a person moves their device, so that the icon responds as if light was reflecting off the glass. The Settings app allows people to personalize the icon by selecting light, dark, clear, or tinted variants of your app icon as well.
For more information on creating a new app icon, see Creating your app icon using Icon Composer.
Topics
App features
Landmarks: Applying a background extension effect
Configure an image to blur and extend under a sidebar or inspector panel.
Landmarks: Extending horizontal scrolling under a sidebar or inspector
Improve your horizontal scrollbar’s appearance by extending it under a sidebar or inspector.
Landmarks: Refining the system provided Liquid Glass effect in toolbars
Organize toolbars into related groupings to improve their appearance and utility.
Landmarks: Displaying custom activity badges
Provide people with a way to mark their adventures by displaying animated custom activity badges.
See Also
Essentials
Adopting Liquid Glass
Find out how to bring the new material to your app.
Learning SwiftUI
Discover tips and techniques for building multiplatform apps with this set of conceptual articles and sample code.
Exploring SwiftUI Sample Apps
Explore these SwiftUI samples using Swift Playgrounds on iPad or in Xcode to learn about defining user interfaces, responding to user interactions, and managing data flow.
SwiftUI updates
Learn about important changes to SwiftUI.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/app-organization
Collection
- SwiftUI
- App organization
API Collection
App organization
Define the entry point and top-level structure of your app.
Overview
Describe your app’s structure declaratively, much like you declare a view’s appearance. Create a type that conforms to the App protocol and use it to enumerate the Scenes that represent aspects of your app’s user interface.
SwiftUI enables you to write code that works across all of Apple’s platforms. However, it also enables you to tailor your app to the specific capabilities of each platform. For example, if you need to respond to the callbacks that the system traditionally makes on a UIKit, AppKit, or WatchKit app’s delegate, define a delegate object and instantiate it in your app structure using an appropriate delegate adaptor property wrapper, like UIApplicationDelegateAdaptor.
For platform-specific design guidance, see Getting started in the Human Interface Guidelines.
Topics
Creating an app
Destination Video
Leverage SwiftUI to build an immersive media experience in a multiplatform app.
Hello World
Use windows, volumes, and immersive spaces to teach people about the Earth.
Backyard Birds: Building an app with SwiftData and widgets
Create an app with persistent data, interactive widgets, and an all new in-app purchase experience.
Food Truck: Building a SwiftUI multiplatform app
Create a single codebase and app target for Mac, iPad, and iPhone.
Fruta: Building a Feature-Rich App with SwiftUI
Create a shared codebase to build a multiplatform app that offers widgets and an App Clip.
Migrating to the SwiftUI life cycle
Use a scene-based life cycle in SwiftUI while keeping your existing codebase.
protocol App
A type that represents the structure and behavior of an app.
Targeting iOS and iPadOS
UILaunchScreen
The user interface to show while an app launches.
UILaunchScreens
The user interfaces to show while an app launches in response to different URL schemes.
struct UIApplicationDelegateAdaptor
A property wrapper type that you use to create a UIKit app delegate.
Targeting macOS
struct NSApplicationDelegateAdaptor
A property wrapper type that you use to create an AppKit app delegate.
Targeting watchOS
struct WKApplicationDelegateAdaptor
A property wrapper that is used in App to provide a delegate from WatchKit.
struct WKExtensionDelegateAdaptor
A property wrapper type that you use to create a WatchKit extension delegate.
Targeting tvOS
Creating a tvOS media catalog app in SwiftUI
Build standard content lockups and rows of content shelves for your tvOS app.
Handling system recenter events
enum WorldRecenterPhase
A type that represents information associated with a phase of a system recenter event. Values of this type are passed to the closure specified in View.onWorldRecenter(action:).
Beta
See Also
App structure
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
https://developer.apple.com/documentation/swiftui/scenes
Collection
- SwiftUI
- Scenes
API Collection
Scenes
Declare the user interface groupings that make up the parts of your app.
Overview
A scene represents a part of your app’s user interface that has a life cycle that the system manages. An App instance presents the scenes it contains, while each Scene acts as the root element of a View hierarchy.
The system presents scenes in different ways depending on the type of scene, the platform, and the context. A scene might fill the entire display, part of the display, a window, a tab in a window, or something else. In some cases, your app might also be able to display more than one instance of the scene at a time, like when a user simultaneously opens multiple windows based on a single WindowGroup declaration in your app. For more information about the primary built-in scene types, see Windows and Documents.
You configure scenes using modifiers, similar to how you configure views. For example, you can adjust the appearance of the window that contains a scene — if the scene happens to appear in a window — using the windowStyle(_:) modifier. Similarly, you can add menu commands that become available when the scene is in the foreground on certain platforms using the commands(content:) modifier.
Topics
Creating scenes
protocol Scene
A part of an app’s user interface with a life cycle managed by the system.
struct SceneBuilder
A result builder for composing a collection of scenes into a single composite scene.
Monitoring scene life cycle
var scenePhase: ScenePhase
The current phase of the scene.
enum ScenePhase
An indication of a scene’s operational state.
Managing a settings window
struct Settings
A scene that presents an interface for viewing and modifying an app’s settings.
struct SettingsLink
A view that opens the Settings scene defined by an app.
struct OpenSettingsAction
An action that presents the settings scene for an app.
var openSettings: OpenSettingsAction
A Settings presentation action stored in a view’s environment.
Building a menu bar
Building and customizing the menu bar with SwiftUI
Provide a seamless, cross-platform user experience by building a native menu bar for iPadOS and macOS.
Creating a menu bar extra
struct MenuBarExtra
A scene that renders itself as a persistent control in the system menu bar.
Sets the style for menu bar extra created by this scene.
protocol MenuBarExtraStyle
A specification for the appearance and behavior of a menu bar extra scene.
Creating watch notifications
struct WKNotificationScene
A scene which appears in response to receiving the specified category of remote or local notifications.
See Also
App structure
Define the entry point and top-level structure of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
https://developer.apple.com/documentation/swiftui/windows
Collection
- SwiftUI
- Windows
API Collection
Windows
Display user interface content in a window or a collection of windows.
Overview
The most common way to present a view hierarchy in your app’s interface is with a WindowGroup, which produces a platform-specific behavior and appearance.
On platforms that support it, people can open multiple windows from the group simultaneously. Each window relies on the same root view definition, but retains its own view state. On some platforms, you can also supplement your app’s user interface with a single-instance window using the Window scene type.
Configure windows using scene modifiers that you add to the window declaration, like windowStyle(_:) or defaultPosition(_:). You can also indicate how to configure new windows that you present from a view hierarchy by adding the presentedWindowStyle(_:) view modifier to a view in the hierarchy.
For design guidance, see Windows in the Human Interface Guidelines.
Topics
Essentials
Customizing window styles and state-restoration behavior in macOS
Configure how your app’s windows look and function in macOS to provide an engaging and more coherent experience.
Bringing multiple windows to your SwiftUI app
Compose rich views by reacting to state changes and customize your app’s scene presentation and behavior on iPadOS and macOS.
Creating windows
struct WindowGroup
A scene that presents a group of identically structured windows.
struct Window
A scene that presents its content in a single, unique window.
struct UtilityWindow
A specialized window scene that provides secondary utility to the content of the main scenes of an application.
protocol WindowStyle
A specification for the appearance and interaction of a window.
Sets the style for windows created by this scene.
Styling the associated toolbar
Sets the style for the toolbar defined within this scene.
Sets the label style of items in a toolbar and enables user customization.
Sets the label style of items in a toolbar.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
Opening windows
Presenting windows and spaces
Open and close the scenes that make up your app’s interface.
var supportsMultipleWindows: Bool
A Boolean value that indicates whether the current platform supports opening multiple windows.
var openWindow: OpenWindowAction
A window presentation action stored in a view’s environment.
struct OpenWindowAction
An action that presents a window.
struct PushWindowAction
An action that opens the requested window in place of the window the action is called from.
Closing windows
var dismissWindow: DismissWindowAction
A window dismissal action stored in a view’s environment.
struct DismissWindowAction
An action that dismisses a window associated to a particular scene.
var dismiss: DismissAction
An action that dismisses the current presentation.
struct DismissAction
An action that dismisses a presentation.
struct DismissBehavior
Programmatic window dismissal behaviors.
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
func defaultSize(_:)
Sets a default size for a window.
Sets a default width and height for a window.
Sets a default size for a volumetric window.
Sets the kind of resizability to use for a window.
struct WindowResizability
The resizability of a window.
Specifies how windows derived form this scene should determine their size when zooming.
struct WindowIdealSize
A type which defines the size a window should use when zooming.
Positioning a window
Sets a default position for a window.
struct WindowLevel
The level of a window.
Sets the window level of this scene.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Defines a function used for determining the default placement of windows.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowProxy
The proxy for an open window in the app.
struct DisplayProxy
A type which provides information about display hardware.
Configuring window visibility
struct WindowVisibilityToggle
A specialized button for toggling the visibility of a window.
Sets the default launch behavior for this scene.
Sets the restoration behavior for this scene.
struct SceneLaunchBehavior
The launch behavior for a scene.
struct SceneRestorationBehavior
The restoration behavior for a scene.
Sets the preferred visibility of the non-transient system views overlaying the app.
Configures the visibility of the window toolbar when the window enters full screen mode.
struct WindowToolbarFullScreenVisibility
The visibility of the window toolbar with respect to full screen mode.
Managing window behavior
struct WindowManagerRole
Options for defining how a scene’s windows behave when used within a managed window context, such as full screen mode and Stage Manager.
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
struct WindowInteractionBehavior
Options for enabling and disabling window interaction behaviors.
Configures the dismiss functionality for the window enclosing self.
Configures the full screen functionality for the window enclosing self.
Configures the minimize functionality for the window enclosing self.
Configures the resize functionality for the window enclosing self.
Configures the behavior of dragging a window by its background.
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
Deprecated Types
enum ControlActiveState
The active appearance expected of controls in a window.
Deprecated
See Also
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
https://developer.apple.com/documentation/swiftui/immersive-spaces
Collection
- SwiftUI
- Immersive spaces
API Collection
Immersive spaces
Display unbounded content in a person’s surroundings.
Overview
Use an immersive space in visionOS to present SwiftUI views outside of any containers. You can include any views in a space, although you typically use a RealityView to present RealityKit content.
You can request one of three styles of spaces with the immersionStyle(selection:in:) scene modifier:
-
The
mixedstyle blends your content with passthrough. This enables you to place virtual objects in a person’s surroundings. -
The
fullstyle displays only your content, with passthrough turned off. This enables you to completely control the visual experience, like when you want to transport people to a new world. -
The
progressivestyle completely replaces passthrough in a portion of the display. You might use this style to keep people grounded in the real world while displaying a view into another world.
When you open an immersive space, the system continues to display all of your app’s windows, but hides windows from other apps. The system supports displaying only one space at a time across all apps, so your app can only open a space if one isn’t already open.
Topics
Creating an immersive space
struct ImmersiveSpace
A scene that presents its content in an unbounded space.
struct ImmersiveSpaceContentBuilder
A result builder for composing a collection of immersive space elements.
Sets the style for an immersive space.
protocol ImmersionStyle
The styles that an immersive space can have.
var immersiveSpaceDisplacement: Pose3D
The displacement that the system applies to the immersive space when moving the space away from its default position, in meters.
struct ImmersiveEnvironmentBehavior
The behavior of the system-provided immersive environments when a scene is opened by your app.
Beta
struct ProgressiveImmersionAspectRatio Beta
Opening an immersive space
var openImmersiveSpace: OpenImmersiveSpaceAction
An action that presents an immersive space.
struct OpenImmersiveSpaceAction
Closing the immersive space
var dismissImmersiveSpace: DismissImmersiveSpaceAction
An immersive space dismissal action stored in a view’s environment.
struct DismissImmersiveSpaceAction
An action that dismisses an immersive space.
Hiding upper limbs during immersion
Sets the preferred visibility of the user’s upper limbs, while an ImmersiveSpace scene is presented.
Adjusting content brightness
Sets the content brightness of an immersive space.
struct ImmersiveContentBrightness
The content brightness of an immersive space.
Responding to immersion changes
Performs an action when the immersion state of your app changes.
struct ImmersionChangeContext
A structure that represents a state of immersion of your app.
Adding menu items to an immersive space
Add menu items to open immersive spaces from a media player’s environment picker.
Handling remote immersive spaces
struct RemoteImmersiveSpace
A scene that presents its content in an unbounded space on a remote device.
struct RemoteDeviceIdentifier
An opaque type that identifies a remote device displaying scene content in a RemoteImmersiveSpace.
See Also
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
https://developer.apple.com/documentation/swiftui/documents
Collection
- SwiftUI
- Documents
API Collection
Documents
Enable people to open and manage documents.
Overview
Create a user interface for opening and editing documents using the DocumentGroup scene type.
You initialize the scene with a model that describes the organization of the document’s data, and a view hierarchy that SwiftUI uses to display the document’s contents to the user. You can use either a value type model, which you typically store as a structure, that conforms to the FileDocument protocol, or a reference type model you store in a class instance that conforms to the ReferenceFileDocument protocol. You can also use SwiftData-backed documents using an initializer like init(editing:contentType:editor:prepareDocument:).
SwiftUI supports standard behaviors that users expect from a document-based app, appropriate for each platform, like multiwindow support, open and save panels, drag and drop, and so on. For related design guidance, see Patterns in the Human Interface Guidelines.
Topics
Creating a document
Building a document-based app with SwiftUI
Create, save, and open documents in a multiplatform app.
Building a document-based app using SwiftData
Code along with the WWDC presenter to transform an app with SwiftData.
struct DocumentGroup
A scene that enables support for opening, creating, and saving documents.
Storing document data in a structure instance
protocol FileDocument
A type that you use to serialize documents to and from file.
struct FileDocumentConfiguration
The properties of an open file document.
Storing document data in a class instance
protocol ReferenceFileDocument
A type that you use to serialize reference type documents to and from file.
struct ReferenceFileDocumentConfiguration
The properties of an open reference file document.
var undoManager: UndoManager?
The undo manager used to register a view’s undo operations.
Accessing document configuration
var documentConfiguration: DocumentConfiguration?
The configuration of a document in a DocumentGroup.
struct DocumentConfiguration
Reading and writing documents
struct FileDocumentReadConfiguration
The configuration for reading file contents.
struct FileDocumentWriteConfiguration
The configuration for serializing file contents.
Opening a document programmatically
var newDocument: NewDocumentAction
An action in the environment that presents a new document.
struct NewDocumentAction
An action that presents a new document.
var openDocument: OpenDocumentAction
An action in the environment that presents an existing document.
struct OpenDocumentAction
An action that presents an existing document.
Configuring the document launch experience
struct DocumentGroupLaunchScene
A launch scene for document-based applications.
struct DocumentLaunchView
A view to present when launching document-related user experience.
struct DocumentLaunchGeometryProxy
A proxy for access to the frame of the scene and its title view.
struct DefaultDocumentGroupLaunchActions
The default actions for the document group launch scene and the document launch view.
struct NewDocumentButton
A button that creates and opens new documents.
protocol DocumentBaseBox
A Box that allows setting its Document base not requiring the caller to know the exact types of the box and its base.
Renaming a document
struct RenameButton
A button that triggers a standard rename action.
func renameAction(_:)
Sets a closure to run for the rename action.
var rename: RenameAction?
An action that activates the standard rename interaction.
struct RenameAction
An action that activates a standard rename interaction.
See Also
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
https://developer.apple.com/documentation/swiftui/navigation
Collection
- SwiftUI
- Navigation
API Collection
Navigation
Enable people to move between different parts of your app’s view hierarchy within a scene.
Overview
Use navigation containers to provide structure to your app’s user interface, enabling people to easily move among the parts of your app.
For example, people can move forward and backward through a stack of views using a NavigationStack, or choose which view to display from a tab bar using a TabView.
Configure navigation containers by adding view modifiers like navigationSplitViewStyle(_:) to the container. Use other modifiers on the views inside the container to affect the container’s behavior when showing that view. For example, you can use navigationTitle(_:) on a view to provide a toolbar title to display when showing that view.
Topics
Essentials
Understanding the navigation stack
Learn about the navigation stack, links, and how to manage navigation types in your app’s structure.
Presenting views in columns
Bringing robust navigation structure to your SwiftUI app
Use navigation links, stacks, destinations, and paths to provide a streamlined experience for all platforms, as well as behaviors such as deep linking and state restoration.
Migrating to new navigation types
Improve navigation behavior in your app by replacing navigation views with navigation stacks and navigation split views.
struct NavigationSplitView
A view that presents views in two or three columns, where selections in leading columns control presentations in subsequent columns.
Sets the style for navigation split views within this view.
Sets a fixed, preferred width for the column containing this view.
Sets a flexible, preferred width for the column containing this view.
struct NavigationSplitViewVisibility
The visibility of the leading columns in a navigation split view.
struct NavigationLink
A view that controls a navigation presentation.
Stacking views in one column
struct NavigationStack
A view that displays a root view and enables you to present additional views over the root view.
struct NavigationPath
A type-erased list of data representing the content of a navigation stack.
Associates a destination view with a presented data type for use within a navigation stack.
Associates a destination view with a binding that can be used to push the view onto a NavigationStack.
func navigationDestination<D, C>(item: Binding<Optional<D>>, destination: (D) -> C) -> some View
Associates a destination view with a bound value for use within a navigation stack or navigation split view
Managing column collapse
struct NavigationSplitViewColumn
A view that represents a column in a navigation split view.
Setting titles for navigation content
func navigationTitle(_:)
Configures the view’s title for purposes of navigation, using a string binding.
func navigationSubtitle(_:)
Configures the view’s subtitle for purposes of navigation.
func navigationDocument(_:)
Configures the view’s document for purposes of navigation.
func navigationDocument(_:preview:)
Configuring the navigation bar
Hides the navigation bar back button for the view.
Configures the title display mode for this view.
struct NavigationBarItem
A configuration for a navigation bar that represents a view at the top of a navigation stack.
Configuring the sidebar
var sidebarRowSize: SidebarRowSize
The current size of sidebar rows.
enum SidebarRowSize
The standard sizes of sidebar rows.
Presenting views in tabs
Enhancing your app’s content with tab navigation
Keep your app content front and center while providing quick access to navigation using the tab bar.
struct TabView
A view that switches between multiple child views using interactive user interface elements.
struct Tab
The content for a tab and the tab’s associated tab item in a tab view.
struct TabRole
A value that defines the purpose of the tab.
struct TabSection
A container that you can use to add hierarchy within a tab view.
Sets the style for the tab view within the current environment.
Configuring a tab bar
Adds a custom header to the sidebar of a tab view.
Adds a custom footer to the sidebar of a tab view.
Adds a custom bottom bar to the sidebar of a tab view.
struct AdaptableTabBarPlacement
A placement for tabs in a tab view using the adaptable sidebar style.
var tabBarPlacement: TabBarPlacement?
The current placement of the tab bar.
struct TabBarPlacement
A placement for tabs in a tab view.
var isTabBarShowingSections: Bool
A Boolean value that determines whether a tab view shows the expanded contents of a tab section.
struct TabBarMinimizeBehavior Beta
enum TabViewBottomAccessoryPlacement
A placement of the bottom accessory in a tab view. You can use this to adjust the content of the accessory view based on the placement.
Beta
Configuring a tab
Adds custom actions to a section.
struct TabPlacement
A place that a tab can appear.
struct TabContentBuilder
A result builder that constructs tabs for a tab view that supports programmatic selection. This builder requires that all tabs in the tab view have the same selection type.
protocol TabContent
A type that provides content for programmatically selectable tabs in a tab view.
struct AnyTabContent
Type erased tab content.
Enabling tab customization
Specifies the customizations to apply to the sidebar representation of the tab view.
struct TabViewCustomization
The customizations a person makes to an adaptable sidebar tab view.
struct TabCustomizationBehavior
The customization behavior of customizable tab view content.
Displaying views in multiple panes
struct HSplitView
A layout container that arranges its children in a horizontal line and allows the user to resize them using dividers placed between them.
struct VSplitView
A layout container that arranges its children in a vertical line and allows the user to resize them using dividers placed between them.
Deprecated Types
struct NavigationView
A view for presenting a stack of views that represents a visible path in a navigation hierarchy.
Deprecated
Sets the tab bar item associated with this view.
See Also
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
https://developer.apple.com/documentation/swiftui/modal-presentations
Collection
- SwiftUI
- Modal presentations
API Collection
Modal presentations
Present content in a separate view that offers focused interaction.
Overview
To draw attention to an important, narrowly scoped task, you display a modal presentation, like an alert, popover, sheet, or confirmation dialog.
In SwiftUI, you create a modal presentation using a view modifier that defines how the presentation looks and the condition under which SwiftUI presents it. SwiftUI detects when the condition changes and makes the presentation for you. Because you provide a Binding to the condition that initiates the presentation, SwiftUI can reset the underlying value when the user dismisses the presentation.
For design guidance, see Modality in the Human Interface Guidelines.
Topics
Configuring a dialog
struct DialogSeverity
The severity of an alert or confirmation dialog.
Showing a sheet, cover, or popover
Presents a sheet when a binding to a Boolean value that you provide is true.
Presents a sheet using the given item as a data source for the sheet’s content.
Presents a modal view that covers as much of the screen as possible when binding to a Boolean value you provide is true.
Presents a modal view that covers as much of the screen as possible using the binding you provide as a data source for the sheet’s content.
Presents a popover using the given item as a data source for the popover’s content.
Presents a popover when a given condition is true.
enum PopoverAttachmentAnchor
An attachment anchor for a popover.
Adapting a presentation size
Specifies how to adapt a presentation to horizontally and vertically compact size classes.
Specifies how to adapt a presentation to compact size classes.
struct PresentationAdaptation
Strategies for adapting a presentation to a different size class.
Sets the sizing of the containing presentation.
protocol PresentationSizing
A type that defines the size of the presentation content and how the presentation size adjusts to its content’s size changing.
struct PresentationSizingRoot
A proxy to a view provided to the presentation with a defined presentation size.
struct PresentationSizingContext
Contextual information about a presentation.
Configuring a sheet’s height
Sets the available detents for the enclosing sheet.
Sets the available detents for the enclosing sheet, giving you programmatic control of the currently selected detent.
Configures the behavior of swipe gestures on a presentation.
Sets the visibility of the drag indicator on top of a sheet.
struct PresentationDetent
A type that represents a height where a sheet naturally rests.
protocol CustomPresentationDetent
The definition of a custom detent with a calculated height.
struct PresentationContentInteraction
A behavior that you can use to influence how a presentation responds to swipe gestures.
Styling a sheet and its background
Requests that the presentation have a specific corner radius.
Sets the presentation background of the enclosing sheet using a shape style.
Sets the presentation background of the enclosing sheet to a custom view.
Controls whether people can interact with the view behind a presentation.
struct PresentationBackgroundInteraction
The kinds of interaction available to views behind a presentation.
Presenting an alert
struct AlertScene
A scene that renders itself as a standalone alert dialog.
func alert(_:isPresented:actions:)
Presents an alert when a given condition is true, using a text view for the title.
func alert(_:isPresented:presenting:actions:)
Presents an alert using the given data to produce the alert’s content and a text view as a title.
Presents an alert when an error is present.
func alert(_:isPresented:actions:message:)
Presents an alert with a message when a given condition is true using a text view as a title.
func alert(_:isPresented:presenting:actions:message:)
Presents an alert with a message using the given data to produce the alert’s content and a text view for a title.
Presents an alert with a message when an error is present.
Getting confirmation for an action
func confirmationDialog(_:isPresented:titleVisibility:actions:)
Presents a confirmation dialog when a given condition is true, using a text view for the title.
func confirmationDialog(_:isPresented:titleVisibility:presenting:actions:)
Presents a confirmation dialog using data to produce the dialog’s content and a text view for the title.
func dismissalConfirmationDialog(_:shouldPresent:actions:)
Presents a confirmation dialog when a dismiss action has been triggered.
Showing a confirmation dialog with a message
func confirmationDialog(_:isPresented:titleVisibility:actions:message:)
Presents a confirmation dialog with a message when a given condition is true, using a text view for the title.
func confirmationDialog(_:isPresented:titleVisibility:presenting:actions:message:)
Presents a confirmation dialog with a message using data to produce the dialog’s content and a text view for the message.
func dismissalConfirmationDialog(_:shouldPresent:actions:message:)
Configuring a dialog
Configures the icon used by dialogs within this view.
Configures the icon used by alerts.
Sets the severity for alerts.
Enables user suppression of dialogs and alerts presented within self, with a default suppression message on macOS. Unused on other platforms.
Enables user suppression of an alert with a custom suppression message.
func dialogSuppressionToggle(_:isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a custom suppression message on macOS. Unused on other platforms.
Exporting to file
func fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)
Presents a system interface for exporting a document that’s stored in a value type, like a structure, to a file on disk.
func fileExporter(isPresented:documents:contentType:onCompletion:)
Presents a system interface for exporting a collection of value type documents to files on disk.
func fileExporter(isPresented:document:contentTypes:defaultFilename:onCompletion:onCancellation:)
Presents a system interface for allowing the user to export a FileDocument to a file on disk.
func fileExporter(isPresented:documents:contentTypes:onCompletion:onCancellation:)
Presents a system dialog for allowing the user to export a collection of documents that conform to FileDocument to files on disk.
Presents a system interface allowing the user to export a Transferable item to file on disk.
Presents a system interface allowing the user to export a collection of items to files on disk.
func fileExporterFilenameLabel(_:)
On macOS, configures the fileExporter with a label for the file name field.
Importing from file
Presents a system interface for allowing the user to import multiple files.
Presents a system interface for allowing the user to import an existing file.
Presents a system dialog for allowing the user to import multiple files.
Moving a file
Presents a system interface for allowing the user to move an existing file to a new location.
Presents a system interface for allowing the user to move a collection of existing files to a new location.
Presents a system dialog for allowing the user to move an existing file to a new location.
Presents a system dialog for allowing the user to move a collection of existing files to a new location.
Configuring a file dialog
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
func fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
func fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
struct FileDialogBrowserOptions
The way that file dialogs present the file system.
Presenting an inspector
Inserts an inspector at the applied position in the view hierarchy.
Sets a fixed, preferred width for the inspector containing this view when presented as a trailing column.
Sets a flexible, preferred width for the inspector in a trailing-column presentation.
Dismissing a presentation
var isPresented: Bool
A Boolean value that indicates whether the view associated with this environment is currently presented.
var dismiss: DismissAction
An action that dismisses the current presentation.
struct DismissAction
An action that dismisses a presentation.
Conditionally prevents interactive dismissal of presentations like popovers, sheets, and inspectors.
Deprecated modal presentations
struct Alert
A representation of an alert presentation.
Deprecated
struct ActionSheet
A representation of an action sheet presentation.
See Also
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
https://developer.apple.com/documentation/swiftui/toolbars
Collection
- SwiftUI
- Toolbars
API Collection
Toolbars
Provide immediate access to frequently used commands and controls.
Overview
The system might present toolbars above or below your app’s content, depending on the platform and the context.
Add items to a toolbar by applying the toolbar(content:) view modifier to a view in your app. You can also configure the toolbar using view modifiers. For example, you can set the visibility of a toolbar with the toolbar(_:for:) modifier.
For design guidance, see Toolbars in the Human Interface Guidelines.
Topics
Populating a toolbar
func toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
struct ToolbarItem
A model that represents an item which can be placed in the toolbar or navigation bar.
struct ToolbarItemGroup
A model that represents a group of ToolbarItem s which can be placed in the toolbar or navigation bar.
struct ToolbarItemPlacement
A structure that defines the placement of a toolbar item.
protocol ToolbarContent
Conforming types represent items that can be placed in various locations in a toolbar.
struct ToolbarContentBuilder
Constructs a toolbar item set from multi-expression closures.
struct ToolbarSpacer
A standard space item in toolbars.
Beta
struct DefaultToolbarItem
A toolbar item that represents a system component.
Populating a customizable toolbar
Populates the toolbar or navigation bar with the specified items, allowing for user customization.
protocol CustomizableToolbarContent
Conforming types represent items that can be placed in various locations in a customizable toolbar.
struct ToolbarCustomizationBehavior
The customization behavior of customizable toolbar content.
struct ToolbarCustomizationOptions
Options that influence the default customization behavior of customizable toolbar content.
struct SearchToolbarBehavior
The behavior of a search field in a toolbar.
Removing default items
Remove a toolbar item present by default
struct ToolbarDefaultItemKind
A kind of toolbar item a View adds by default.
Setting toolbar visibility
Specifies the visibility of a bar managed by SwiftUI.
Specifies the preferred visibility of backgrounds on a bar managed by SwiftUI.
struct ToolbarPlacement
The placement of a toolbar.
struct ContentToolbarPlacement
Specifying the role of toolbar content
Configures the semantic role for the content populating the toolbar.
struct ToolbarRole
The purpose of content that populates the toolbar.
Styling a toolbar
func toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
Specifies the preferred color scheme of a bar managed by SwiftUI.
Specifies the preferred foreground style of bars managed by SwiftUI.
Sets the style for the toolbar defined within this scene.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
var toolbarLabelStyle: ToolbarLabelStyle?
The label style to apply to controls within a toolbar.
struct ToolbarLabelStyle
The label style of a toolbar.
struct SpacerSizing
A type which defines how spacers should size themselves.
Configuring the toolbar title display mode
Configures the toolbar title display mode for this view.
struct ToolbarTitleDisplayMode
A type that defines the behavior of title of a toolbar.
Setting the toolbar title menu
Configure the title menu of a toolbar.
struct ToolbarTitleMenu
The title menu of a toolbar.
Creating an ornament
func ornament(visibility:attachmentAnchor:contentAlignment:ornament:)
Presents an ornament.
struct OrnamentAttachmentAnchor
An attachment anchor for an ornament.
See Also
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Enable people to search for text or other content within your app.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
https://developer.apple.com/documentation/swiftui/search
Collection
- SwiftUI
- Search
API Collection
Search
Enable people to search for text or other content within your app.
Overview
To present a search field in your app, create and manage storage for search text and optionally for discrete search terms known as tokens. Then bind the storage to the search field by applying the searchable view modifier to a view in your app.
As people interact with the field, they implicitly modify the underlying storage and, thereby, the search parameters. Your app correspondingly updates other parts of its interface. To enhance the search interaction, you can also:
-
Offer suggestions during search, for both text and tokens.
-
Implement search scopes that help people to narrow the search space.
-
Detect when people activate the search field, and programmatically dismiss the search field using environment values.
For design guidance, see Searching in the Human Interface Guidelines.
Topics
Searching your app’s data model
Adding a search interface to your app
Present an interface that people can use to search for content in your app.
Performing a search operation
Update search results based on search text and optional tokens that you store.
func searchable(text:placement:prompt:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:placement:prompt:token:)
Marks this view as searchable with text and tokens.
func searchable(text:editableTokens:placement:prompt:token:)
struct SearchFieldPlacement
The placement of a search field in a view hierarchy.
Making search suggestions
Suggesting search terms
Provide suggestions to people searching for content in your app.
Configures the search suggestions for this view.
Configures how to display search suggestions within this view.
func searchCompletion(_:)
Associates a fully formed string with the value of this view when used as a search suggestion.
func searchable(text:tokens:suggestedTokens:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions.
struct SearchSuggestionsPlacement
The ways that SwiftUI displays search suggestions.
Limiting search scope
Scoping a search operation
Divide the search space into a few broad categories.
Configures the search scopes for this view.
Configures the search scopes for this view with the specified activation strategy.
struct SearchScopeActivation
The ways that searchable modifiers can show or hide search scopes.
Detecting, activating, and dismissing search
Managing search interface activation
Programmatically detect and dismiss a search field.
var isSearching: Bool
A Boolean value that indicates when the user is searching.
var dismissSearch: DismissSearchAction
An action that ends the current search interaction.
struct DismissSearchAction
An action that can end a search interaction.
func searchable(text:isPresented:placement:prompt:)
Marks this view as searchable with programmatic presentation of the search field.
func searchable(text:tokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text and tokens, as well as programmatic presentation.
func searchable(text:editableTokens:isPresented:placement:prompt:token:)
func searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions, as well as programmatic presentation.
Displaying toolbar content during search
Configures the search toolbar presentation behavior for any searchable modifiers within this view.
struct SearchPresentationToolbarBehavior
A type that defines how the toolbar behaves when presenting search.
Searching for text in a view
Programmatically presents the find and replace interface for text editor views.
Prevents find and replace operations in a text editor.
Prevents replace operations in a text editor.
struct FindContext
The status of the find navigator for views which support text editing.
Beta
See Also
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
https://developer.apple.com/documentation/swiftui/app-extensions
Collection
- SwiftUI
- App extensions
API Collection
App extensions
Extend your app’s basic functionality to other parts of the system, like by adding a Widget.
Overview
Use SwiftUI along with WidgetKit to add widgets to your app.
Widgets provide quick access to relevant content from your app. Define a structure that conforms to the Widget protocol, and declare a view hierarchy for the widget. Configure the views inside the widget as you do other SwiftUI views, using view modifiers, including a few widget-specific modifiers.
For design guidance, see Widgets in the Human Interface Guidelines.
Topics
Creating widgets
Building Widgets Using WidgetKit and SwiftUI
Create widgets to show your app’s content on the Home screen, with custom intents for user-customizable settings.
Creating a widget extension
Display your app’s content in a convenient, informative widget on various devices.
Keeping a widget up to date
Plan your widget’s timeline to show timely, relevant information using dynamic views, and update the timeline when things change.
Making a configurable widget
Give people the option to customize their widgets by adding a custom app intent to your project.
protocol Widget
The configuration and content of a widget to display on the Home screen or in Notification Center.
protocol WidgetBundle
A container used to expose multiple widgets from a single widget extension.
struct LimitedAvailabilityConfiguration
A type-erased widget configuration.
protocol WidgetConfiguration
A type that describes a widget’s content.
struct EmptyWidgetConfiguration
An empty widget configuration.
Composing control widgets
protocol ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
protocol ControlWidgetConfiguration
A type that describes a control widget’s content.
struct EmptyControlWidgetConfiguration
An empty control widget configuration.
struct ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
protocol ControlWidgetTemplate
struct EmptyControlWidgetTemplate
An empty control widget template.
struct ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Labeling a widget
func widgetLabel(_:)
Returns a localized text label that displays additional content outside the accessory family widget’s main SwiftUI view.
Creates a label for displaying additional content outside an accessory family widget’s main SwiftUI view.
Styling a widget group
The view modifier that can be applied to AccessoryWidgetGroup to specify the shape the three content views will be masked with. The value of style is set to .automatic, which is .circular by default.
Controlling the accented group
Adds the view and all of its subviews to the accented group.
Managing placement in the Dynamic Island
Specifies the vertical placement for a view of an expanded Live Activity that appears in the Dynamic Island.
See Also
App structure
Define the entry point and top-level structure of your app.
Declare the user interface groupings that make up the parts of your app.
Display user interface content in a window or a collection of windows.
Display unbounded content in a person’s surroundings.
Enable people to open and manage documents.
Enable people to move between different parts of your app’s view hierarchy within a scene.
Present content in a separate view that offers focused interaction.
Provide immediate access to frequently used commands and controls.
Enable people to search for text or other content within your app.
https://developer.apple.com/documentation/swiftui/model-data
Collection
- SwiftUI
- Model data
API Collection
Model data
Manage the data that your app uses to drive its interface.
Overview
SwiftUI offers a declarative approach to user interface design. As you compose a hierarchy of views, you also indicate data dependencies for the views. When the data changes, either due to an external event or because of an action that the user performs, SwiftUI automatically updates the affected parts of the interface. As a result, the framework automatically performs most of the work that view controllers traditionally do.
The framework provides tools, like state variables and bindings, for connecting your app’s data to the user interface. These tools help you maintain a single source of truth for every piece of data in your app, in part by reducing the amount of glue logic you write. Select the tool that best suits the task you need to perform:
-
Manage transient UI state locally within a view by wrapping value types as
Stateproperties. -
Share a reference to a source of truth, like local state, using the
Bindingproperty wrapper. -
Connect to and observe reference model data in views by applying the
Observable()macro to the model data type. Instantiate an observable model data type directly in a view using aStateproperty. Share the observable model data with other views in the hierarchy without passing a reference using theEnvironmentproperty wrapper.
Leveraging property wrappers
SwiftUI implements many data management types, like State and Binding, as Swift property wrappers. Apply a property wrapper by adding an attribute with the wrapper’s name to a property’s declaration.
@State private var isVisible = true // Declares isVisible as a state variable.
The property gains the behavior that the wrapper specifies. The state and data flow property wrappers in SwiftUI watch for changes in your data, and automatically update affected views as necessary. When you refer directly to the property in your code, you access the wrapped value, which for the isVisible state property in the example above is the stored Boolean.
if isVisible == true { Text("Hello") // Only renders when isVisible is true. }
Alternatively, you can access a property wrapper’s projected value by prefixing the property name with the dollar sign ( $). SwiftUI state and data flow property wrappers project a Binding, which is a two-way connection to the wrapped value, allowing another view to access and mutate a single source of truth.
Toggle("Visible", isOn: $isVisible) // The toggle can update the stored value.
For more information about property wrappers, see Property Wrappers in The Swift Programming Language.
Topics
Creating and sharing view state
Managing user interface state
Encapsulate view-specific data within your app’s view hierarchy to make your views reusable.
struct State
A property wrapper type that can read and write a value managed by SwiftUI.
struct Bindable
A property wrapper type that supports creating bindings to the mutable properties of observable objects.
struct Binding
A property wrapper type that can read and write a value owned by a source of truth.
Creating model data
Managing model data in your app
Create connections between your app’s data model and views.
Migrating from the Observable Object protocol to the Observable macro
Update your existing app to leverage the benefits of Observation in Swift.
@attached(member, names: named(_$observationRegistrar), named(access), named(withMutation), named(shouldNotifyObservers)) @attached(memberAttribute) @attached(extension, conformances: Observable) macro Observable()
Defines and implements conformance of the Observable protocol.
Monitoring data changes in your app
Show changes to data in your app’s user interface by using observable objects.
struct StateObject
A property wrapper type that instantiates an observable object.
struct ObservedObject
A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.
protocol ObservableObject : AnyObject
A type of object with a publisher that emits before the object has changed.
Responding to data changes
func onChange(of:initial:_:)
Adds a modifier for this view that fires an action when a specific value changes.
Adds an action to perform when this view detects data emitted by the given publisher.
Distributing model data throughout your app
Supplies an observable object to a view’s hierarchy.
Supplies an ObservableObject to a view subhierarchy.
struct EnvironmentObject
A property wrapper type for an observable object that a parent or ancestor view supplies.
Managing dynamic data
protocol DynamicProperty
An interface for a stored variable that updates an external property of a view.
See Also
Data and storage
Share data throughout a view hierarchy using the environment.
Indicate configuration preferences from views to their container views.
Store data for use across sessions of your app.
https://developer.apple.com/documentation/swiftui/environment-values
Collection
- SwiftUI
- Environment values
API Collection
Environment values
Share data throughout a view hierarchy using the environment.
Overview
Views in SwiftUI can react to configuration information that they read from the environment using an Environment property wrapper.
A view inherits its environment from its container view, subject to explicit changes from an environment(_:_:) view modifier, or by implicit changes from one of the many modifiers that operate on environment values. As a result, you can configure a entire hierarchy of views by modifying the environment of the group’s container.
You can find many built-in environment values in the EnvironmentValues structure. You can also create a custom EnvironmentValues property by defining a new property in an extension to the environment values structure and applying the Entry() macro to the variable declaration.
Topics
Accessing environment values
struct Environment
A property wrapper that reads a value from a view’s environment.
struct EnvironmentValues
A collection of environment values propagated through a view hierarchy.
Creating custom environment values
macro Entry()
Creates an environment values, transaction, container values, or focused values entry.
protocol EnvironmentKey
A key for accessing values in the environment.
Modifying the environment of a view
Places an observable object in the view’s environment.
Sets the environment value of the specified key path to the given value.
Transforms the environment value of the specified key path with the given function.
Modifying the environment of a scene
Places an observable object in the scene’s environment.
See Also
Data and storage
Manage the data that your app uses to drive its interface.
Indicate configuration preferences from views to their container views.
Store data for use across sessions of your app.
https://developer.apple.com/documentation/swiftui/preferences
Collection
- SwiftUI
- Preferences
API Collection
Preferences
Indicate configuration preferences from views to their container views.
Overview
Whereas you use the environment to configure the subviews of a view, you use preferences to send configuration information from subviews toward their container. However, unlike configuration information that flows down a view hierarchy from one container to many subviews, a single container needs to reconcile potentially conflicting preferences flowing up from its many subviews.
When you use the PreferenceKey protocol to define a custom preference, you indicate how to merge preferences from multiple subviews. You can then set a value for the preference on a view using the preference(key:value:) view modifier. Many built-in modifiers, like navigationTitle(_:), rely on preferences to send configuration information to their container.
Topics
Setting preferences
Sets a value for the given preference.
Applies a transformation to a preference value.
Creating custom preferences
protocol PreferenceKey
A named value produced by a view.
Setting preferences based on geometry
Sets a value for the specified preference key, the value is a function of a geometry value tied to the current coordinate space, allowing readers of the value to convert the geometry to their local coordinates.
Sets a value for the specified preference key, the value is a function of the key’s current value and a geometry value tied to the current coordinate space, allowing readers of the value to convert the geometry to their local coordinates.
Responding to changes in preferences
Adds an action to perform when the specified preference key’s value changes.
Generating backgrounds and overlays from preferences
Reads the specified preference value from the view, using it to produce a second view that is applied as the background of the original view.
Reads the specified preference value from the view, using it to produce a second view that is applied as an overlay to the original view.
See Also
Data and storage
Manage the data that your app uses to drive its interface.
Share data throughout a view hierarchy using the environment.
Store data for use across sessions of your app.
https://developer.apple.com/documentation/swiftui/persistent-storage
Collection
- SwiftUI
- Persistent storage
API Collection
Persistent storage
Store data for use across sessions of your app.
Overview
The operating system provides ways to store data when your app closes, so that when people open your app again later, they can continue working without interruption. The mechanism that you use depends on factors like what and how much you need to store, whether you need serialized or random access to the data, and so on.
You use the same kinds of storage in a SwiftUI app that you use in any other app. For example, you can access files on disk using the FileManager interface. However, SwiftUI also provides conveniences that make it easier to use certain kinds of persistent storage in a declarative environment. For example, you can use FetchRequest and FetchedResults to interact with a Core Data model.
Topics
Saving state across app launches
Restoring Your App’s State with SwiftUI
Provide app continuity for users by preserving their current activities.
The default store used by AppStorage contained within the view.
struct AppStorage
A property wrapper type that reflects a value from UserDefaults and invalidates a view on a change in value in that user default.
struct SceneStorage
A property wrapper type that reads and writes to persisted, per-scene storage.
Accessing Core Data
Loading and Displaying a Large Data Feed
Consume data in the background, and lower memory use by batching imports and preventing duplicate records.
var managedObjectContext: NSManagedObjectContext
struct FetchRequest
A property wrapper type that retrieves entities from a Core Data persistent store.
struct FetchedResults
A collection of results retrieved from a Core Data store.
struct SectionedFetchRequest
A property wrapper type that retrieves entities, grouped into sections, from a Core Data persistent store.
struct SectionedFetchResults
A collection of results retrieved from a Core Data persistent store, grouped into sections.
See Also
Data and storage
Manage the data that your app uses to drive its interface.
Share data throughout a view hierarchy using the environment.
Indicate configuration preferences from views to their container views.
https://developer.apple.com/documentation/swiftui/view-fundamentals
Collection
- SwiftUI
- View fundamentals
API Collection
View fundamentals
Define the visual elements of your app using a hierarchy of views.
Overview
Views are the building blocks that you use to declare your app’s user interface. Each view contains a description of what to display for a given state. Every bit of your app that’s visible to the user derives from the description in a view, and any type that conforms to the View protocol can act as a view in your app.
Compose a custom view by combining built-in views that SwiftUI provides with other custom views that you create in your view’s body computed property. Configure views using the view modifiers that SwiftUI provides, or by defining your own view modifiers using the ViewModifier protocol and the modifier(_:) method.
Topics
Creating a view
Declaring a custom view
Define views and assemble them into a view hierarchy.
protocol View
A type that represents part of your app’s user interface and provides modifiers that you use to configure views.
struct ViewBuilder
A custom parameter attribute that constructs views from closures.
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
Responding to view life cycle updates
Adds an action to perform before this view appears.
Adds an action to perform after this view disappears.
Adds an asynchronous task to perform before this view appears.
Adds a task to perform before this view appears or when a specified value changes.
Managing the view hierarchy
Binds a view’s identity to the given proxy value.
Sets the unique tag value of this view.
Prevents the view from updating its child view when its new value is the same as its old value.
Supporting view types
struct AnyView
A type-erased view.
struct EmptyView
A view that doesn’t contain any content.
struct EquatableView
A view type that compares itself against its previous value and prevents its child updating if its new value is the same as its old value.
struct SubscriptionView
A view that subscribes to a publisher with an action.
struct TupleView
A View created from a swift tuple of View values.
See Also
Views
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
https://developer.apple.com/documentation/swiftui/view-configuration
Collection
- SwiftUI
- View configuration
API Collection
View configuration
Adjust the characteristics of views in a hierarchy.
Overview
SwiftUI enables you to tune the appearance and behavior of views using view modifiers.
Many modifiers apply to specific kinds of views or behaviors, but some apply more generally. For example, you can conditionally hide any view by dynamically setting its opacity, display contextual help when people hover over a view, or request the light or dark appearance for a view.
Topics
Hiding views
Sets the transparency of this view.
Hides this view unconditionally.
Hiding system elements
Hides the labels of any controls contained within this view.
Controls the visibility of labels of any controls contained within this view.
var labelsVisibility: Visibility
The labels visibility set by labelsVisibility(_:).
Sets the menu indicator visibility for controls within this view.
Sets the visibility of the status bar.
Sets the preferred visibility of the non-transient system views overlaying the app.
enum Visibility
The visibility of a UI element, chosen automatically based on the platform, current context, and other factors.
Managing view interaction
Adds a condition that controls whether users can interact with this view.
var isEnabled: Bool
A Boolean value that indicates whether the view associated with this environment allows user interaction.
Sets a tag that you use for tracking interactivity.
Mark the receiver as their content might be invalidated.
Providing contextual help
func help(_:)
Adds help text to a view using a text view that you provide.
Detecting and requesting the light or dark appearance
Sets the preferred color scheme for this presentation.
var colorScheme: ColorScheme
The color scheme of this environment.
enum ColorScheme
The possible color schemes, corresponding to the light and dark appearances.
Getting the color scheme contrast
var colorSchemeContrast: ColorSchemeContrast
The contrast associated with the color scheme of this environment.
enum ColorSchemeContrast
The contrast between the app’s foreground and background colors.
Configuring passthrough
Applies an effect to passthrough video.
struct SurroundingsEffect
Effects that the system can apply to passthrough video.
struct BreakthroughEffect Beta
Redacting private content
Designing your app for the Always On state
Customize your watchOS app’s user interface for continuous display.
Marks the view as containing sensitive, private user data.
Adds a reason to apply a redaction to this view hierarchy.
Removes any reason to apply a redaction to this view hierarchy.
var redactionReasons: RedactionReasons
The current redaction reasons applied to the view hierarchy.
var isSceneCaptured: Bool
The current capture state.
struct RedactionReasons
The reasons to apply a redaction to data displayed on screen.
See Also
Views
Define the visual elements of your app using a hierarchy of views.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
https://developer.apple.com/documentation/swiftui/view-styles
Collection
- SwiftUI
- View styles
API Collection
View styles
Apply built-in and custom appearances and behaviors to different types of views.
Overview
SwiftUI defines built-in styles for certain kinds of views and automatically selects the appropriate style for a particular presentation context. For example, a Label might appear as an icon, a string title, or both, depending on factors like the platform, whether the view appears in a toolbar, and so on.
You can override the automatic style by using one of the style view modifiers. These modifiers typically propagate throughout a container view, so that you can wrap a view hierarchy in a style modifier to affect all the views of the given type within the hierarchy.
Any of the style protocols that define a makeBody(configuration:) method, like ToggleStyle, also enable you to define custom styles. Create a type that conforms to the corresponding style protocol and implement its makeBody(configuration:) method. Then apply the new style using a style view modifier exactly like a built-in style.
Topics
Styling views with Liquid Glass
Applying Liquid Glass to custom views
Configure, combine, and morph views using Liquid Glass effects.
Landmarks: Building an app with Liquid Glass
Enhance your app experience with system-provided and custom Liquid Glass.
Applies the Liquid Glass effect to a view.
Beta
Returns a copy of the structure configured to be interactive.
struct GlassEffectContainer
A view that combines multiple Liquid Glass shapes into a single shape that can morph individual shapes into one another.
struct GlassEffectTransition
A structure that describes changes to apply when a glass effect is added or removed from the view hierarchy.
struct GlassButtonStyle
A button style that applies glass border artwork based on the button’s context.
Styling buttons
func buttonStyle(_:)
Sets the style for buttons within this view to a button style with a custom appearance and standard interaction behavior.
protocol ButtonStyle
A type that applies standard interaction behavior and a custom appearance to all buttons within a view hierarchy.
struct ButtonStyleConfiguration
The properties of a button.
protocol PrimitiveButtonStyle
A type that applies custom interaction behavior and a custom appearance to all buttons within a view hierarchy.
struct PrimitiveButtonStyleConfiguration
Sets the style used for displaying the control (see SignInWithAppleButton.Style).
Styling pickers
Sets the style for pickers within this view.
protocol PickerStyle
A type that specifies the appearance and interaction of all pickers within a view hierarchy.
Sets the style for date pickers within this view.
protocol DatePickerStyle
A type that specifies the appearance and interaction of all date pickers within a view hierarchy.
Styling menus
Sets the style for menus within this view.
protocol MenuStyle
A type that applies standard interaction behavior and a custom appearance to all menus within a view hierarchy.
struct MenuStyleConfiguration
A configuration of a menu.
Styling toggles
Sets the style for toggles in a view hierarchy.
protocol ToggleStyle
The appearance and behavior of a toggle.
struct ToggleStyleConfiguration
The properties of a toggle instance.
Styling indicators
Sets the style for gauges within this view.
protocol GaugeStyle
Defines the implementation of all gauge instances within a view hierarchy.
struct GaugeStyleConfiguration
The properties of a gauge instance.
Sets the style for progress views in this view.
protocol ProgressViewStyle
A type that applies standard interaction behavior to all progress views within a view hierarchy.
struct ProgressViewStyleConfiguration
The properties of a progress view instance.
Styling views that display text
Sets the style for labels within this view.
protocol LabelStyle
A type that applies a custom appearance to all labels within a view.
struct LabelStyleConfiguration
The properties of a label.
Sets the style for text fields within this view.
protocol TextFieldStyle
A specification for the appearance and interaction of a text field.
Sets the style for text editors within this view.
protocol TextEditorStyle
A specification for the appearance and interaction of a text editor.
struct TextEditorStyleConfiguration
The properties of a text editor.
Styling collection views
Sets the style for lists within this view.
protocol ListStyle
A protocol that describes the behavior and appearance of a list.
Sets the style for tables within this view.
protocol TableStyle
A type that applies a custom appearance to all tables within a view.
struct TableStyleConfiguration
The properties of a table.
Sets the style for disclosure groups within this view.
protocol DisclosureGroupStyle
A type that specifies the appearance and interaction of disclosure groups within a view hierarchy.
Styling navigation views
Sets the style for navigation split views within this view.
protocol NavigationSplitViewStyle
A type that specifies the appearance and interaction of navigation split views within a view hierarchy.
Sets the style for the tab view within the current environment.
protocol TabViewStyle
A specification for the appearance and interaction of a tab view.
Styling groups
Sets the style for control groups within this view.
protocol ControlGroupStyle
Defines the implementation of all control groups within a view hierarchy.
struct ControlGroupStyleConfiguration
The properties of a control group.
Sets the style for forms in a view hierarchy.
protocol FormStyle
The appearance and behavior of a form.
struct FormStyleConfiguration
The properties of a form instance.
Sets the style for group boxes within this view.
protocol GroupBoxStyle
A type that specifies the appearance and interaction of all group boxes within a view hierarchy.
struct GroupBoxStyleConfiguration
The properties of a group box instance.
Sets the style for the index view within the current environment.
protocol IndexViewStyle
Defines the implementation of all IndexView instances within a view hierarchy.
Sets a style for labeled content.
protocol LabeledContentStyle
The appearance and behavior of a labeled content instance..
struct LabeledContentStyleConfiguration
The properties of a labeled content instance.
Styling windows from a view inside the window
Sets the style for windows created by interacting with this view.
Sets the style for the toolbar in windows created by interacting with this view.
Adding a glass background on views in visionOS
Fills the view’s background with an automatic glass background effect and container-relative rounded rectangle shape.
Fills the view’s background with an automatic glass background effect and a shape that you specify.
enum GlassBackgroundDisplayMode
The display mode of a glass background.
protocol GlassBackgroundEffect
A specification for the appearance of a glass background.
struct AutomaticGlassBackgroundEffect
The automatic glass background effect.
struct GlassBackgroundEffectConfiguration
A configuration used to build a custom effect.
struct FeatheredGlassBackgroundEffect
The feathered glass background effect.
struct PlateGlassBackgroundEffect
The plate glass background effect.
See Also
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
https://developer.apple.com/documentation/swiftui/animations
Collection
- SwiftUI
- Animations
API Collection
Animations
Create smooth visual updates in response to state changes.
Overview
You tell SwiftUI how to draw your app’s user interface for different states, and then rely on SwiftUI to make interface updates when the state changes.
To avoid abrupt visual transitions when the state changes, add animation in one of the following ways:
-
Animate all of the visual changes for a state change by changing the state inside a call to the
withAnimation(_:_:)global function. -
Add animation to a particular view when a specific value changes by applying the
animation(_:value:)view modifier to the view. -
Animate changes to a
Bindingby using the binding’sanimation(_:)method.
SwiftUI animates the effects that many built-in view modifiers produce, like those that set a scale or opacity value. You can animate other values by making your custom views conform to the Animatable protocol, and telling SwiftUI about the value you want to animate.
When an animated state change results in adding or removing a view to or from the view hierarchy, you can tell SwiftUI how to transition the view into or out of place using built-in transitions that AnyTransition defines, like slide or scale. You can also create custom transitions.
For design guidance, see Motion in the Human Interface Guidelines.
Topics
Adding state-based animation to an action
Returns the result of recomputing the view’s body with the provided animation.
Returns the result of recomputing the view’s body with the provided animation, and runs the completion when all animations are complete.
struct AnimationCompletionCriteria
The criteria that determines when an animation is considered finished.
struct Animation
The way a view changes over time to create a smooth visual transition from one state to another.
Adding state-based animation to a view
func animation(_:)
Applies the given animation to this view when this view changes.
Applies the given animation to this view when the specified value changes.
Applies the given animation to all animatable values within the body closure.
Creating phase-based animation
Controlling the timing and movements of your animations
Build sophisticated animations that you control using phase and keyframe animators.
Animates effects that you apply to a view over a sequence of phases that change continuously.
Animates effects that you apply to a view over a sequence of phases that change based on a trigger.
struct PhaseAnimator
A container that animates its content by automatically cycling through a collection of phases that you provide, each defining a discrete step within an animation.
Creating keyframe-based animation
Loops the given keyframes continuously, updating the view using the modifiers you apply in body.
Plays the given keyframes when the given trigger value changes, updating the view using the modifiers you apply in body.
struct KeyframeAnimator
A container that animates its content with keyframes.
protocol Keyframes
A type that defines changes to a value over time.
struct KeyframeTimeline
A description of how a value changes over time, modeled using keyframes.
struct KeyframeTrack
A sequence of keyframes animating a single property of a root type.
struct KeyframeTrackContentBuilder
The builder that creates keyframe track content from the keyframes that you define within a closure.
struct KeyframesBuilder
A builder that combines keyframe content values into a single value.
protocol KeyframeTrackContent
A group of keyframes that define an interpolation curve of an animatable value.
struct CubicKeyframe
A keyframe that uses a cubic curve to smoothly interpolate between values.
struct LinearKeyframe
A keyframe that uses simple linear interpolation.
struct MoveKeyframe
A keyframe that immediately moves to the given value without interpolating.
struct SpringKeyframe
A keyframe that uses a spring function to interpolate to the given value.
Creating custom animations
protocol CustomAnimation
A type that defines how an animatable value changes over time.
struct AnimationContext
Contextual values that a custom animation can use to manage state and access a view’s environment.
struct AnimationState
A container that stores the state for a custom animation.
protocol AnimationStateKey
A key for accessing animation state values.
struct UnitCurve
A function defined by a two-dimensional curve that maps an input progress in the range [0,1] to an output progress that is also in the range [0,1]. By changing the shape of the curve, the effective speed of an animation or other interpolation can be changed.
struct Spring
A representation of a spring’s motion.
Making data animatable
protocol Animatable
A type that describes how to animate a property of a view.
struct AnimatableValues Beta
struct AnimatablePair
A pair of animatable values, which is itself animatable.
protocol VectorArithmetic
A type that can serve as the animatable data of an animatable type.
struct EmptyAnimatableData
An empty type for animatable data.
Updating a view on a schedule
Updating watchOS apps with timelines
Seamlessly schedule updates to your user interface, even while it’s inactive.
struct TimelineView
A view that updates according to a schedule that you provide.
protocol TimelineSchedule
A type that provides a sequence of dates for use as a schedule.
typealias TimelineViewDefaultContext
Information passed to a timeline view’s content callback.
Synchronizing geometries
Defines a group of views with synchronized geometry using an identifier and namespace that you provide.
struct MatchedGeometryProperties
A set of view properties that may be synchronized between views using the View.matchedGeometryEffect() function.
protocol GeometryEffect
An effect that changes the visual appearance of a view, largely without changing its ancestors or descendants.
struct Namespace
A dynamic property type that allows access to a namespace defined by the persistent identity of the object containing the property (e.g. a view).
Isolates the geometry (e.g. position and size) of the view from its parent view.
Defining transitions
func transition(_:)
Associates a transition with the view.
protocol Transition
A description of view changes to apply when a view is added to and removed from the view hierarchy.
struct TransitionProperties
The properties a Transition can have.
enum TransitionPhase
An indication of which the current stage of a transition.
struct AsymmetricTransition
A composite Transition that uses a different transition for insertion versus removal.
struct AnyTransition
A type-erased transition.
Modifies the view to use a given transition as its method of animating changes to the contents of its views.
var contentTransition: ContentTransition
The current method of animating the contents of views.
var contentTransitionAddsDrawingGroup: Bool
A Boolean value that controls whether views that render content transitions use GPU-accelerated rendering.
struct ContentTransition
A kind of transition that applies to the content within a single view, rather than to the insertion or removal of a view.
struct PlaceholderContentView
A placeholder used to construct an inline modifier, transition, or other helper type.
Sets the navigation transition style for this view.
protocol NavigationTransition
A type that defines the transition to use when navigating to a view.
Identifies this view as the source of a navigation transition, such as a zoom transition.
protocol MatchedTransitionSourceConfiguration
A configuration that defines the appearance of a matched transition source.
struct EmptyMatchedTransitionSourceConfiguration
An unstyled matched transition source configuration.
Moving an animation to another view
Executes a closure with the specified transaction and returns the result.
Executes a closure with the specified transaction key path and value and returns the result.
Applies the given transaction mutation function to all animations used within the view.
Applies the given transaction mutation function to all animations used within the body closure.
struct Transaction
The context of the current state-processing update.
macro Entry()
Creates an environment values, transaction, container values, or focused values entry.
protocol TransactionKey
A key for accessing values in a transaction.
Deprecated types
protocol AnimatableModifier
A modifier that can create another modifier with animation.
Deprecated
See Also
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
https://developer.apple.com/documentation/swiftui/text-input-and-output
Collection
- SwiftUI
- Text input and output
API Collection
Text input and output
Display formatted text and get text input from the user.
Overview
To display read-only text, or read-only text paired with an image, use the built-in Text or Label views, respectively. When you need to collect text input from the user, use an appropriate text input view, like TextField or TextEditor.
You add view modifiers to control the text’s font, selectability, alignment, layout direction, and so on. These modifiers also affect other views that display text, like the labels on controls, even if you don’t define an explicit Text view.
For design guidance, see Typography in the Human Interface Guidelines.
Topics
Displaying text
struct Text
A view that displays one or more lines of read-only text.
struct Label
A standard label for user interface items, consisting of an icon with a title.
Sets the style for labels within this view.
Getting text input
Building rich SwiftUI text experiences
Build an editor for formatted text using SwiftUI text editor views and attributed strings.
struct TextField
A control that displays an editable text interface.
Sets the style for text fields within this view.
struct SecureField
A control into which people securely enter private text.
struct TextEditor
A view that can display and edit long-form text.
Selecting text
Controls whether people can select text within this view.
protocol TextSelectability
A type that describes the ability to select text.
struct TextSelection
Represents a selection of text.
Sets the direction of a selection or cursor relative to a text character.
var textSelectionAffinity: TextSelectionAffinity
A representation of the direction or association of a selection or cursor relative to a text character. This concept becomes much more prominent when dealing with bidirectional text (text that contains both LTR and RTL scripts, like English and Arabic combined).
enum TextSelectionAffinity
struct AttributedTextSelection
Represents a selection of attributed text.
Beta
Setting a font
Applying custom fonts to text
Add and use a font in your app that scales with Dynamic Type.
Sets the default font for text in this view.
Sets the font design of the text in this view.
Sets the font weight of the text in this view.
Sets the font width of the text in this view.
var font: Font?
The default font of this environment.
struct Font
An environment-dependent font.
Adjusting text size
Applies a text scale to text in the view.
func dynamicTypeSize(_:)
Sets the Dynamic Type size within the view to the given value.
var dynamicTypeSize: DynamicTypeSize
The current Dynamic Type size.
enum DynamicTypeSize
A Dynamic Type size, which specifies how large scalable content should be.
struct ScaledMetric
A dynamic property that scales a numeric value.
protocol TextVariantPreference
A protocol for controlling the size variant of text views.
struct FixedTextVariant
The default text variant preference that chooses the largest available variant.
struct SizeDependentTextVariant
The size dependent variant preference allows the text to take the available space into account when choosing the variant to display.
Controlling text style
Applies a bold font weight to the text in this view.
Applies italics to the text in this view.
Applies an underline to the text in this view.
Applies a strikethrough to the text in this view.
Sets a transform for the case of the text contained in this view when displayed.
var textCase: Text.Case?
A stylistic override to transform the case of Text when displayed, using the environment’s locale.
Modifies the fonts of all child views to use the fixed-width variant of the current font, if possible.
Modifies the fonts of all child views to use fixed-width digits, if possible, while leaving other characters proportionally spaced.
protocol AttributedTextFormattingDefinition
A protocol for defining how text can be styled in a certain context, e.g. a TextEditor.
protocol AttributedTextValueConstraint
A protocol for defining a constraint on the value of a certain attribute.
enum AttributedTextFormatting
A namespace for types related to attributed text formatting definitions.
Managing text layout
Sets the truncation mode for lines of text that are too long to fit in the available space.
var truncationMode: Text.TruncationMode
A value that indicates how the layout truncates the last line of text to fit into the available space.
Sets whether text in this view can compress the space between characters when necessary to fit text in a line.
var allowsTightening: Bool
A Boolean value that indicates whether inter-character spacing should tighten to fit the text into the available space.
Sets the minimum amount that text in this view scales down to fit in the available space.
var minimumScaleFactor: CGFloat
The minimum permissible proportion to shrink the font size to fit the text into the available space.
Sets the vertical offset for the text relative to its baseline in this view.
Sets the spacing, or kerning, between characters for the text in this view.
Sets the tracking for the text in this view.
Sets whether this view mirrors its contents horizontally when the layout direction is right-to-left.
enum TextAlignment
An alignment position for text along the horizontal axis.
Rendering text
Creating visual effects with SwiftUI
Add scroll effects, rich color treatments, custom transitions, and advanced effects using shaders and a text renderer.
protocol TextAttribute
A value that you can attach to text views and that text renderers can query.
Returns a new view such that any text views within it will use renderer to draw themselves.
protocol TextRenderer
A value that can replace the default text view rendering behavior.
struct TextProxy
A proxy for a text view that custom text renderers use.
Limiting line count for multiline text
func lineLimit(_:)
Sets to a closed range the number of lines that text can occupy in this view.
Sets a limit for the number of lines text can occupy in this view.
var lineLimit: Int?
The maximum number of lines that text can occupy in a view.
Formatting multiline text
Sets the amount of space between lines of text in this view.
var lineSpacing: CGFloat
The distance in points between the bottom of one line fragment and the top of the next.
Sets the alignment of a text view that contains multiple lines of text.
var multilineTextAlignment: TextAlignment
An environment value that indicates how a text view aligns its lines when the content wraps or contains newlines.
Formatting date and time
enum SystemFormatStyle
A namespace for format styles that implement designs used across Apple’s platformes.
struct TimeDataSource
A source of time related data.
Managing text entry
Sets whether to disable autocorrection for this view.
var autocorrectionDisabled: Bool
A Boolean value that determines whether the view hierarchy has auto-correction enabled.
Sets the keyboard type for this view.
Configures the behavior in which scrollable content interacts with the software keyboard.
func textContentType(_:)
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on macOS.
Sets how often the shift key in the keyboard is automatically enabled.
struct TextInputAutocapitalization
The kind of autocapitalization behavior applied during text input.
Associates a fully formed string with the value of this view when used as a text input suggestion
Configures the text input suggestions for this view.
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on a watchOS device.
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on an iOS or tvOS device.
struct TextInputFormattingControlPlacement
A structure defining the system text formatting controls available on each platform.
Dictating text
Configures the dictation behavior for any search fields configured by the searchable modifier.
struct TextInputDictationActivation
struct TextInputDictationBehavior
Configuring the Writing Tools behavior
Specifies the Writing Tools behavior for text and text input in the environment.
struct WritingToolsBehavior
The Writing Tools editing experience for text and text input.
Specifying text equivalents
func typeSelectEquivalent(_:)
Sets an explicit type select equivalent text in a collection, such as a list or table.
Localizing text
Preparing views for localization
Specify hints and add strings to localize your SwiftUI views.
struct LocalizedStringKey
The key used to look up an entry in a strings file or strings dictionary file.
var locale: Locale
The current locale that views should use.
func typesettingLanguage(_:isEnabled:)
Specifies the language for typesetting.
struct TypesettingLanguage
Defines how typesetting language is determined for text.
Deprecated types
enum ContentSizeCategory
The sizes that you can specify for content.
Deprecated
See Also
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
https://developer.apple.com/documentation/swiftui/images
Collection
- SwiftUI
- Images
API Collection
Images
Add images and symbols to your app’s user interface.
Overview
Display images, including SF Symbols, images that you store in an asset catalog, and images that you store on disk, using an Image view.
For images that take time to retrieve — for example, when you load an image from a network endpoint — load the image asynchronously using AsyncImage. You can instruct that view to display a placeholder during the load operation.
For design guidance, see Images in the Human Interface Guidelines.
Topics
Creating an image
struct Image
A view that displays an image.
Configuring an image
Fitting images into available space
Adjust the size and shape of images in your app’s user interface by applying view modifiers.
Scales images within the view according to one of the relative sizes available including small, medium, and large images sizes.
var imageScale: Image.Scale
The image scale for this environment.
enum Scale
A scale to apply to vector images relative to text.
enum Orientation
The orientation of an image.
enum ResizingMode
The modes that SwiftUI uses to resize an image to fit within its containing view.
Loading images asynchronously
struct AsyncImage
A view that asynchronously loads and displays an image.
enum AsyncImagePhase
The current phase of the asynchronous image loading operation.
Setting a symbol variant
Makes symbols within the view show a particular variant.
var symbolVariants: SymbolVariants
The symbol variant to use in this environment.
struct SymbolVariants
A variant of a symbol.
Managing symbol effects
Returns a new view with a symbol effect added to it.
Returns a new view with its inherited symbol image effects either removed or left unchanged.
struct SymbolEffectTransition
Creates a transition that applies the Appear, Disappear, DrawOn or DrawOff symbol animation to symbol images within the inserted or removed view hierarchy.
Setting symbol rendering modes
Sets the rendering mode for symbol images within this view.
var symbolRenderingMode: SymbolRenderingMode?
The current symbol rendering mode, or nil denoting that the mode is picked automatically using the current image and foreground style as parameters.
struct SymbolRenderingMode
A symbol rendering mode.
struct SymbolColorRenderingMode
A method of filling a layer in a symbol image.
Beta
struct SymbolVariableValueMode
A method of rendering the variable value of a symbol image.
Rendering images from views
class ImageRenderer
An object that creates images from SwiftUI views.
See Also
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
https://developer.apple.com/documentation/swiftui/controls-and-indicators
Collection
- SwiftUI
- Controls and indicators
API Collection
Controls and indicators
Display values and get user selections.
Overview
SwiftUI provides controls that enable user interaction specific to each platform and context. For example, people can initiate events with buttons and links, or choose among a set of discrete values with different kinds of pickers. You can also display information to the user with indicators like progress views and gauges.
Use these built-in controls and indicators when composing custom views, and style them to match the needs of your app’s user interface. For design guidance, see Menus and actions, Selection and input, and Status in the Human Interface Guidelines.
Topics
Creating buttons
struct Button
A control that initiates an action.
func buttonStyle(_:)
Sets the style for buttons within this view to a button style with a custom appearance and standard interaction behavior.
Sets the border shape for buttons in this view.
Sets whether buttons in this view should repeatedly trigger their actions on prolonged interactions.
var buttonRepeatBehavior: ButtonRepeatBehavior
Whether buttons with this associated environment should repeatedly trigger their actions on prolonged interactions.
struct ButtonBorderShape
A shape used to draw a button’s border.
struct ButtonRole
A value that describes the purpose of a button.
struct ButtonRepeatBehavior
The options for controlling the repeatability of button actions.
struct ButtonSizing Beta
Creating special-purpose buttons
struct EditButton
A button that toggles the edit mode environment value.
struct PasteButton
A system button that reads items from the pasteboard and delivers it to a closure.
struct RenameButton
A button that triggers a standard rename action.
Linking to other content
struct Link
A control for navigating to a URL.
struct ShareLink
A view that controls a sharing presentation.
struct SharePreview
A representation of a type to display in a share preview.
struct TextFieldLink
A control that requests text input from the user when pressed.
struct HelpLink
A button with a standard appearance that opens app-specific help documentation.
Getting numeric inputs
struct Slider
A control for selecting a value from a bounded linear range of values.
struct Stepper
A control that performs increment and decrement actions.
struct Toggle
A control that toggles between on and off states.
Sets the style for toggles in a view hierarchy.
Choosing from a set of options
struct Picker
A control for selecting from a set of mutually exclusive values.
Sets the style for pickers within this view.
Sets the style for radio group style pickers within this view to be horizontally positioned with the radio buttons inside the layout.
Sets the default wheel-style picker item height.
var defaultWheelPickerItemHeight: CGFloat
The default height of an item in a wheel-style picker, such as a date picker.
Specifies the selection effect to apply to a palette item.
struct PaletteSelectionEffect
The selection effect to apply to a palette item.
Choosing dates
struct DatePicker
A control for selecting an absolute date.
Sets the style for date pickers within this view.
struct MultiDatePicker
A control for picking multiple dates.
var calendar: Calendar
The current calendar that views should use when handling dates.
var timeZone: TimeZone
The current time zone that views should use when handling dates.
Choosing a color
struct ColorPicker
A control used to select a color from the system color picker UI.
Indicating a value
struct Gauge
A view that shows a value within a range.
Sets the style for gauges within this view.
struct ProgressView
A view that shows the progress toward completion of a task.
Sets the style for progress views in this view.
struct DefaultDateProgressLabel
The default type of the current value label when used by a date-relative progress view.
struct DefaultButtonLabel
The default label to use for a button.
Beta
Indicating missing content
struct ContentUnavailableView
An interface, consisting of a label and additional content, that you display when the content of your app is unavailable to users.
Providing haptic feedback
Plays the specified feedback when the provided trigger value changes.
func sensoryFeedback(trigger:_:)
Plays feedback when returned from the feedback closure after the provided trigger value changes.
Plays the specified feedback when the provided trigger value changes and the condition closure returns true.
struct SensoryFeedback
Represents a type of haptic and/or audio feedback that can be played.
Sizing controls
func controlSize(_:)
Sets the size for controls within this view.
enum ControlSize
The size classes, like regular or small, that you can apply to controls within a view.
See Also
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
https://developer.apple.com/documentation/swiftui/menus-and-commands
Collection
- SwiftUI
- Menus and commands
API Collection
Menus and commands
Provide space-efficient, context-dependent access to commands and controls.
Overview
Use a menu to provide people with easy access to common commands. You can add items to a macOS or iPadOS app’s menu bar using the commands(content:) scene modifier, or create context menus that people reveal near their current task using the contextMenu(menuItems:) view modifier.
Create submenus by nesting Menu instances inside others. Use a Divider view to create a separator between menu elements.
For design guidance, see Menus in the Human Interface Guidelines.
Topics
Building a menu bar
Building and customizing the menu bar with SwiftUI
Provide a seamless, cross-platform user experience by building a native menu bar for iPadOS and macOS.
Creating a menu
Populating SwiftUI menus with adaptive controls
Improve your app by populating menus with controls and organizing your content intuitively.
struct Menu
A control for presenting a menu of actions.
Sets the style for menus within this view.
Creating context menus
Adds a context menu to a view.
Adds a context menu with a custom preview to a view.
Adds an item-based context menu to a view.
Defining commands
Adds commands to the scene.
Removes all commands defined by the modified scene.
Replaces all commands defined by the modified scene with the commands from the builder.
protocol Commands
Conforming types represent a group of related commands that can be exposed to the user via the main menu on macOS and key commands on iOS.
struct CommandMenu
Command menus are stand-alone, top-level containers for controls that perform related, app-specific commands.
struct CommandGroup
Groups of controls that you can add to existing command menus.
struct CommandsBuilder
Constructs command sets from multi-expression closures. Like ViewBuilder, it supports up to ten expressions in the closure body.
struct CommandGroupPlacement
The standard locations that you can place new command groups relative to.
Getting built-in command groups
struct SidebarCommands
A built-in set of commands for manipulating window sidebars.
struct TextEditingCommands
A built-in group of commands for searching, editing, and transforming selections of text.
struct TextFormattingCommands
A built-in set of commands for transforming the styles applied to selections of text.
struct ToolbarCommands
A built-in set of commands for manipulating window toolbars.
struct ImportFromDevicesCommands
A built-in set of commands that enables importing content from nearby devices.
struct InspectorCommands
A built-in set of commands for manipulating inspectors.
struct EmptyCommands
An empty group of commands.
Showing a menu indicator
Sets the menu indicator visibility for controls within this view.
var menuIndicatorVisibility: Visibility
The menu indicator visibility to apply to controls within a view.
Configuring menu dismissal
Tells a menu whether to dismiss after performing an action.
struct MenuActionDismissBehavior
The set of menu dismissal behavior options.
Setting a preferred order
Sets the preferred order of items for menus presented from this view.
var menuOrder: MenuOrder
The preferred order of items for menus presented from this view.
struct MenuOrder
The order in which a menu presents its content.
Deprecated types
struct MenuButton
A button that displays a menu containing a list of choices when pressed.
Deprecated
typealias PullDownButton Deprecated
struct ContextMenu
A container for views that you present as menu items in a context menu.
See Also
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Enhance your views with graphical effects and customized drawings.
https://developer.apple.com/documentation/swiftui/shapes
Collection
- SwiftUI
- Shapes
API Collection
Shapes
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
Overview
Draw shapes like circles and rectangles, as well as custom paths that define shapes of your own design. Apply styles that include environment-aware colors, rich gradients, and material effects to the foreground, background, and outline of your shapes.
If you need the efficiency or flexibility of immediate mode drawing — for example, to create particle effects — use a Canvas view instead.
Topics
Creating rectangular shapes
struct Rectangle
A rectangular shape aligned inside the frame of the view containing it.
struct RoundedRectangle
A rectangular shape with rounded corners, aligned inside the frame of the view containing it.
enum RoundedCornerStyle
Defines the shape of a rounded rectangle’s corners.
struct UnevenRoundedRectangle
A rectangular shape with rounded corners with different values, aligned inside the frame of the view containing it.
struct RectangleCornerRadii
Describes the corner radius values of a rounded rectangle with uneven corners.
Creating circular shapes
struct Circle
A circle centered on the frame of the view containing it.
struct Ellipse
An ellipse aligned inside the frame of the view containing it.
struct Capsule
A capsule shape aligned inside the frame of the view containing it.
Drawing custom shapes
struct Path
The outline of a 2D shape.
Defining shape behavior
protocol ShapeView
A view that provides a shape that you can use for drawing operations.
protocol Shape
A 2D shape that you can use when drawing a view.
struct AnyShape
A type-erased shape value.
enum ShapeRole
Ways of styling a shape.
struct StrokeStyle
The characteristics of a stroke that traces a path.
struct StrokeShapeView
A shape provider that strokes its shape.
struct StrokeBorderShapeView
A shape provider that strokes the border of its shape.
struct FillStyle
A style for rasterizing vector shapes.
struct FillShapeView
A shape provider that fills its shape.
Transforming a shape
struct ScaledShape
A shape with a scale transform applied to it.
struct RotatedShape
A shape with a rotation transform applied to it.
struct OffsetShape
A shape with a translation offset transform applied to it.
struct TransformedShape
A shape with an affine transform applied to it.
Setting a container shape
Sets the container shape to use for any container relative shape within this view.
protocol InsettableShape
A shape type that is able to inset itself to produce another shape.
struct ContainerRelativeShape
A shape that is replaced by an inset version of the current container shape. If no container shape was defined, is replaced by a rectangle.
See Also
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Enhance your views with graphical effects and customized drawings.
https://developer.apple.com/documentation/swiftui/drawing-and-graphics
Collection
- SwiftUI
- Drawing and graphics
API Collection
Drawing and graphics
Enhance your views with graphical effects and customized drawings.
Overview
You create rich, dynamic user interfaces with the built-in views and Shapes that SwiftUI provides. To enhance any view, you can apply many of the graphical effects typically associated with a graphics context, like setting colors, adding masks, and creating composites.
When you need the flexibility of immediate mode drawing in a graphics context, use a Canvas view. This can be particularly helpful when you want to draw an extremely large number of dynamic shapes — for example, to create particle effects.
For design guidance, see Materials and Color in the Human Interface Guidelines.
Topics
Immediate mode drawing
Add Rich Graphics to Your SwiftUI App
Make your apps stand out by adding background materials, vibrancy, custom graphics, and animations.
struct Canvas
A view type that supports immediate mode drawing.
struct GraphicsContext
An immediate mode drawing destination, and its current state.
Setting a color
func tint(_:)
Sets the tint color within this view.
struct Color
A representation of a color that adapts to a given context.
Styling content
Adds a border to this view with the specified style and width.
Sets a view’s foreground elements to use a given style.
Sets the primary and secondary levels of the foreground style in the child view.
Sets the primary, secondary, and tertiary levels of the foreground style.
Sets the specified style to render backgrounds within the view.
var backgroundStyle: AnyShapeStyle?
An optional style that overrides the default system background style when set.
protocol ShapeStyle
A color or pattern to use when rendering a shape.
struct AnyShapeStyle
A type-erased ShapeStyle value.
struct Gradient
A color gradient represented as an array of color stops, each having a parametric location value.
struct MeshGradient
A two-dimensional gradient defined by a 2D grid of positioned colors.
struct AnyGradient
A color gradient.
struct ShadowStyle
A style to use when rendering shadows.
struct Glass
A structure that defines the configuration of the Liquid Glass material.
Beta
Transforming colors
Brightens this view by the specified amount.
Sets the contrast and separation between similar colors in this view.
Inverts the colors in this view.
Adds a color multiplication effect to this view.
Adjusts the color saturation of this view.
Adds a grayscale effect to this view.
Applies a hue rotation effect to this view.
Adds a luminance to alpha effect to this view.
Sets an explicit active appearance for materials in this view.
var materialActiveAppearance: MaterialActiveAppearance
The behavior materials should use for their active state, defaulting to automatic.
struct MaterialActiveAppearance
The behavior for how materials appear active and inactive.
Scaling, rotating, or transforming a view
Scales this view to fill its parent.
Scales this view to fit its parent.
func scaleEffect(_:anchor:)
Scales this view’s rendered output by the given amount in both the horizontal and vertical directions, relative to an anchor point.
Scales this view’s rendered output by the given horizontal and vertical amounts, relative to an anchor point.
Scales this view by the specified horizontal, vertical, and depth factors, relative to an anchor point.
func aspectRatio(_:contentMode:)
Constrains this view’s dimensions to the specified aspect ratio.
Rotates a view’s rendered output in two dimensions around the specified point.
Renders a view’s content as if it’s rotated in three dimensions around the specified axis.
Rotates the view’s content by the specified 3D rotation value.
func rotation3DEffect(_:axis:anchor:)
Rotates the view’s content by an angle about an axis that you specify as a tuple of elements.
Applies an affine transformation to this view’s rendered output.
Applies a 3D transformation to this view’s rendered output.
Applies a projection transformation to this view’s rendered output.
struct ProjectionTransform
enum ContentMode
Constants that define how a view’s content fills the available space.
Masking and clipping
Masks this view using the alpha channel of the given view.
Clips this view to its bounding rectangular frame.
Sets a clipping shape for this view.
Applying blur and shadows
Applies a Gaussian blur to this view.
Adds a shadow to this view.
struct ColorMatrix
A matrix to use in an RGBA color transformation.
Applying effects based on geometry
Applies effects to this view, while providing access to layout information through a geometry proxy.
Applies effects to this view, while providing access to layout information through a 3D geometry proxy.
protocol VisualEffect
Visual Effects change the visual appearance of a view without changing its ancestors or descendents.
struct EmptyVisualEffect
The base visual effect that you apply additional effect to.
Compositing views
Sets the blend mode for compositing this view with overlapping views.
Wraps this view in a compositing group.
Composites this view’s contents into an offscreen image before final display.
enum BlendMode
Modes for compositing a view with overlapping content.
enum ColorRenderingMode
The set of possible working color spaces for color-compositing operations.
protocol CompositorContent Beta
struct CompositorContentBuilder
A result builder for composing a collection of CompositorContent elements.
Measuring a view
struct GeometryReader
A container view that defines its content as a function of its own size and coordinate space.
struct GeometryReader3D
struct GeometryProxy
A proxy for access to the size and coordinate space (for anchor resolution) of the container view.
struct GeometryProxy3D
A proxy for access to the size and coordinate space of the container view.
Assigns a name to the view’s coordinate space, so other code can operate on dimensions like points and sizes relative to the named space.
enum CoordinateSpace
A resolved coordinate space created by the coordinate space protocol.
protocol CoordinateSpaceProtocol
A frame of reference within the layout system.
struct PhysicalMetric
Provides access to a value in points that corresponds to the specified physical measurement.
struct PhysicalMetricsConverter
A physical metrics converter provides conversion between point values and their extent in 3D space, in the form of physical length measurements.
Responding to a geometry change
func onGeometryChange(for:of:action:)
Adds an action to be performed when a value, created from a geometry proxy, changes.
Accessing Metal shaders
Returns a new view that applies shader to self as a filter effect on the color of each pixel.
Returns a new view that applies shader to self as a geometric distortion effect on the location of each pixel.
Returns a new view that applies shader to self as a filter on the raster layer created from self.
struct Shader
A reference to a function in a Metal shader library, along with its bound uniform argument values.
struct ShaderFunction
A reference to a function in a Metal shader library.
struct ShaderLibrary
A Metal shader library.
Accessing geometric constructs
enum Axis
The horizontal or vertical dimension in a 2D coordinate system.
struct Angle
A geometric angle whose value you access in either radians or degrees.
struct UnitPoint
A normalized 2D point in a view’s coordinate space.
struct UnitPoint3D
A normalized 3D point in a view’s coordinate space.
struct Anchor
An opaque value derived from an anchor source and a particular view.
protocol DepthAlignmentID
struct Alignment3D
An alignment in all three axes.
struct GeometryProxyCoordinateSpace3D
A representation of a GeometryProxy3D which can be used for CoordinateSpace3D based conversions.
See Also
Views
Define the visual elements of your app using a hierarchy of views.
Adjust the characteristics of views in a hierarchy.
Apply built-in and custom appearances and behaviors to different types of views.
Create smooth visual updates in response to state changes.
Display formatted text and get text input from the user.
Add images and symbols to your app’s user interface.
Display values and get user selections.
Provide space-efficient, context-dependent access to commands and controls.
Trace and fill built-in and custom shapes with a color, gradient, or other pattern.
https://developer.apple.com/documentation/swiftui/layout-fundamentals
Collection
- SwiftUI
- Layout fundamentals
API Collection
Layout fundamentals
Arrange views inside built-in layout containers like stacks and grids.
Overview
Use layout containers to arrange the elements of your user interface. Stacks and grids update and adjust the positions of the subviews they contain in response to changes in content or interface dimensions. You can nest layout containers inside other layout containers to any depth to achieve complex layout effects.
To finetune the position, alignment, and other elements of a layout that you build with layout container views, see Layout adjustments. To define custom layout containers, see Custom layout. For design guidance, see Layout in the Human Interface Guidelines.
Topics
Choosing a layout
Picking container views for your content
Build flexible user interfaces by using stacks, grids, lists, and forms.
Statically arranging views in one dimension
Building layouts with stack views
Compose complex layouts from primitive container views.
struct HStack
A view that arranges its subviews in a horizontal line.
struct VStack
A view that arranges its subviews in a vertical line.
Dynamically arranging views in one dimension
Grouping data with lazy stack views
Split content into logical sections inside lazy stack views.
Creating performant scrollable stacks
Display large numbers of repeated views efficiently with scroll views, stack views, and lazy stacks.
struct LazyHStack
A view that arranges its children in a line that grows horizontally, creating items only as needed.
struct LazyVStack
A view that arranges its children in a line that grows vertically, creating items only as needed.
struct PinnedScrollableViews
A set of view types that may be pinned to the bounds of a scroll view.
Statically arranging views in two dimensions
struct Grid
A container view that arranges other views in a two dimensional layout.
struct GridRow
A horizontal row in a two dimensional grid container.
Tells a view that acts as a cell in a grid to span the specified number of columns.
Specifies a custom alignment anchor for a view that acts as a grid cell.
Asks grid layouts not to offer the view extra size in the specified axes.
Overrides the default horizontal alignment of the grid column that the view appears in.
Dynamically arranging views in two dimensions
struct LazyHGrid
A container view that arranges its child views in a grid that grows horizontally, creating items only as needed.
struct LazyVGrid
A container view that arranges its child views in a grid that grows vertically, creating items only as needed.
struct GridItem
A description of a row or a column in a lazy grid.
Layering views
Adding a background to your view
Compose a background behind your view and extend it beyond the safe area insets.
struct ZStack
A view that overlays its subviews, aligning them in both axes.
Controls the display order of overlapping views.
Layers the views that you specify behind this view.
Sets the view’s background to a style.
Sets the view’s background to the default background style.
func background(_:in:fillStyle:)
Sets the view’s background to an insettable shape filled with a style.
func background(in:fillStyle:)
Sets the view’s background to an insettable shape filled with the default background style.
Layers the views that you specify in front of this view.
Layers the specified style in front of this view.
Layers a shape that you specify in front of this view.
var backgroundMaterial: Material?
The material underneath the current view.
Sets the container background of the enclosing container using a view.
struct ContainerBackgroundPlacement
The placement of a container background.
Automatically choosing the layout that fits
struct ViewThatFits
A view that adapts to the available space by providing the first child view that fits.
Separators
struct Spacer
A flexible space that expands along the major axis of its containing stack layout, or on both axes if not contained in a stack.
struct Divider
A visual element that can be used to separate other content.
See Also
View layout
Make fine adjustments to alignment, spacing, padding, and other layout parameters.
Place views in custom arrangements and create animated transitions between layout types.
Display a structured, scrollable column of information.
Display selectable, sortable data arranged in rows and columns.
Present views in different kinds of purpose-driven containers, like forms or control groups.
Enable people to scroll to content that doesn’t fit in the current display.
https://developer.apple.com/documentation/swiftui/layout-adjustments
Collection
- SwiftUI
- Layout adjustments
API Collection
Layout adjustments
Make fine adjustments to alignment, spacing, padding, and other layout parameters.
Overview
Layout containers like stacks and grids provide a great starting point for arranging views in your app’s user interface. When you need to make fine adjustments, use layout view modifiers. You can adjust or constrain the size, position, and alignment of a view. You can also add padding around a view, and indicate how the view interacts with system-defined safe areas.
To get started with a basic layout, see Layout fundamentals. For design guidance, see Layout in the Human Interface Guidelines.
Topics
Finetuning a layout
Laying out a simple view
Create a view layout by adjusting the size of views.
Inspecting view layout
Determine the position and extent of a view using Xcode previews or by adding temporary borders.
Adding padding around a view
func padding(_:)
Adds a different padding amount to each edge of this view.
Adds an equal padding amount to specific edges of this view.
func padding3D(_:)
Pads this view using the edge insets you specify.
Adds padding to the specified edges of this view using an amount that’s appropriate for the current scene.
Adds a specified kind of padding to the specified edges of this view using an amount that’s appropriate for the current scene.
struct ScenePadding
The padding used to space a view from its containing scene.
Influencing a view’s size
Positions this view within an invisible frame with the specified size.
Positions this view within an invisible frame with the specified depth.
Positions this view within an invisible frame having the specified size constraints.
Positions this view within an invisible frame having the specified depth constraints.
Positions this view within an invisible frame with a size relative to the nearest container.
Fixes this view at its ideal size.
Fixes this view at its ideal size in the specified dimensions.
Sets the priority by which a parent layout should apportion space to this child.
Adjusting a view’s position
Making fine adjustments to a view’s position
Shift the position of a view by applying the offset or position modifier.
Positions the center of this view at the specified point in its parent’s coordinate space.
Positions the center of this view at the specified coordinates in its parent’s coordinate space.
Offset this view by the horizontal and vertical amount specified in the offset parameter.
Offset this view by the specified horizontal and vertical distances.
Brings a view forward in Z by the provided distance in points.
Aligning views
Aligning views within a stack
Position views inside a stack using alignment guides.
Aligning views across stacks
Create a custom alignment and use it to align views across multiple stacks.
func alignmentGuide(_:computeValue:)
Sets the view’s horizontal alignment.
struct Alignment
An alignment in both axes.
struct HorizontalAlignment
An alignment position along the horizontal axis.
struct VerticalAlignment
An alignment position along the vertical axis.
struct DepthAlignment
An alignment position along the depth axis.
protocol AlignmentID
A type that you use to create custom alignment guides.
struct ViewDimensions
A view’s size and alignment guides in its own coordinate space.
struct ViewDimensions3D
A view’s 3D size and alignment guides in its own coordinate space.
struct SpatialContainer
A layout container that aligns overlapping content in 3D space.
Beta
Setting margins
Configures the content margin for a provided placement.
func contentMargins(_:_:for:)
struct ContentMarginPlacement
The placement of margins.
Staying in the safe areas
Expands the safe area of a view.
func safeAreaInset(edge:alignment:spacing:content:)
Shows the specified content beside the modified view.
func safeAreaPadding(_:)
Adds the provided insets into the safe area of this view.
struct SafeAreaRegions
A set of symbolic safe area regions.
Setting a layout direction
Sets the behavior of this view for different layout directions.
enum LayoutDirectionBehavior
A description of what should happen when the layout direction changes.
var layoutDirection: LayoutDirection
The layout direction associated with the current environment.
enum LayoutDirection
A direction in which SwiftUI can lay out content.
struct LayoutRotationUnaryLayout Beta
Reacting to interface characteristics
var isLuminanceReduced: Bool
A Boolean value that indicates whether the display or environment currently requires reduced luminance.
var displayScale: CGFloat
The display scale of this environment.
var pixelLength: CGFloat
The size of a pixel on the screen.
var horizontalSizeClass: UserInterfaceSizeClass?
The horizontal size class of this environment.
var verticalSizeClass: UserInterfaceSizeClass?
The vertical size class of this environment.
enum UserInterfaceSizeClass
A set of values that indicate the visual size available to the view.
Accessing edges, regions, and layouts
enum Edge
An enumeration to indicate one edge of a rectangle.
enum Edge3D
An edge or face of a 3D volume.
enum HorizontalEdge
An edge on the horizontal axis.
enum VerticalEdge
An edge on the vertical axis.
struct EdgeInsets
The inset distances for the sides of a rectangle.
struct EdgeInsets3D
The inset distances for the faces of a 3D volume.
See Also
View layout
Arrange views inside built-in layout containers like stacks and grids.
Place views in custom arrangements and create animated transitions between layout types.
Display a structured, scrollable column of information.
Display selectable, sortable data arranged in rows and columns.
Present views in different kinds of purpose-driven containers, like forms or control groups.
Enable people to scroll to content that doesn’t fit in the current display.
https://developer.apple.com/documentation/swiftui/custom-layout
Collection
- SwiftUI
- Custom layout
API Collection
Custom layout
Place views in custom arrangements and create animated transitions between layout types.
Overview
You can create complex view layouts using the built-in layout containers and layout view modifiers that SwiftUI provides. However, if you need behavior that you can’t achieve with the built-in layout tools, create a custom layout container type using the Layout protocol. A container that you define asks for the sizes of all its subviews, and then indicates where to place the subviews within its own bounds.
You can also create animated transitions among layout types that conform to the Layout procotol, including both built-in and custom layouts.
For design guidance, see Layout in the Human Interface Guidelines.
Topics
Creating a custom layout container
Composing custom layouts with SwiftUI
Arrange views in your app’s interface using layout tools that SwiftUI provides.
protocol Layout
A type that defines the geometry of a collection of views.
struct LayoutSubview
A proxy that represents one subview of a layout.
struct LayoutSubviews
A collection of proxy values that represent the subviews of a layout view.
Configuring a custom layout
struct LayoutProperties
Layout-specific properties of a layout container.
struct ProposedViewSize
A proposal for the size of a view.
struct ViewSpacing
A collection of the geometric spacing preferences of a view.
Associating values with views in a custom layout
Associates a value with a custom layout property.
protocol LayoutValueKey
A key for accessing a layout value of a layout container’s subviews.
Transitioning between layout types
struct AnyLayout
A type-erased instance of the layout protocol.
struct HStackLayout
A horizontal container that you can use in conditional layouts.
struct VStackLayout
A vertical container that you can use in conditional layouts.
struct ZStackLayout
An overlaying container that you can use in conditional layouts.
struct GridLayout
A grid that you can use in conditional layouts.
See Also
View layout
Arrange views inside built-in layout containers like stacks and grids.
Make fine adjustments to alignment, spacing, padding, and other layout parameters.
Display a structured, scrollable column of information.
Display selectable, sortable data arranged in rows and columns.
Present views in different kinds of purpose-driven containers, like forms or control groups.
Enable people to scroll to content that doesn’t fit in the current display.
https://developer.apple.com/documentation/swiftui/lists
Collection
- SwiftUI
- Lists
API Collection
Lists
Display a structured, scrollable column of information.
Overview
Use a list to display a one-dimensional vertical collection of views.
The list is a complex container type that automatically provides scrolling when it grows too large for the current display. You build a list by providing it with individual views for the rows in the list, or by using a ForEach to enumerate a group of rows. You can also mix these strategies, blending any number of individual views and ForEach constructs.
Use view modifiers to configure the appearance and behavior of a list and its rows, headers, sections, and separators. For example, you can apply a style to the list, add swipe gestures to individual rows, or make the list refreshable with a pull-down gesture. You can also use the configuration associated with Scroll views to control the list’s implicit scrolling behavior.
For design guidance, see Lists and tables in the Human Interface Guidelines.
Topics
Creating a list
Displaying data in lists
Visualize collections of data with platform-appropriate appearance.
struct List
A container that presents rows of data arranged in a single column, optionally providing the ability to select one or more members.
Sets the style for lists within this view.
Disclosing information progressively
struct OutlineGroup
A structure that computes views and disclosure groups on demand from an underlying collection of tree-structured, identified data.
struct DisclosureGroup
A view that shows or hides another content view, based on the state of a disclosure control.
Sets the style for disclosure groups within this view.
Configuring rows
Applies an inset to the rows in a list.
Requests that the containing list row use the provided hover effect.
Requests that the containing list row have its hover effect disabled.
func listItemTint(_:)
Sets a fixed tint color for content in a list.
struct ListItemTint
A tint effect configuration that you can apply to content in a list.
var defaultMinListRowHeight: CGFloat
The default minimum height of a row in a list.
Configuring separators
Sets the tint color associated with a row.
Sets the tint color associated with a section.
Sets the display mode for the separator associated with this specific row.
Sets whether to hide the separator associated with a list section.
Configuring headers
Sets the header prominence for this view.
var headerProminence: Prominence
The prominence to apply to section headers within a view.
enum Prominence
A type indicating the prominence of a view hierarchy.
var defaultMinListHeaderHeight: CGFloat?
The default minimum height of a header in a list.
Configuring spacing
Sets the vertical spacing between two adjacent rows in a List.
func listSectionSpacing(_:)
Sets the spacing between adjacent sections in a List to a custom value.
struct ListSectionSpacing
The spacing options between two adjacent sections in a list.
Configuring backgrounds
Places a custom background view behind a list row item.
Overrides whether lists and tables in this view have alternating row backgrounds.
struct AlternatingRowBackgroundBehavior
The styling of views with respect to alternating row backgrounds.
var backgroundProminence: BackgroundProminence
The prominence of the background underneath views associated with this environment.
struct BackgroundProminence
The prominence of backgrounds underneath other views.
Displaying a badge on a list item
func badge(_:)
Generates a badge for the view from an integer value.
Specifies the prominence of badges created by this view.
var badgeProminence: BadgeProminence
The prominence to apply to badges associated with this environment.
struct BadgeProminence
The visual prominence of a badge.
Configuring interaction
Adds custom swipe actions to a row in a list.
Adds a condition that controls whether users can select this view.
Refreshing a list’s content
Marks this view as refreshable.
var refresh: RefreshAction?
A refresh action stored in a view’s environment.
struct RefreshAction
An action that initiates a refresh operation.
Editing a list
Adds a condition for whether the view’s view hierarchy is movable.
Adds a condition for whether the view’s view hierarchy is deletable.
An indication of whether the user can edit the contents of a view associated with this environment.
enum EditMode
A mode that indicates whether the user can edit a view’s content.
struct EditActions
A set of edit actions on a collection of data that a view can offer to a user.
struct EditableCollectionContent
An opaque wrapper view that adds editing capabilities to a row in a list.
struct IndexedIdentifierCollection
A collection wrapper that iterates over the indices and identifiers of a collection together.
See Also
View layout
Arrange views inside built-in layout containers like stacks and grids.
Make fine adjustments to alignment, spacing, padding, and other layout parameters.
Place views in custom arrangements and create animated transitions between layout types.
Display selectable, sortable data arranged in rows and columns.
Present views in different kinds of purpose-driven containers, like forms or control groups.
Enable people to scroll to content that doesn’t fit in the current display.
https://developer.apple.com/documentation/swiftui/tables
Collection
- SwiftUI
- Tables
API Collection
Tables
Display selectable, sortable data arranged in rows and columns.
Overview
Use a table to display multiple values across a collection of elements. Each element in the collection appears in a different row of the table, while each value for a given element appears in a different column. Narrow displays may adapt to show only the first column of the table.
When you create a table, you provide a collection of elements, and then tell the table how to find the needed value for each column. In simple cases, SwiftUI infers the element for each row, but you can also specify the row elements explicitly in more complex scenarios. With a small amount of additional configuration, you can also make the items in the table selectable, and the columns sortable.
Like a List, a table includes implicit vertical scrolling that you can configure using the view modifiers described in Scroll views. For design guidance, see Lists and tables in the Human Interface Guidelines.
Topics
Creating a table
Building a Great Mac App with SwiftUI
Create engaging SwiftUI Mac apps by incorporating side bars, tables, toolbars, and several other popular user interface elements.
struct Table
A container that presents rows of data arranged in one or more columns, optionally providing the ability to select one or more members.
Sets the style for tables within this view.
Creating columns
struct TableColumn
A column that displays a view for each row in a table.
protocol TableColumnContent
A type used to represent columns within a table.
struct TableColumnAlignment
Describes the alignment of the content of a table column.
struct TableColumnBuilder
A result builder that creates table column content from closures.
struct TableColumnForEach
A structure that computes columns on demand from an underlying collection of identified data.
Customizing columns
Controls the visibility of a Table’s column header views.
struct TableColumnCustomization
A representation of the state of the columns in a table.
struct TableColumnCustomizationBehavior
A set of customization behaviors of a column that a table can offer to a user.
Creating rows
struct TableRow
A row that represents a data value in a table.
protocol TableRowContent
A type used to represent table rows.
struct TableHeaderRowContent
A table row that displays a single view instead of columned content.
struct TupleTableRowContent
A type of table column content that creates table rows created from a Swift tuple of table rows.
struct TableForEachContent
A type of table row content that creates table rows created by iterating over a collection.
struct EmptyTableRowContent
A table row content that doesn’t produce any rows.
protocol DynamicTableRowContent
A type of table row content that generates table rows from an underlying collection of data.
struct TableRowBuilder
A result builder that creates table row content from closures.
Adding progressive disclosure
struct DisclosureTableRow
A kind of table row that shows or hides additional rows based on the state of a disclosure control.
struct TableOutlineGroupContent
An opaque table row type created by a table’s hierarchical initializers.
See Also
View layout
Arrange views inside built-in layout containers like stacks and grids.
Make fine adjustments to alignment, spacing, padding, and other layout parameters.
Place views in custom arrangements and create animated transitions between layout types.
Display a structured, scrollable column of information.
Present views in different kinds of purpose-driven containers, like forms or control groups.
Enable people to scroll to content that doesn’t fit in the current display.
https://developer.apple.com/documentation/swiftui/view-groupings
Collection
- SwiftUI
- View groupings
API Collection
View groupings
Present views in different kinds of purpose-driven containers, like forms or control groups.
Overview
You can create groups of views that serve different purposes.
For example, a Group construct treats the specified views as a unit without imposing any additional layout or appearance characteristics. A Form presents a group of elements with a platform-specific appearance that’s suitable for gathering input from people.
For design guidance, see Layout in the Human Interface Guidelines.
Topics
Grouping views into a container
Creating custom container views
Access individual subviews to compose flexible container views.
struct Group
A type that collects multiple instances of a content type — like views, scenes, or commands — into a single unit.
struct GroupElementsOfContent
Transforms the subviews of a given view into a resulting content view.
struct GroupSectionsOfContent
Transforms the sections of a given view into a resulting content view.
Organizing views into sections
struct Section
A container view that you can use to add hierarchy within certain views.
struct SectionCollection
An opaque collection representing the sections of view.
struct SectionConfiguration
Specifies the contents of a section.
Iterating over dynamic data
struct ForEach
A structure that computes views on demand from an underlying collection of identified data.
struct ForEachSectionCollection
A collection which allows a view to be treated as a collection of its sections in a for each loop.
struct ForEachSubviewCollection
A collection which allows a view to be treated as a collection of its subviews in a for each loop.
protocol DynamicViewContent
A type of view that generates views from an underlying collection of data.
Accessing a container’s subviews
struct Subview
An opaque value representing a subview of another view.
struct SubviewsCollection
An opaque collection representing the subviews of view.
struct SubviewsCollectionSlice
A slice of a SubviewsCollection.
Sets a particular container value of a view.
struct ContainerValues
A collection of container values associated with a given view.
protocol ContainerValueKey
A key for accessing container values.
Grouping views into a box
struct GroupBox
A stylized view, with an optional label, that visually collects a logical grouping of content.
Sets the style for group boxes within this view.
Grouping inputs
struct Form
A container for grouping controls used for data entry, such as in settings or inspectors.
Sets the style for forms in a view hierarchy.
struct LabeledContent
A container for attaching a label to a value-bearing view.
Sets a style for labeled content.
Presenting a group of controls
struct ControlGroup
A container view that displays semantically-related controls in a visually-appropriate manner for the context
Sets the style for control groups within this view.
See Also
View layout
Arrange views inside built-in layout containers like stacks and grids.
Make fine adjustments to alignment, spacing, padding, and other layout parameters.
Place views in custom arrangements and create animated transitions between layout types.
Display a structured, scrollable column of information.
Display selectable, sortable data arranged in rows and columns.
Enable people to scroll to content that doesn’t fit in the current display.
https://developer.apple.com/documentation/swiftui/scroll-views
Collection
- SwiftUI
- Scroll views
API Collection
Scroll views
Enable people to scroll to content that doesn’t fit in the current display.
Overview
When the content of a view doesn’t fit in the display, you can wrap the view in a ScrollView to enable people to scroll on one or more axes. Configure the scroll view using view modifiers. For example, you can set the visibility of the scroll indicators or the availability of scrolling in a given dimension.
You can put any view type in a scroll view, but you most often use a scroll view for a layout container with too many elements to fit in the display. For some container views that you put in a scroll view, like lazy stacks, the container doesn’t load views until they are visible or almost visible. For others, like regular stacks and grids, the container loads the content all at once, regardless of the state of scrolling.
Lists and Tables implicitly include a scroll view, so you don’t need to add scrolling to those container types. However, you can configure their implicit scroll views with the same view modifiers that apply to explicit scroll views.
For design guidance, see Scroll views in the Human Interface Guidelines.
Topics
Creating a scroll view
struct ScrollView
A scrollable view.
struct ScrollViewReader
A view that provides programmatic scrolling, by working with a proxy to scroll to known child views.
struct ScrollViewProxy
A proxy value that supports programmatic scrolling of the scrollable views within a view hierarchy.
Managing scroll position
Associates a binding to a scroll position with a scroll view within this view.
Associates a binding to be updated when a scroll view within this view scrolls.
Associates an anchor to control which part of the scroll view’s content should be rendered by default.
Associates an anchor to control the position of a scroll view in a particular circumstance.
struct ScrollAnchorRole
A type defining the role of a scroll anchor.
struct ScrollPosition
A type that defines the semantic position of where a scroll view is scrolled within its content.
Defining scroll targets
Sets the scroll behavior of views scrollable in the provided axes.
Configures the outermost layout as a scroll target layout.
struct ScrollTarget
A type defining the target in which a scroll view should try and scroll to.
protocol ScrollTargetBehavior
A type that defines the scroll behavior of a scrollable view.
struct ScrollTargetBehaviorContext
The context in which a scroll target behavior updates its scroll target.
struct PagingScrollTargetBehavior
The scroll behavior that aligns scroll targets to container-based geometry.
struct ViewAlignedScrollTargetBehavior
The scroll behavior that aligns scroll targets to view-based geometry.
struct AnyScrollTargetBehavior
A type-erased scroll target behavior.
struct ScrollTargetBehaviorProperties
Properties influencing the scroll view a scroll target behavior applies to.
struct ScrollTargetBehaviorPropertiesContext
The context in which a scroll target behavior can decide its properties.
Animating scroll transitions
Applies the given transition, animating between the phases of the transition as this view appears and disappears within the visible region of the containing scroll view.
enum ScrollTransitionPhase
The phases that a view transitions between when it scrolls among other views.
struct ScrollTransitionConfiguration
The configuration of a scroll transition that controls how a transition is applied as a view is scrolled through the visible region of a containing scroll view or other container.
Responding to scroll view changes
Adds an action to be performed when a value, created from a scroll geometry, changes.
Adds an action to be called with information about what views would be considered visible.
Adds an action to be called when the view crosses the threshold to be considered on/off screen.
func onScrollPhaseChange(_:)
Adds an action to perform when the scroll phase of the first scroll view in the hierarchy changes.
struct ScrollGeometry
A type that defines the geometry of a scroll view.
enum ScrollPhase
A type that describes the state of a scroll gesture of a scrollable view like a scroll view.
struct ScrollPhaseChangeContext
A type that provides you with more content when the phase of a scroll view changes.
Showing scroll indicators
Flashes the scroll indicators of a scrollable view when it appears.
Flashes the scroll indicators of scrollable views when a value changes.
Sets the visibility of scroll indicators within this view.
var horizontalScrollIndicatorVisibility: ScrollIndicatorVisibility
The visibility to apply to scroll indicators of any horizontally scrollable content.
var verticalScrollIndicatorVisibility: ScrollIndicatorVisibility
The visiblity to apply to scroll indicators of any vertically scrollable content.
struct ScrollIndicatorVisibility
The visibility of scroll indicators of a UI element.
Managing content visibility
Specifies the visibility of the background for scrollable views within this view.
Sets whether a scroll view clips its content to its bounds.
struct ScrollContentOffsetAdjustmentBehavior
A type that defines the different kinds of content offset adjusting behaviors a scroll view can have.
Disabling scrolling
Disables or enables scrolling in scrollable views.
var isScrollEnabled: Bool
A Boolean value that indicates whether any scroll views associated with this environment allow scrolling to occur.
Configuring scroll bounce behavior
Configures the bounce behavior of scrollable views along the specified axis.
var horizontalScrollBounceBehavior: ScrollBounceBehavior
The scroll bounce mode for the horizontal axis of scrollable views.
var verticalScrollBounceBehavior: ScrollBounceBehavior
The scroll bounce mode for the vertical axis of scrollable views.
struct ScrollBounceBehavior
The ways that a scrollable view can bounce when it reaches the end of its content.
Configuring scroll edge effects
Configures the scroll edge effect style for scroll views within this hierarchy.
Beta
Disables any scroll edge effects for scroll views within this hierarchy.
struct ScrollEdgeEffectStyle
A structure that defines the style of pocket a scroll view will have.
func safeAreaBar(edge:alignment:spacing:content:)
Renders the provided content appropriately to be displayed as a custom bar.
Interacting with a software keyboard
Configures the behavior in which scrollable content interacts with the software keyboard.
var scrollDismissesKeyboardMode: ScrollDismissesKeyboardMode
The way that scrollable content interacts with the software keyboard.
struct ScrollDismissesKeyboardMode
The ways that scrollable content can interact with the software keyboard.
Managing scrolling for different inputs
Enables or disables scrolling in scrollable views when using particular inputs.
struct ScrollInputKind
Inputs used to scroll views.
struct ScrollInputBehavior
A type that defines whether input should scroll a view.
See Also
View layout
Arrange views inside built-in layout containers like stacks and grids.
Make fine adjustments to alignment, spacing, padding, and other layout parameters.
Place views in custom arrangements and create animated transitions between layout types.
Display a structured, scrollable column of information.
Display selectable, sortable data arranged in rows and columns.
Present views in different kinds of purpose-driven containers, like forms or control groups.
https://developer.apple.com/documentation/swiftui/gestures
Collection
- SwiftUI
- Gestures
API Collection
Gestures
Define interactions from taps, clicks, and swipes to fine-grained gestures.
Overview
Respond to gestures by adding gesture modifiers to your views. You can listen for taps, drags, pinches, and other standard gestures.
You can also compose custom gestures from individual gestures using the simultaneously(with:), sequenced(before:), or exclusively(before:) modifiers, or combine gestures with keyboard modifiers using the modifiers(_:) modifier.
For design guidance, see Gestures in the Human Interface Guidelines.
Topics
Essentials
Adding interactivity with gestures
Use gesture modifiers to add interactivity to your app.
Recognizing tap gestures
Adds an action to perform when this view recognizes a tap gesture.
func onTapGesture(count:coordinateSpace:perform:)
Adds an action to perform when this view recognizes a tap gesture, and provides the action with the location of the interaction.
struct TapGesture
A gesture that recognizes one or more taps.
struct SpatialTapGesture
A gesture that recognizes one or more taps and reports their location.
Recognizing long press gestures
Adds an action to perform when this view recognizes a long press gesture.
Adds an action to perform when this view recognizes a remote long touch gesture. A long touch gesture is when the finger is on the remote touch surface without actually pressing.
struct LongPressGesture
A gesture that succeeds when the user performs a long press.
Recognizing spatial events
struct SpatialEventGesture
A gesture that provides information about ongoing spatial events like clicks and touches.
struct SpatialEventCollection
A collection of spatial input events that target a specific view.
enum Chirality
The chirality, or handedness, of a pose.
Recognizing gestures that change over time
func gesture(_:)
Attaches an NSGestureRecognizerRepresentable to the view.
Beta
Attaches a gesture to the view with a lower precedence than gestures defined by the view.
struct DragGesture
A dragging motion that invokes an action as the drag-event sequence changes.
struct WindowDragGesture
A gesture that recognizes the motion of and handles dragging a window.
struct MagnifyGesture
A gesture that recognizes a magnification motion and tracks the amount of magnification.
struct RotateGesture
A gesture that recognizes a rotation motion and tracks the angle of the rotation.
struct RotateGesture3D
A gesture that recognizes 3D rotation motion and tracks the angle and axis of the rotation.
struct GestureMask
Options that control how adding a gesture to a view affects other gestures recognized by the view and its subviews.
Recognizing Apple Pencil gestures
Adds an action to perform after the user double-taps their Apple Pencil.
Adds an action to perform when the user squeezes their Apple Pencil.
var preferredPencilDoubleTapAction: PencilPreferredAction
The action that the user prefers to perform after double-tapping their Apple Pencil, as selected in the Settings app.
var preferredPencilSqueezeAction: PencilPreferredAction
The action that the user prefers to perform when squeezing their Apple Pencil, as selected in the Settings app.
struct PencilPreferredAction
An action that the user prefers to perform after double-tapping their Apple Pencil.
struct PencilDoubleTapGestureValue
Describes the value of an Apple Pencil double-tap gesture.
struct PencilSqueezeGestureValue
Describes the value of an Apple Pencil squeeze gesture.
enum PencilSqueezeGesturePhase
Describes the phase and value of an Apple Pencil squeeze gesture.
struct PencilHoverPose
A value describing the location and distance of an Apple Pencil hovering in the area above a view’s bounds.
Combining gestures
Composing SwiftUI gestures
Combine gestures to create complex interactions.
Attaches a gesture to the view to process simultaneously with gestures defined by the view.
struct SequenceGesture
A gesture that’s a sequence of two gestures.
struct SimultaneousGesture
A gesture containing two gestures that can happen at the same time with neither of them preceding the other.
struct ExclusiveGesture
A gesture that consists of two gestures where only one of them can succeed.
Defining custom gestures
Attaches a gesture to the view with a higher precedence than gestures defined by the view.
Assigns a hand gesture shortcut to the modified control.
Sets the screen edge from which you want your gesture to take precedence over the system gesture.
protocol Gesture
An instance that matches a sequence of events to a gesture, and returns a stream of values for each of its states.
struct AnyGesture
A type-erased gesture.
struct HandActivationBehavior
An activation behavior specific to hand-driven input.
struct HandGestureShortcut
Hand gesture shortcuts describe finger and wrist movements that the user can perform in order to activate a button or toggle.
Managing gesture state
struct GestureState
A property wrapper type that updates a property while the user performs a gesture and resets the property
A gesture that updates the state provided by a gesture’s updating callback.
Handling activation events
Configures whether gestures in this view hierarchy can handle events that activate the containing window.
Deprecated gestures
struct MagnificationGesture
Deprecated
struct RotationGesture
See Also
Event handling
Respond to input from a hardware device, like a keyboard or a Touch Bar.
Enable people to move or duplicate items by issuing Copy and Paste commands.
Enable people to move or duplicate items by dragging them from one location to another.
Identify and control which visible object responds to user interaction.
React to system events, like opening a URL.
https://developer.apple.com/documentation/swiftui/input-events
Collection
- SwiftUI
- Input events
API Collection
Input events
Respond to input from a hardware device, like a keyboard or a Touch Bar.
Overview
SwiftUI provides view modifiers that enable your app to listen for and react to various kinds of user input. For example, you can create keyboard shortcuts, respond to a form submission, or take input from the digital crown of an Apple Watch.
For design guidance, see Inputs in the Human Interface Guidelines.
Topics
Responding to keyboard input
Performs an action if the user presses a key on a hardware keyboard while the view has focus.
Performs an action if the user presses any key on a hardware keyboard while the view has focus.
Performs an action if the user presses one or more keys on a hardware keyboard while the view has focus.
struct KeyPress
Creating keyboard shortcuts
func keyboardShortcut(_:)
Assigns a keyboard shortcut to the modified control.
Defines a keyboard shortcut and assigns it to the modified control.
var keyboardShortcut: KeyboardShortcut?
The keyboard shortcut that buttons in this environment will be triggered with.
struct KeyboardShortcut
Keyboard shortcuts describe combinations of keys on a keyboard that the user can press in order to activate a button or toggle.
struct KeyEquivalent
Key equivalents consist of a letter, punctuation, or function key that can be combined with an optional set of modifier keys to specify a keyboard shortcut.
struct EventModifiers
A set of key modifiers that you can add to a gesture.
Responding to modifier keys
Performs an action whenever the user presses or releases a hardware modifier key.
Builds a view to use in place of the modified view when the user presses the modifier key(s) indicated by the given set.
Responding to hover events
Adds an action to perform when the user moves the pointer over or away from the view’s frame.
func onContinuousHover(coordinateSpace:perform:)
Adds an action to perform when the pointer enters, moves within, and exits the view’s bounds.
func hoverEffect(_:isEnabled:)
Applies a hover effect to this view.
Adds a condition that controls whether this view can display hover effects.
func defaultHoverEffect(_:)
Sets the default hover effect to use for views within this view.
var isHoverEffectEnabled: Bool
A Boolean value that indicates whether the view associated with this environment allows hover effects to be displayed.
enum HoverPhase
The current hovering state and value of the pointer.
struct HoverEffectPhaseOverride
Options for overriding a hover effect’s current phase.
Beta
struct OrnamentHoverContentEffect
Presents an ornament on hover using a custom effect.
struct OrnamentHoverEffect
Presents an ornament on hover.
Modifying pointer appearance
Sets the pointer style to display when the pointer is over the view.
struct PointerStyle
A style describing the appearance of the pointer (also called a cursor) when it’s hovered over a view.
Sets the visibility of the pointer when it’s over the view.
Changing view appearance for hover events
struct HoverEffect
An effect applied when the pointer hovers over a view.
Applies a hover effect to this view, optionally adding it to a HoverEffectGroup.
Applies a hover effect to this view described by the given closure.
protocol CustomHoverEffect
A type that represents how a view should change when a pointer hovers over a view, or when someone looks at the view.
struct ContentHoverEffect
A CustomHoverEffect that applies effects to a view on hover using a closure.
struct HoverEffectGroup
Describes a grouping of effects that activate together.
Adds an implicit HoverEffectGroup to all effects defined on descendant views, so that all effects added to subviews activate as a group whenever this view or any descendant views are hovered.
Adds a HoverEffectGroup to all effects defined on descendant views, and activates the group whenever this view or any descendant views are hovered.
struct GroupHoverEffect
A CustomHoverEffect that activates a named group of effects.
protocol HoverEffectContent
A type that describes the effects of a view for a particular hover effect phase.
struct EmptyHoverEffectContent
An empty base effect that you use to build other effects.
Sets the behavior of the hand pointer while the user is interacting with the view.
struct HandPointerBehavior
A behavior that can be applied to the hand pointer while the user is interacting with a view.
Responding to submission events
Adds an action to perform when the user submits a value to this view.
Prevents submission triggers originating from this view to invoke a submission action configured by a submission modifier higher up in the view hierarchy.
struct SubmitTriggers
A type that defines various triggers that result in the firing of a submission action.
Labeling a submission event
Sets the submit label for this view.
struct SubmitLabel
A semantic label describing the label of submission within a view hierarchy.
Responding to commands
Adds an action to perform in response to a move command, like when the user presses an arrow key on a Mac keyboard, or taps the edge of the Siri Remote when controlling an Apple TV.
Adds an action to perform in response to the system’s Delete command, or pressing either the ⌫ (backspace) or ⌦ (forward delete) keys while the view has focus.
Steps a value through a range in response to page up or page down commands.
Sets up an action that triggers in response to receiving the exit command while the view has focus.
Adds an action to perform in response to the system’s Play/Pause command.
Adds an action to perform in response to the given selector.
enum MoveCommandDirection
Specifies the direction of an arrow key movement.
Controlling hit testing
Sets whether text in this view can compress the space between characters when necessary to fit text in a line.
Defines the content shape for hit testing.
Sets the content shape for this view.
struct ContentShapeKinds
A kind for the content shape of a view.
Interacting with the Digital Crown
Specifies the visibility of Digital Crown accessory Views on Apple Watch.
Places an accessory View next to the Digital Crown on Apple Watch.
Tracks Digital Crown rotations by updating the specified binding.
func digitalCrownRotation(detent:from:through:by:sensitivity:isContinuous:isHapticFeedbackEnabled:onChange:onIdle:)
struct DigitalCrownEvent
An event emitted when the user rotates the Digital Crown.
enum DigitalCrownRotationalSensitivity
The amount of Digital Crown rotation needed to move between two integer numbers.
Managing Touch Bar input
Sets the content that the Touch Bar displays.
Sets the Touch Bar content to be shown in the Touch Bar when applicable.
Sets principal views that have special significance to this Touch Bar.
Sets a user-visible string that identifies the view’s functionality.
Sets the behavior of the user-customized view.
struct TouchBar
A container for a view that you can show in the Touch Bar.
enum TouchBarItemPresence
Options that affect user customization of the Touch Bar.
Responding to capture events
Used to register an action triggered by system capture events.
Used to register actions triggered by system capture events.
See Also
Event handling
Define interactions from taps, clicks, and swipes to fine-grained gestures.
Enable people to move or duplicate items by issuing Copy and Paste commands.
Enable people to move or duplicate items by dragging them from one location to another.
Identify and control which visible object responds to user interaction.
React to system events, like opening a URL.
https://developer.apple.com/documentation/swiftui/clipboard
Collection
- SwiftUI
- Clipboard
API Collection
Clipboard
Enable people to move or duplicate items by issuing Copy and Paste commands.
Overview
When people issue standard Copy and Cut commands, they expect to move items to the system’s Clipboard, from which they can paste the items into another place in the same app or into another app. Your app can participate in this activity if you add view modifiers that indicate how to respond to the standard commands.
In your copy and paste modifiers, provide or accept types that conform to the Transferable protocol, or that inherit from the NSItemProvider class. When possible, prefer using transferable items.
Topics
Copying transferable items
Specifies a list of items to copy in response to the system’s Copy command.
Specifies an action that moves items to the Clipboard in response to the system’s Cut command.
Specifies an action that adds validated items to a view in response to the system’s Paste command.
Copying items using item providers
Adds an action to perform in response to the system’s Copy command.
Adds an action to perform in response to the system’s Cut command.
func onPasteCommand(of:perform:)
Adds an action to perform in response to the system’s Paste command.
func onPasteCommand(of:validator:perform:)
Adds an action to perform in response to the system’s Paste command with items that you validate.
See Also
Event handling
Define interactions from taps, clicks, and swipes to fine-grained gestures.
Respond to input from a hardware device, like a keyboard or a Touch Bar.
Enable people to move or duplicate items by dragging them from one location to another.
Identify and control which visible object responds to user interaction.
React to system events, like opening a URL.
https://developer.apple.com/documentation/swiftui/drag-and-drop
Collection
- SwiftUI
- Drag and drop
API Collection
Drag and drop
Enable people to move or duplicate items by dragging them from one location to another.
Overview
Drag and drop offers people a convenient way to move content from one part of your app to another, or from one app to another, using an intuitive dragging gesture. Support this feature in your app by adding view modifiers to potential source and destination views within your app’s interface.
In your modifiers, provide or accept types that conform to the Transferable protocol, or that inherit from the NSItemProvider class. When possible, prefer using transferable items.
For design guidance, see Drag and drop in the Human Interface Guidelines.
Topics
Essentials
Adopting drag and drop using SwiftUI
Enable drag-and-drop interactions in lists, tables and custom views.
Making a view into a drag source
Adopt draggable API to provide items for drag-and-drop operations.
Configuring drag and drop behavior
struct DragConfiguration
The behavior of the drag, proposed by the dragging source.
Beta
struct DropConfiguration
Describes the behavior of the drop.
Moving items
struct DragSession
Describes the ongoing dragging session.
struct DropSession Beta
Moving transferable items
Activates this view as the source of a drag and drop operation.
Defines the destination of a drag and drop operation that handles the dropped content with a closure that you specify.
Moving items using item providers
Provides a closure that vends the drag representation to be used for a particular data element.
func onDrop(of:isTargeted:perform:)
Defines the destination of a drag-and-drop operation that handles the dropped content with a closure that you specify.
func onDrop(of:delegate:)
Defines the destination of a drag and drop operation using behavior controlled by the delegate that you provide.
protocol DropDelegate
An interface that you implement to interact with a drop operation in a view modified to accept drops.
struct DropProposal
The behavior of a drop.
enum DropOperation
Operation types that determine how a drag and drop session resolves when the user drops a drag item.
struct DropInfo
The current state of a drop.
Describing preview formations
struct DragDropPreviewsFormation
On macOS, describes the way the dragged previews are visually composed. Both drag sources and drop destination can specify their desired preview formation.
Configuring spring loading
Sets the spring loading behavior this view.
var springLoadingBehavior: SpringLoadingBehavior
The behavior of spring loaded interactions for the views associated with this environment.
struct SpringLoadingBehavior
The options for controlling the spring loading behavior of views.
See Also
Event handling
Define interactions from taps, clicks, and swipes to fine-grained gestures.
Respond to input from a hardware device, like a keyboard or a Touch Bar.
Enable people to move or duplicate items by issuing Copy and Paste commands.
Identify and control which visible object responds to user interaction.
React to system events, like opening a URL.
https://developer.apple.com/documentation/swiftui/focus
Collection
- SwiftUI
- Focus
API Collection
Focus
Identify and control which visible object responds to user interaction.
Overview
Focus indicates which element in the display receives the next input. Use view modifiers to indicate which views can receive focus, to detect which view has focus, and to programmatically control focus state.
For design guidance, see Focus and selection in the Human Interface Guidelines.
Topics
Essentials
Focus Cookbook: Supporting and enhancing focus-driven interactions in your SwiftUI app
Create custom focusable views with key-press handlers that accelerate keyboard input and support movement, and control focus programmatically.
Indicating that a view can receive focus
Specifies if the view is focusable.
Specifies if the view is focusable, and if so, what focus-driven interactions it supports.
struct FocusInteractions
Values describe different focus interactions that a view can support.
Managing focus state
Modifies this view by binding its focus state to the given state value.
Modifies this view by binding its focus state to the given Boolean state value.
var isFocused: Bool
Returns whether the nearest focusable ancestor has focus.
struct FocusState
A property wrapper type that can read and write a value that SwiftUI updates as the placement of focus within the scene changes.
struct FocusedValue
A property wrapper for observing values from the focused view or one of its ancestors.
macro Entry()
Creates an environment values, transaction, container values, or focused values entry.
protocol FocusedValueKey
A protocol for identifier types used when publishing and observing focused values.
struct FocusedBinding
A convenience property wrapper for observing and automatically unwrapping state bindings from the focused view or one of its ancestors.
Modifies this view by binding the focus state of the search field associated with the nearest searchable modifier to the given Boolean value.
Modifies this view by binding the focus state of the search field associated with the nearest searchable modifier to the given value.
Exposing value types to focused views
Sets the focused value for the given object type.
func focusedValue(_:_:)
Modifies this view by injecting a value that you provide for use by other views whose state depends on the focused view hierarchy.
Sets the focused value for the given object type at a scene-wide scope.
func focusedSceneValue(_:_:)
Modifies this view by injecting a value that you provide for use by other views whose state depends on the focused scene.
struct FocusedValues
A collection of state exported by the focused view and its ancestors.
Exposing reference types to focused views
func focusedObject(_:)
Creates a new view that exposes the provided object to other views whose whose state depends on the focused view hierarchy.
func focusedSceneObject(_:)
Creates a new view that exposes the provided object to other views whose whose state depends on the active scene.
struct FocusedObject
A property wrapper type for an observable object supplied by the focused view or one of its ancestors.
Setting focus scope
Creates a focus scope that SwiftUI uses to limit default focus preferences.
Indicates that the view’s frame and cohort of focusable descendants should be used to guide focus movement.
Controlling default focus
Indicates that the view should receive focus by default for a given namespace.
Defines a region of the window in which default focus is evaluated by assigning a value to a given focus state binding.
struct DefaultFocusEvaluationPriority
Prioritizations for default focus preferences when evaluating where to move focus in different circumstances.
Resetting focus
var resetFocus: ResetFocusAction
An action that requests the focus system to reevaluate default focus.
struct ResetFocusAction
An environment value that provides the ability to reevaluate default focus.
Configuring effects
Adds a condition that controls whether this view can display focus effects, such as a default focus ring or hover effect.
var isFocusEffectEnabled: Bool
A Boolean value that indicates whether the view associated with this environment allows focus effects to be displayed.
See Also
Event handling
Define interactions from taps, clicks, and swipes to fine-grained gestures.
Respond to input from a hardware device, like a keyboard or a Touch Bar.
Enable people to move or duplicate items by issuing Copy and Paste commands.
Enable people to move or duplicate items by dragging them from one location to another.
React to system events, like opening a URL.
https://developer.apple.com/documentation/swiftui/system-events
Collection
- SwiftUI
- System events
API Collection
System events
React to system events, like opening a URL.
Overview
Specify view and scene modifiers to indicate how your app responds to certain system events. For example, you can use the onOpenURL(perform:) view modifier to define an action to take when your app receives a universal link, or use the backgroundTask(_:action:) scene modifier to specify an asynchronous task to carry out in response to a background task event, like the completion of a background URL session.
Topics
Sending and receiving user activities
Restoring Your App’s State with SwiftUI
Provide app continuity for users by preserving their current activities.
Advertises a user activity type.
Registers a handler to invoke in response to a user activity that your app receives.
Sending and receiving URLs
var openURL: OpenURLAction
An action that opens a URL.
struct OpenURLAction
Registers a handler to invoke in response to a URL that your app receives.
Handling external events
Specifies the external events for which SwiftUI opens a new instance of the modified scene.
Specifies the external events that the view’s scene handles if the scene is already open.
Handling background tasks
Runs the specified action when the system provides a background task.
struct BackgroundTask
The kinds of background tasks that your app or extension can handle.
struct SnapshotData
The associated data of a snapshot background task.
struct SnapshotResponse
Your appplication’s response to a snapshot background task.
Importing and exporting transferable items
Enables importing items from services, such as Continuity Camera on macOS.
Exports items for consumption by shortcuts, quick actions, and services.
Exports read-write items for consumption by shortcuts, quick actions, and services.
Importing and exporting using item providers
Enables importing item providers from services, such as Continuity Camera on macOS.
Exports a read-only item provider for consumption by shortcuts, quick actions, and services.
Exports a read-write item provider for consumption by shortcuts, quick actions, and services.
See Also
Event handling
Define interactions from taps, clicks, and swipes to fine-grained gestures.
Respond to input from a hardware device, like a keyboard or a Touch Bar.
Enable people to move or duplicate items by issuing Copy and Paste commands.
Enable people to move or duplicate items by dragging them from one location to another.
Identify and control which visible object responds to user interaction.
https://developer.apple.com/documentation/swiftui/accessibility-fundamentals
Collection
- SwiftUI
- Accessibility fundamentals
API Collection
Accessibility fundamentals
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Overview
Like all Apple UI frameworks, SwiftUI comes with built-in accessibility support. The framework introspects common elements like navigation views, lists, text fields, sliders, buttons, and so on, and provides basic accessibility labels and values by default. You don’t have to do any extra work to enable these standard accessibility features.
SwiftUI also provides tools to help you enhance the accessibility of your app. To find out what enhancements you need, try using your app with accessibility features like VoiceOver, Voice Control, and Switch Control, or get feedback from users of your app that regularly use these features. Then use the accessibility view modifiers that SwiftUI provides to improve the experience. For example, you can explicitly add accessibility labels to elements in your UI using the accessibilityLabel(_:) or the accessibilityValue(_:) view modifier.
Customize your use of accessibility modifiers for all the platforms that your app runs on. For example, you may need to adjust the accessibility elements for a companion Apple Watch app that shares a common code base with an iOS app. If you integrate AppKit or UIKit controls in SwiftUI, expose any accessibility labels and make them accessible from your NSViewRepresentable or UIViewRepresentable views, or provide custom accessibility information if the underlying accessibility labels aren’t available.
For design guidance, see Accessibility in the Human Interface Guidelines.
Topics
Essentials
Creating Accessible Views
Make your app accessible to everyone by applying accessibility modifiers to your SwiftUI views.
Creating accessible elements
Creates a new accessibility element, or modifies the AccessibilityChildBehavior of the existing accessibility element.
Replaces the existing accessibility element’s children with one or more new synthetic accessibility elements.
Replaces one or more accessibility elements for this view with new accessibility elements.
struct AccessibilityChildBehavior
Defines the behavior for the child elements of the new parent element.
Identifying elements
Uses the string you specify to identify the view.
Hiding elements
Specifies whether to hide this view from system accessibility features.
Supporting types
struct AccessibilityTechnologies
Accessibility technologies available to the system.
struct AccessibilityAttachmentModifier
A view modifier that adds accessibility properties to the view
See Also
Accessibility
Enhance the legibility of content in your app’s interface.
Improve access to actions that your app can undertake.
Describe interface elements to help people understand what they represent.
Enable users to navigate to specific user interface elements using rotors.
https://developer.apple.com/documentation/swiftui/accessible-appearance
Collection
- SwiftUI
- Accessible appearance
API Collection
Accessible appearance
Enhance the legibility of content in your app’s interface.
Overview
Make content easier for people to see by making it larger, giving it greater contrast, or reducing the amount of distracting motion.
For design guidance, see Accessibility in the Accessibility section of the Human Interface Guidelines.
Topics
Managing color
Sets whether this view should ignore the system Smart Invert setting.
var accessibilityInvertColors: Bool
Whether the system preference for Invert Colors is enabled.
var accessibilityDifferentiateWithoutColor: Bool
Whether the system preference for Differentiate without Color is enabled.
Enlarging content
Adds a default large content view to be shown by the large content viewer.
Adds a custom large content view to be shown by the large content viewer.
var accessibilityLargeContentViewerEnabled: Bool
Whether the Large Content Viewer is enabled.
Improving legibility
var accessibilityShowButtonShapes: Bool
Whether the system preference for Show Button Shapes is enabled.
var accessibilityReduceTransparency: Bool
Whether the system preference for Reduce Transparency is enabled.
var legibilityWeight: LegibilityWeight?
The font weight to apply to text.
enum LegibilityWeight
The Accessibility Bold Text user setting options.
Minimizing motion
var accessibilityDimFlashingLights: Bool
Whether the setting to reduce flashing or strobing lights in video content is on. This setting can also be used to determine if UI in playback controls should be shown to indicate upcoming content that includes flashing or strobing lights.
var accessibilityPlayAnimatedImages: Bool
Whether the setting for playing animations in an animated image is on. When this value is false, any presented image that contains animation should not play automatically.
var accessibilityReduceMotion: Bool
Whether the system preference for Reduce Motion is enabled.
Using assistive access
var accessibilityAssistiveAccessEnabled: Bool
A Boolean value that indicates whether Assistive Access is in use.
struct AssistiveAccess
A scene that presents an interface appropriate for Assistive Access on iOS and iPadOS. On other platforms, this scene is unused.
Beta
See Also
Accessibility
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Improve access to actions that your app can undertake.
Describe interface elements to help people understand what they represent.
Enable users to navigate to specific user interface elements using rotors.
https://developer.apple.com/documentation/swiftui/accessible-controls
Collection
- SwiftUI
- Accessible controls
API Collection
Accessible controls
Improve access to actions that your app can undertake.
Overview
Help people using assistive technologies to gain access to controls in your app.
For design guidance, see Accessibility in the Accessibility section of the Human Interface Guidelines.
Topics
Adding actions to views
Adds an accessibility action to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action.
Adds multiple accessibility actions to the view.
func accessibilityAction(named:_:)
Adds an accessibility action labeled by the contents of label to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action. When the action is performed, the intent will be invoked.
Adds an accessibility action representing actionKind to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action. When the action is performed, the intent will be invoked.
func accessibilityAction(named:intent:)
Adds an accessibility action labeled name to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action. When the action is performed, the intent will be invoked.
Adds an accessibility adjustable action to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action.
Adds an accessibility scroll action to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action.
Adds multiple accessibility actions to the view with a specific category. Actions allow assistive technologies, such as VoiceOver, to interact with the view by invoking the action and are grouped by their category. When multiple action modifiers with an equal category are applied to the view, the actions are combined together.
struct AccessibilityActionKind
The structure that defines the kinds of available accessibility actions.
enum AccessibilityAdjustmentDirection
A directional indicator you use when making an accessibility adjustment.
struct AccessibilityActionCategory
Designates an accessibility action category that is provided and named by the system.
Offering Quick Actions to people
Adds a quick action to be shown by the system when active.
protocol AccessibilityQuickActionStyle
A type that describes the presentation style of an accessibility quick action.
Making gestures accessible
func accessibilityActivationPoint(_:)
The activation point for an element is the location assistive technologies use to initiate gestures.
func accessibilityActivationPoint(_:isEnabled:)
func accessibilityDragPoint(_:description:)
The point an assistive technology should use to begin a drag interaction.
func accessibilityDragPoint(_:description:isEnabled:)
func accessibilityDropPoint(_:description:)
The point an assistive technology should use to end a drag interaction.
func accessibilityDropPoint(_:description:isEnabled:)
Explicitly set whether this accessibility element is a direct touch area. Direct touch areas passthrough touch events to the app rather than being handled through an assistive technology, such as VoiceOver. The modifier accepts an optional AccessibilityDirectTouchOptions option set to customize the functionality of the direct touch area.
Adds an accessibility zoom action to the view. Actions allow assistive technologies, such as VoiceOver, to interact with the view by invoking the action.
struct AccessibilityDirectTouchOptions
An option set that defines the functionality of a view’s direct touch area.
struct AccessibilityZoomGestureAction
Position and direction information of a zoom gesture that someone performs with an assistive technology like VoiceOver.
Controlling focus
Modifies this view by binding its accessibility element’s focus state to the given boolean state value.
Modifies this view by binding its accessibility element’s focus state to the given state value.
struct AccessibilityFocusState
A property wrapper type that can read and write a value that SwiftUI updates as the focus of any active accessibility technology, such as VoiceOver, changes.
Managing interactivity
Explicitly set whether this Accessibility element responds to user interaction and would thus be interacted with by technologies such as Switch Control, Voice Control or Full Keyboard Access.
See Also
Accessibility
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Enhance the legibility of content in your app’s interface.
Describe interface elements to help people understand what they represent.
Enable users to navigate to specific user interface elements using rotors.
https://developer.apple.com/documentation/swiftui/accessible-descriptions
Collection
- SwiftUI
- Accessible descriptions
API Collection
Accessible descriptions
Describe interface elements to help people understand what they represent.
Overview
SwiftUI can often infer some information about your user interface elements, but you can use accessibility modifiers to provide even more information for users that need it.
For design guidance, see Accessibility in the Accessibility section of the Human Interface Guidelines.
Topics
Applying labels
func accessibilityLabel(_:)
Adds a label to the view that describes its contents.
func accessibilityLabel(_:isEnabled:)
func accessibilityInputLabels(_:)
Sets alternate input labels with which users identify a view.
func accessibilityInputLabels(_:isEnabled:)
Pairs an accessibility element representing a label with the element for the matching content.
enum AccessibilityLabeledPairRole
The role of an accessibility element in a label / content pair.
Describing values
func accessibilityValue(_:)
Adds a textual description of the value that the view contains.
func accessibilityValue(_:isEnabled:)
Describing content
Sets an accessibility text content type.
Sets the accessibility level of this heading.
enum AccessibilityHeadingLevel
The hierarchy of a heading in relation other headings.
struct AccessibilityTextContentType
Textual context that assistive technologies can use to improve the presentation of spoken text.
Describing charts
Adds a descriptor to a View that represents a chart to make the chart’s contents accessible to all users.
protocol AXChartDescriptorRepresentable
A type to generate an AXChartDescriptor object that you use to provide information about a chart and its data for an accessible experience in VoiceOver or other assistive technologies.
Adding custom descriptions
func accessibilityCustomContent(_:_:importance:)
Add additional accessibility information to the view.
struct AccessibilityCustomContentKey
Key used to specify the identifier and label associated with an entry of additional accessibility information.
Assigning traits to content
Adds the given traits to the view.
Removes the given traits from this view.
struct AccessibilityTraits
A set of accessibility traits that describe how an element behaves.
Offering hints
func accessibilityHint(_:)
Communicates to the user what happens after performing the view’s action.
func accessibilityHint(_:isEnabled:)
Configuring VoiceOver
Raises or lowers the pitch of spoken text.
Sets whether VoiceOver should always speak all punctuation in the text view.
Controls whether to queue pending announcements behind existing speech rather than interrupting speech in progress.
Sets whether VoiceOver should speak the contents of the text view character by character.
See Also
Accessibility
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Enhance the legibility of content in your app’s interface.
Improve access to actions that your app can undertake.
Enable users to navigate to specific user interface elements using rotors.
https://developer.apple.com/documentation/swiftui/accessible-navigation
Collection
- SwiftUI
- Accessible navigation
API Collection
Accessible navigation
Enable users to navigate to specific user interface elements using rotors.
Overview
An accessibility rotor is a shortcut that enables users to quickly navigate to specific elements of the user interface, and, optionally, to specific ranges of text within those elements.
The system automatically provides rotors for many navigable elements, but you can supply additional rotors for specific purposes, or replace system rotors when they don’t automatically pick up off-screen elements, like those far down in a LazyVStack or a List.
For design guidance, see Accessibility in the Accessibility section of the Human Interface Guidelines.
Topics
Working with rotors
func accessibilityRotor(_:entries:)
Create an Accessibility Rotor with the specified user-visible label, and entries generated from the content closure.
func accessibilityRotor(_:entries:entryID:entryLabel:)
Create an Accessibility Rotor with the specified user-visible label and entries.
func accessibilityRotor(_:entries:entryLabel:)
func accessibilityRotor(_:textRanges:)
Create an Accessibility Rotor with the specified user-visible label and entries for each of the specified ranges. The Rotor will be attached to the current Accessibility element, and each entry will go the specified range of that element.
Creating rotors
protocol AccessibilityRotorContent
Content within an accessibility rotor.
struct AccessibilityRotorContentBuilder
Result builder you use to generate rotor entry content.
struct AccessibilityRotorEntry
A struct representing an entry in an Accessibility Rotor.
Replacing system rotors
struct AccessibilitySystemRotor
Designates a Rotor that replaces one of the automatic, system-provided Rotors with a developer-provided Rotor.
Configuring rotors
Defines an explicit identifier tying an Accessibility element for this view to an entry in an Accessibility Rotor.
Links multiple accessibility elements so that the user can quickly navigate from one element to another, even when the elements are not near each other in the accessibility hierarchy.
Sets the sort priority order for this view’s accessibility element, relative to other elements at the same level.
See Also
Accessibility
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Enhance the legibility of content in your app’s interface.
Improve access to actions that your app can undertake.
Describe interface elements to help people understand what they represent.
https://developer.apple.com/documentation/swiftui/appkit-integration
Collection
- SwiftUI
- AppKit integration
API Collection
AppKit integration
Add AppKit views to your SwiftUI app, or use SwiftUI views in your AppKit app.
Overview
Integrate SwiftUI with your app’s existing content using hosting controllers to add SwiftUI views into AppKit interfaces. A hosting controller wraps a set of SwiftUI views in a form that you can then add to your storyboard-based app.
You can also add AppKit views and view controllers to your SwiftUI interfaces. A representable object wraps the designated view or view controller, and facilitates communication between the wrapped object and your SwiftUI views.
For design guidance, see Designing for macOS in the Human Interface Guidelines.
Topics
Displaying SwiftUI views in AppKit
Unifying your app’s animations
Create a consistent UI animation experience across SwiftUI, UIKit, and AppKit.
class NSHostingController
An AppKit view controller that hosts SwiftUI view hierarchy.
class NSHostingView
An AppKit view that hosts a SwiftUI view hierarchy.
class NSHostingMenu
An AppKit menu with menu items that are defined by a SwiftUI View.
struct NSHostingSizingOptions
Options for how hosting views and controllers reflect their content’s size into Auto Layout constraints.
class NSHostingSceneRepresentation
An AppKit type that hosts and can present SwiftUI scenes
Beta
struct NSHostingSceneBridgingOptions
Options for how hosting views and controllers manage aspects of the associated window.
Adding AppKit views to SwiftUI view hierarchies
protocol NSViewRepresentable
A wrapper that you use to integrate an AppKit view into your SwiftUI view hierarchy.
struct NSViewRepresentableContext
Contextual information about the state of the system that you use to create and update your AppKit view.
protocol NSViewControllerRepresentable
A wrapper that you use to integrate an AppKit view controller into your SwiftUI interface.
struct NSViewControllerRepresentableContext
Contextual information about the state of the system that you use to create and update your AppKit view controller.
Adding AppKit gesture recognizers into SwiftUI view hierarchies
protocol NSGestureRecognizerRepresentable
A wrapper for an NSGestureRecognizer that you use to integrate that gesture recognizer into your SwiftUI hierarchy.
struct NSGestureRecognizerRepresentableContext
Contextual information about the state of the system that you use to create and update a represented gesture recognizer.
struct NSGestureRecognizerRepresentableCoordinateSpaceConverter
A structure used to convert locations to and from coordinate spaces in the hierarchy of the SwiftUI view associated with an NSGestureRecognizerRepresentable.
See Also
Framework integration
Add UIKit views to your SwiftUI app, or use SwiftUI views in your UIKit app.
Add WatchKit views to your SwiftUI app, or use SwiftUI views in your WatchKit app.
Use SwiftUI views that other Apple frameworks provide.
https://developer.apple.com/documentation/swiftui/uikit-integration
Collection
- SwiftUI
- UIKit integration
API Collection
UIKit integration
Add UIKit views to your SwiftUI app, or use SwiftUI views in your UIKit app.
Overview
Integrate SwiftUI with your app’s existing content using hosting controllers to add SwiftUI views into UIKit interfaces. A hosting controller wraps a set of SwiftUI views in a form that you can then add to your storyboard-based app.
You can also add UIKit views and view controllers to your SwiftUI interfaces. A representable object wraps the designated view or view controller, and facilitates communication between the wrapped object and your SwiftUI views.
For design guidance, see the following sections in the Human Interface Guidelines:
-
Designing for iOS
-
Designing for iPadOS
-
Designing for tvOS
Topics
Displaying SwiftUI views in UIKit
Using SwiftUI with UIKit
Learn how to incorporate SwiftUI views into a UIKit app.
Unifying your app’s animations
Create a consistent UI animation experience across SwiftUI, UIKit, and AppKit.
class UIHostingController
A UIKit view controller that manages a SwiftUI view hierarchy.
struct UIHostingControllerSizingOptions
Options for how a hosting controller tracks its content’s size.
struct UIHostingConfiguration
A content configuration suitable for hosting a hierarchy of SwiftUI views.
protocol UIHostingSceneDelegate
Extends UIKit/UISceneDelegate to bridge SwiftUI scenes.
Beta
Adding UIKit views to SwiftUI view hierarchies
protocol UIViewRepresentable
A wrapper for a UIKit view that you use to integrate that view into your SwiftUI view hierarchy.
struct UIViewRepresentableContext
Contextual information about the state of the system that you use to create and update your UIKit view.
protocol UIViewControllerRepresentable
A view that represents a UIKit view controller.
struct UIViewControllerRepresentableContext
Contextual information about the state of the system that you use to create and update your UIKit view controller.
Adding UIKit gesture recognizers into SwiftUI view hierarchies
protocol UIGestureRecognizerRepresentable
A wrapper for a UIGestureRecognizer that you use to integrate that gesture recognizer into your SwiftUI hierarchy.
struct UIGestureRecognizerRepresentableContext
Contextual information about the state of the system that you use to create and update a represented gesture recognizer.
struct UIGestureRecognizerRepresentableCoordinateSpaceConverter
A proxy structure used to convert locations to/from coordinate spaces in the hierarchy of the SwiftUI view associated with a UIGestureRecognizerRepresentable.
Sharing configuration information
typealias UITraitBridgedEnvironmentKey
Hosting an ornament in UIKit
class UIHostingOrnament
A model that represents an ornament suitable for being hosted in UIKit.
class UIOrnament
The abstract base class that represents an ornament.
See Also
Framework integration
Add AppKit views to your SwiftUI app, or use SwiftUI views in your AppKit app.
Add WatchKit views to your SwiftUI app, or use SwiftUI views in your WatchKit app.
Use SwiftUI views that other Apple frameworks provide.
https://developer.apple.com/documentation/swiftui/watchkit-integration
Collection
- SwiftUI
- WatchKit integration
API Collection
WatchKit integration
Add WatchKit views to your SwiftUI app, or use SwiftUI views in your WatchKit app.
Overview
Integrate SwiftUI with your app’s existing content using hosting controllers to add SwiftUI views into WatchKit interfaces. A hosting controller wraps a set of SwiftUI views in a form that you can then add to your storyboard-based app.
You can also add WatchKit views and view controllers to your SwiftUI interfaces. A representable object wraps the designated view or view controller, and facilitates communication between the wrapped object and your SwiftUI views.
For design guidance, see Designing for watchOS in the Human Interface Guidelines.
Topics
Displaying SwiftUI views in WatchKit
class WKHostingController
A WatchKit interface controller that hosts a SwiftUI view hierarchy.
class WKUserNotificationHostingController
A WatchKit user notification interface controller that hosts a SwiftUI view hierarchy.
Adding WatchKit views to SwiftUI view hierarchies
protocol WKInterfaceObjectRepresentable
A view that represents a WatchKit interface object.
struct WKInterfaceObjectRepresentableContext
Contextual information about the state of the system that you use to create and update your WatchKit interface object.
See Also
Framework integration
Add AppKit views to your SwiftUI app, or use SwiftUI views in your AppKit app.
Add UIKit views to your SwiftUI app, or use SwiftUI views in your UIKit app.
Use SwiftUI views that other Apple frameworks provide.
https://developer.apple.com/documentation/swiftui/technology-specific-views
Collection
- SwiftUI
- Technology-specific views
API Collection
Technology-specific views
Use SwiftUI views that other Apple frameworks provide.
Overview
To access SwiftUI views that another framework defines, import both SwiftUI and the other framework into the file where you use the view. You can find the framework to import by looking at the availability information on the view’s documentation page.
For example, to use the Map view in your app, import both SwiftUI and MapKit.
import SwiftUI import MapKit
struct MyMapView: View { // Center the map on Joshua Tree National Park. var region = MKCoordinateRegion( center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868), span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2) )
var body: some View { Map(initialPosition: .region(region)) } }
For design guidance, see Technologies in the Human Interface Guidelines.
Topics
Accessing Apple Pay and Wallet
A view that displays a button for identity verification.
Sets the button’s style.
Sets the style to be used by the button. (see PKAddPassButtonStyle).
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
Sets the action on the PayLaterView. See PKPayLaterAction.
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Sets the style to be used by the button. (see PKIdentityButtonStyle).
Provides a task to perform before this view appears
Authorizing and authenticating
A SwiftUI view that displays an authentication interface.
@MainActor @preconcurrency struct SignInWithAppleButton
The view that creates the Sign in with Apple button for display.
Sets the style used for displaying the control (see SignInWithAppleButton.Style).
var authorizationController: AuthorizationController
A value provided in the SwiftUI environment that views can use to perform authorization requests.
var webAuthenticationSession: WebAuthenticationSession
A value provided in the SwiftUI environment that views can use to authenticate a user through a web service.
Configuring Family Sharing
@MainActor @preconcurrency struct FamilyActivityPicker
A view in which users specify applications, web domains, and categories without revealing their choices to the app.
Presents an activity picker view as a sheet.
Reporting on device activity
@MainActor @preconcurrency struct DeviceActivityReport
A view that reports the user’s application, category, and web domain activity in a privacy-preserving way.
Working with managed devices
Applies a managed content style to the view.
Presents a modal view that enables users to add devices to their organization.
Creating graphics
A SwiftUI view that displays a chart.
@MainActor @preconcurrency struct SceneView
A SwiftUI view for displaying 3D SceneKit content.
Deprecated
@MainActor @preconcurrency struct SpriteView
A SwiftUI view that renders a SpriteKit scene.
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
Presents a map item detail sheet.
Displaying media
@MainActor @preconcurrency struct CameraView
A SwiftUI view into which a video stream or an image snapshot is rendered.
@MainActor @preconcurrency struct NowPlayingView
A view that displays the system’s Now Playing interface so that the user can control audio.
A view that displays content from a player and a native user interface to control playback.
A continuityDevicePicker should be used to discover and connect nearby continuity device through a button interface or other form of activation. On tvOS, this presents a fullscreen continuity device picker experience when selected. The modal view covers as much the screen of self as possible when a given condition is true.
Specifies the view that should act as the virtual camera for Apple Vision Pro 2D Persona stream.
Selecting photos
A view that displays a Photos picker for choosing assets from the photo library.
Presents a Photos picker that selects a PhotosPickerItem.
Presents a Photos picker that selects a PhotosPickerItem from a given photo library.
Presents a Photos picker that selects a collection of PhotosPickerItem.
Presents a Photos picker that selects a collection of PhotosPickerItem from a given photo library.
Sets the accessory visibility of the Photos picker. Accessories include anything between the content and the edge, like the navigation bar or the sidebar.
Disables capabilities of the Photos picker.
Sets the mode of the Photos picker.
Previewing content
Presents a Quick Look preview of the contents of a single URL.
Presents a Quick Look preview of the URLs you provide.
Interacting with networked devices
A SwiftUI view that displays other devices on the network, and creates an encrypted connection to a copy of your app running on that device.
var devicePickerSupports: DevicePickerSupportedAction
Checks for support to present a DevicePicker.
Configuring a Live Activity
The text color for the auxiliary action button that the system shows next to a Live Activity on the Lock Screen.
Sets the tint color for the background of a Live Activity that appears on the Lock Screen.
var isActivityFullscreen: Bool
A Boolean value that indicates whether the Live Activity appears in a full-screen presentation.
var activityFamily: ActivityFamily
The size family of the current Live Activity.
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
Declares the view as dependent on a collection of In-App Purchase products and returns a modified view.
Declares the view as dependent on the status of an auto-renewable subscription group, and returns a modified view.
Configures subscription store view instances within a view to use the provided button label.
Sets a view to use to decorate individual subscription options within a subscription store view.
Sets the control style for subscription store views within a view.
Sets the control style and control placement for subscription store views within a view.
Sets the style subscription store views within this view use to display groups of subscription options.
Sets the background style for picker items of the subscription store view instances within a view.
Sets the background shape and style for subscription store view picker items within a view.
Configures a view as the destination for a policy button action in subscription store views.
Configures a URL as the destination for a policy button action in subscription store views.
Sets the style for the and buttons within a subscription store view.
Sets the primary and secondary style for the and buttons within a subscription store view.
Adds an action to perform when a person uses the sign-in button on a subscription store view within a view.
func subscriptionStoreControlBackground(_:)
Set a standard effect to use for the background of subscription store view controls within the view.
Selects a promotional offer to apply to a purchase a customer makes from a subscription store view.
Selects a subscription offer to apply to a purchase that a customer makes from a subscription store view, a store view, or a product view.
Accessing health data
Asynchronously requests permission to read a data type that requires per-object authorization (such as vision prescriptions).
Requests permission to read the specified HealthKit data types.
Requests permission to save and read the specified HealthKit data types.
Presents a preview of the workout contents as a modal sheet
Providing tips
Presents a popover tip on the modified view.
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
Sets the corner radius for an inline tip view.
Sets the size for a tip’s image.
Sets the given style for TipView within the view hierarchy.
Sets the style for a tip’s image.
Showing a translation
Presents a translation popover when a given condition is true.
Adds a task to perform before this view appears or when the translation configuration changes.
Adds a task to perform before this view appears or when the specified source or target languages change.
Presenting journaling suggestions
Presents a visual picker interface that contains events and images that a person can select to retrieve more information.
Managing contact access
Modally present UI which allows the user to select which contacts your app has access to.
Handling game controller events
Specifies the game controllers events which should be delivered through the GameController framework when the view, or one of its descendants has focus.
Creating a tabletop game
Adds a tabletop game to a view.
Supplies a closure which returns a new interaction whenever needed.
Configuring camera controls
var realityViewCameraControls: CameraControls
The camera controls for the reality view.
Adds gestures that control the position and direction of a virtual camera.
Interacting with transactions
Presents a picker that selects a collection of transactions.
See Also
Framework integration
Add AppKit views to your SwiftUI app, or use SwiftUI views in your AppKit app.
Add UIKit views to your SwiftUI app, or use SwiftUI views in your UIKit app.
Add WatchKit views to your SwiftUI app, or use SwiftUI views in your WatchKit app.
https://developer.apple.com/documentation/swiftui/previews-in-xcode
Collection
- SwiftUI
- Previews in Xcode
API Collection
Previews in Xcode
Generate dynamic, interactive previews of your custom views.
Overview
When you create a custom View with SwiftUI, Xcode can display a preview of the view’s content that stays up-to-date as you make changes to the view’s code. You use one of the preview macros — like Preview(_:body:) — to tell Xcode what to display. Xcode shows the preview in a canvas beside your code.
Different preview macros enable different kinds of configuration. For example, you can add traits that affect the preview’s appearance using the Preview(_:traits:_:body:) macro or add custom viewpoints for the preview using the Preview(_:traits:body:cameras:) macro. You can also check how your view behaves inside a specific scene type. For example, in visionOS you can use the Preview(_:immersionStyle:traits:body:) macro to preview your view inside an ImmersiveSpace.
You typically rely on preview macros to create previews in your code. However, if you can’t get the behavior you need using a preview macro, you can use the PreviewProvider protocol and its associated supporting types to define and configure a preview.
Topics
Essentials
Previewing your app’s interface in Xcode
Iterate designs quickly and preview your apps’ displays across different Apple devices.
Creating a preview
Creates a preview of a SwiftUI view.
Creates a preview of a SwiftUI view using the specified traits.
Creates a preview of a SwiftUI view using the specified traits and custom viewpoints.
Creating a preview in the context of a scene
Creates a preview of a SwiftUI view in an immersive space.
Creates a preview of a SwiftUI view in an immersive space with custom viewpoints.
Creates a preview of a SwiftUI view in a window.
Creates a preview of a SwiftUI view in a window with custom viewpoints.
Defining a preview
macro Previewable()
Tag allowing a dynamic property to appear inline in a preview.
protocol PreviewProvider
A type that produces view previews in Xcode.
enum PreviewPlatform
Platforms that can run the preview.
Sets a user visible name to show in the canvas for a preview.
protocol PreviewModifier
A type that defines an environment in which previews can appear.
struct PreviewModifierContent
The type-erased content of a preview.
Customizing a preview
Overrides the device for a preview.
struct PreviewDevice
A simulator device that runs a preview.
Overrides the size of the container for the preview.
Overrides the orientation of the preview.
struct InterfaceOrientation
The orientation of the interface from the user’s perspective.
Setting a context
Declares a context for the preview.
protocol PreviewContext
A context type for use with a preview.
protocol PreviewContextKey
A key type for a preview context.
Building in debug mode
struct DebugReplaceableView
Erases view opaque result types in debug builds.
Beta
See Also
Tool support
Expose custom views and modifiers in the Xcode library.
Measure and improve your app’s responsiveness.
https://developer.apple.com/documentation/swiftui/xcode-library-customization
Collection
- SwiftUI
- Xcode library customization
Xcode library customization
Expose custom views and modifiers in the Xcode library.
Overview
You can add your custom SwiftUI views and view modifiers to Xcode’s library. This allows anyone developing your app or adopting your framework to access them by clicking the Library button (+) in Xcode’s toolbar. You can select and drag the custom library items into code, just like you would for system-provided items.
To add items to the library, create a structure that conforms to the LibraryContentProvider protocol and encapsulate any items you want to add as LibraryItem instances. Implement the doc://com.apple.documentation/documentation/DeveloperToolsSupport/LibraryContentProvider/views-25pdm computed property to add library items containing views. Implement the doc://com.apple.documentation/documentation/DeveloperToolsSupport/LibraryContentProvider/modifiers(base:)-4svii method to add items containing view modifiers. Xcode harvests items from all of the library content providers in your project as you work, and makes them available to you in its library.
Topics
Creating library items
protocol LibraryContentProvider
A source of Xcode library and code completion content.
struct LibraryItem
A single item to add to the Xcode library.
See Also
Tool support
Generate dynamic, interactive previews of your custom views.
Measure and improve your app’s responsiveness.
https://developer.apple.com/documentation/swiftui/performance-analysis
Collection
- SwiftUI
- Performance analysis
Performance analysis
Measure and improve your app’s responsiveness.
Overview
Use Instruments to detect hangs and hitches in your app, and to analyze long view body updates and frequently occurring SwiftUI updates that can contribute to hangs and hitches.
Topics
Essentials
Understanding user interface responsiveness
Make your app more responsive by examining the event-handling and rendering loop.
Understanding hangs in your app
Determine the cause for delays in user interactions by examining the main thread and the main run loop.
Understanding hitches in your app
Determine the cause of interruptions in motion by examining the render loop.
Analyzing SwiftUI performance
Understanding and improving SwiftUI performance
Identify and address long-running view updates, and reduce the frequency of updates.
See Also
Tool support
Generate dynamic, interactive previews of your custom views.
Expose custom views and modifiers in the Xcode library.
https://developer.apple.com/documentation/swiftui/app)
https://developer.apple.com/documentation/swiftui/view)
https://developer.apple.com/documentation/swiftui/landmarks-building-an-app-with-liquid-glass)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/building-a-document-based-app-with-swiftui)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/app-organization)
https://developer.apple.com/documentation/swiftui/scenes)
https://developer.apple.com/documentation/swiftui/windows)
https://developer.apple.com/documentation/swiftui/immersive-spaces)
https://developer.apple.com/documentation/swiftui/documents)
https://developer.apple.com/documentation/swiftui/navigation)
https://developer.apple.com/documentation/swiftui/modal-presentations)
https://developer.apple.com/documentation/swiftui/toolbars)
https://developer.apple.com/documentation/swiftui/search)
https://developer.apple.com/documentation/swiftui/app-extensions)
https://developer.apple.com/documentation/swiftui/model-data)
https://developer.apple.com/documentation/swiftui/environment-values)
https://developer.apple.com/documentation/swiftui/preferences)
https://developer.apple.com/documentation/swiftui/persistent-storage)
https://developer.apple.com/documentation/swiftui/view-fundamentals)
https://developer.apple.com/documentation/swiftui/view-configuration)
https://developer.apple.com/documentation/swiftui/view-styles)
https://developer.apple.com/documentation/swiftui/animations)
https://developer.apple.com/documentation/swiftui/text-input-and-output)
https://developer.apple.com/documentation/swiftui/images)
https://developer.apple.com/documentation/swiftui/controls-and-indicators)
https://developer.apple.com/documentation/swiftui/menus-and-commands)
https://developer.apple.com/documentation/swiftui/shapes)
https://developer.apple.com/documentation/swiftui/drawing-and-graphics)
https://developer.apple.com/documentation/swiftui/layout-fundamentals)
https://developer.apple.com/documentation/swiftui/layout-adjustments)
https://developer.apple.com/documentation/swiftui/custom-layout)
https://developer.apple.com/documentation/swiftui/lists)
https://developer.apple.com/documentation/swiftui/tables)
https://developer.apple.com/documentation/swiftui/view-groupings)
https://developer.apple.com/documentation/swiftui/scroll-views)
https://developer.apple.com/documentation/swiftui/gestures)
https://developer.apple.com/documentation/swiftui/input-events)
https://developer.apple.com/documentation/swiftui/clipboard)
https://developer.apple.com/documentation/swiftui/drag-and-drop)
https://developer.apple.com/documentation/swiftui/focus)
https://developer.apple.com/documentation/swiftui/system-events)
https://developer.apple.com/documentation/swiftui/accessibility-fundamentals)
https://developer.apple.com/documentation/swiftui/accessible-appearance)
https://developer.apple.com/documentation/swiftui/accessible-controls)
https://developer.apple.com/documentation/swiftui/accessible-descriptions)
https://developer.apple.com/documentation/swiftui/accessible-navigation)
https://developer.apple.com/documentation/swiftui/appkit-integration)
https://developer.apple.com/documentation/swiftui/uikit-integration)
https://developer.apple.com/documentation/swiftui/watchkit-integration)
https://developer.apple.com/documentation/swiftui/technology-specific-views)
https://developer.apple.com/documentation/swiftui/previews-in-xcode)
https://developer.apple.com/documentation/swiftui/xcode-library-customization)
https://developer.apple.com/documentation/swiftui/performance-analysis)
https://developer.apple.com/documentation/swiftui/documentgroup
- SwiftUI
- DocumentGroup
Structure
DocumentGroup
A scene that enables support for opening, creating, and saving documents.
Mentioned in
Building and customizing the menu bar with SwiftUI
Overview
Use a DocumentGroup scene to tell SwiftUI what kinds of documents your app can open when you declare your app using the App protocol.
Initialize a document group scene by passing in the document model and a view capable of displaying the document type. The document types you supply to DocumentGroup must conform to FileDocument or ReferenceFileDocument. SwiftUI uses the model to add document support to your app. In macOS this includes document-based menu support, including the ability to open multiple documents. On iOS this includes a document browser that can navigate to the documents stored on the file system and multiwindow support:
@main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: TextFile()) { configuration in ContentView(document: configuration.$document) } } }
Any time the configuration changes, SwiftUI updates the contents with that new configuration, similar to other parameterized builders.
Viewing documents
If your app only needs to display but not modify a specific document type, you can use the file viewer document group scene. You supply the file type of the document, and a view that displays the document type that you provide:
@main struct MyApp: App { var body: some Scene { DocumentGroup(viewing: MyImageFormatDocument.self) { MyImageFormatViewer(image: $0.document) } } }
Supporting multiple document types
Your app can support multiple document types by adding additional document group scenes:
@main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: TextFile()) { group in ContentView(document: group.$document) } DocumentGroup(viewing: MyImageFormatDocument.self) { group in MyImageFormatViewer(image: group.document) } } }
Accessing the document’s URL
If your app needs to know the document’s URL, you can read it from the editor closure’s configuration parameter, along with the binding to the document. When you create a new document, the configuration’s fileURL property is nil. Every time it changes, it is passed over to the DocumentGroup builder in the updated configuration. This ensures that the view you define in the closure always knows the URL of the document it hosts.
@main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: TextFile()) { configuration in ContentView( document: configuration.$document, fileURL: configuration.fileURL ) } } }
The URL can be used, for example, to present the file path of the file name in the user interface. Don’t access the document’s contents or metadata using the URL because that can conflict with the management of the file that SwiftUI performs. Instead, use the methods that FileDocument and ReferenceFileDocument provide to perform read and write operations.
Topics
Creating a document group
init(newDocument:editor:)
Creates a document group for creating and editing file documents.
init(viewing:viewer:)
Creates a document group capable of viewing file documents.
Editing a document backed by a persistent store
init(editing:contentType:editor:prepareDocument:)
Instantiates a document group for creating and editing documents that store a specific model type.
Instantiates a document group for creating and editing documents described by the last Schema in the migration plan.
Viewing a document backed by a persistent store
init(viewing:contentType:viewer:)
Instantiates a document group for viewing documents that store a specific model type.
Instantiates a document group for viewing documents described by the last Schema in the migration plan.
Relationships
Conforms To
Scene
See Also
Creating a document
Building a document-based app with SwiftUI
Create, save, and open documents in a multiplatform app.
Building a document-based app using SwiftData
Code along with the WWDC presenter to transform an app with SwiftData.
https://developer.apple.com/documentation/swiftui/filedocument
- SwiftUI
- FileDocument
Protocol
FileDocument
A type that you use to serialize documents to and from file.
@preconcurrency protocol FileDocument : Sendable
Overview
To store a document as a value type — like a structure — create a type that conforms to the FileDocument protocol and implement the required methods and properties. Your implementation:
-
Provides a list of the content types that the document can read from and write to by defining
readableContentTypes. If the list of content types that the document can write to is different from those that it reads from, you can optionally also definewritableContentTypes. -
Loads documents from file in the
init(configuration:)initializer. -
Stores documents to file by serializing their content in the
fileWrapper(configuration:)method.
Ensure that types that conform to this protocol are Sendable. In particular, SwiftUI calls the protocol’s methods from different isolation domains. Don’t perform serialization and deserialization on MainActor.
Topics
Reading a document
init(configuration: Self.ReadConfiguration) throws
Creates a document and initializes it with the contents of a file.
Required
static var readableContentTypes: [UTType]
The file and data types that the document reads from.
typealias ReadConfiguration
The configuration for reading document contents.
Writing a document
Serializes a document snapshot to a file wrapper.
static var writableContentTypes: [UTType]
The file types that the document supports saving or exporting to.
Required Default implementation provided.
typealias WriteConfiguration
The configuration for writing document contents.
Relationships
Inherits From
SendableSendableMetatype
See Also
Storing document data in a structure instance
struct FileDocumentConfiguration
The properties of an open file document.
https://developer.apple.com/documentation/swiftui/referencefiledocument
- SwiftUI
- ReferenceFileDocument
Protocol
ReferenceFileDocument
A type that you use to serialize reference type documents to and from file.
@preconcurrency protocol ReferenceFileDocument : ObservableObject, Sendable
Overview
To store a document as a reference type — like a class — create a type that conforms to the ReferenceFileDocument protocol and implement the required methods and properties. Your implementation:
-
Provides a list of the content types that the document can read from and write to by defining
readableContentTypes. If the list of content types that the document can write to is different from those that it reads from, you can optionally also definewritableContentTypes. -
Loads documents from file in the
init(configuration:)initializer. -
Stores documents to file by providing a snapshot of the document’s content in the
snapshot(contentType:)method, and then serializing that content in thefileWrapper(snapshot:configuration:)method.
Ensure that types that conform to this protocol are Sendable. In particular, SwiftUI calls the protocol’s methods from different isolation domains. Don’t perform serialization and deserialization on MainActor.
final class PDFDocument: ReferenceFileDocument { struct Storage { var contents: Data }
static let readableContentTypes: [UTType] = [.pdf]
guard let data = configuration.file.regularFileContents else { throw CocoaError(.fileReadCorruptFile) } self.storage = .init(.init(contents: data)) }
storage.withLock { $0.contents } }
return FileWrapper(regularFileWithContents: snapshot) } }
Topics
Reading a document
init(configuration: Self.ReadConfiguration) throws
Creates a document and initializes it with the contents of a file.
Required
static var readableContentTypes: [UTType]
The file and data types that the document reads from.
typealias ReadConfiguration
The configuration for reading document contents.
Getting a snapshot
Creates a snapshot that represents the current state of the document.
associatedtype Snapshot
A type that represents the document’s stored content.
Writing a document
Serializes a document snapshot to a file wrapper.
static var writableContentTypes: [UTType]
The file types that the document supports saving or exporting to.
Required Default implementation provided.
typealias WriteConfiguration
The configuration for writing document contents.
Relationships
Inherits From
ObservableObjectSendableSendableMetatype
See Also
Storing document data in a class instance
struct ReferenceFileDocumentConfiguration
The properties of an open reference file document.
var undoManager: UndoManager?
The undo manager used to register a view’s undo operations.
https://developer.apple.com/documentation/swiftui/documentgroup/init(editing:contenttype:editor:preparedocument:)
#app-main)
- SwiftUI
- DocumentGroup
- init(editing:contentType:editor:prepareDocument:)
Initializer
init(editing:contentType:editor:prepareDocument:)
Instantiates a document group for creating and editing documents that store a specific model type.
SwiftDataSwiftUI
init( editing modelType: any PersistentModel.Type, contentType: UTType,
)
Available when Document is ModelDocument and Content conforms to View.
Show all declarations
Parameters
modelType
The model type defining the schema used for each document.
contentType
The content type of the document. It should conform to UTType.package.
editor
The editing UI for the provided document.
prepareDocument
The optional closure that accepts ModelContext associated with the new document. Use this closure to set the document’s initial contents before it is displayed: insert preconfigured models in the provided ModelContext.
Discussion
@main struct Todo: App { var body: some Scene { DocumentGroup(editing: TodoItem.self, contentType: .todoItem) { ContentView() } } }
struct ContentView: View { @Query var items: [TodoItem]
var body: some View { List { ForEach(items) { item in @Bindable var item = item Toggle(item.text, isOn: $item.isDone) } } } }
@Model final class TodoItem { var created: Date var text: String var isDone = false }
extension UTType { static var todoItem = UTType(exportedAs: "com.myApp.todoItem") }
See Also
Editing a document backed by a persistent store
Instantiates a document group for creating and editing documents described by the last Schema in the migration plan.
https://developer.apple.com/documentation/swiftui/building-a-document-based-app-with-swiftui
- SwiftUI
- Documents
- Building a document-based app with SwiftUI
Sample Code
Building a document-based app with SwiftUI
Create, save, and open documents in a multiplatform app.
Download
Xcode 16.0+
Overview
The Writing App sample builds a document-based app for iOS, iPadOS, and macOS. In the app definition, it has a DocumentGroup scene, and its document type conforms to the FileDocument protocol. People can create a writing app document, modify the title and contents of the document, and read the story in focus mode.
Configure the sample code project
To build and run this sample on your device, select your development team for the project’s target using these steps:
-
Open the sample with the latest version of Xcode.
-
Select the top-level project.
-
For the project’s target, choose your team from the Team pop-up menu in the Signing & Capabilities pane to let Xcode automatically manage your provisioning profile.
Define the app’s scene
A document-based SwiftUI app returns a DocumentGroup scene from its body property. The newDocument parameter that an app supplies to the document group’s init(newDocument:editor:) initializer conforms to either FileDocument or ReferenceFileDocument. In this sample, the document type conforms to FileDocument. The trailing closure of the initializer returns a view that renders the document’s contents:
@main struct WritingApp: App { var body: some Scene { DocumentGroup(newDocument: WritingAppDocument()) { file in StoryView(document: file.$document) } } }
Customize the iOS and iPadOS launch experience
You can update the default launch experience on iOS and iPadOS with a custom title, action buttons, and screen background. To add an action button with a custom label, use NewDocumentButton to replace the default label. You can customize the background in many ways such as adding a view or a backgroundStyle with an initializer, for example init(_:backgroundStyle:_:backgroundAccessoryView:overlayAccessoryView:). This sample customizes the background of the title view, using the init(_:_:background:) initializer:
DocumentGroupLaunchScene("Writing App") { NewDocumentButton("Start Writing") } background: { Image(.pinkJungle) .resizable() .scaledToFill() .ignoresSafeArea() }
You can also add accessories to the scene using initializers such as init(_:_:background:backgroundAccessoryView:) and init(_:_:background:overlayAccessoryView:) depending on the positioning.
overlayAccessoryView: { _ in AccessoryView() }
This sample contains two accessories in the overlay position that it defines in AccessoryView. It customizes the accessories by applying modifiers, including offset(x:y:) and frame(width:height:alignment:).
ZStack { Image(.robot) .resizable() .offset(x: size.width / 2 - 450, y: size.height / 2 - 300) .scaledToFit() .frame(width: 200) .opacity(horizontal == .compact ? 0 : 1) Image(.plant) .resizable() .offset(x: size.width / 2 + 250, y: size.height / 2 - 225) .scaledToFit() .frame(width: 200) .opacity(horizontal == .compact ? 0 : 1) }
To add both background and overlay accessories, use an initializer, such as init(_:_:background:backgroundAccessoryView:overlayAccessoryView:). If you don’t provide any accessories, the system displays two faded sheets below the title view by default. In macOS, this sample displays the default system document browser on launch. You may wish to add an additional experience on launch.
Create the data model
This sample has a data model that defines a story as a String, it initializes story with an empty string:
var story: String
init(text: String = "") { self.story = text }
Adopt the file document protocol
The WritingAppDocument structure adopts the FileDocument protocol to serialize documents to and from files. The readableContentTypes property defines the types that the sample can read and write, specifically, the .writingAppDocument type:
static var readableContentTypes: [UTType] { [.writingAppDocument] }
The init(configuration:) initializer loads documents from a file. After reading the file’s data using the file property of the configuration input, it deserializes the data and stores it in the document’s data model:
init(configuration: ReadConfiguration) throws { guard let data = configuration.file.regularFileContents, let string = String(data: data, encoding: .utf8) else { throw CocoaError(.fileReadCorruptFile) } story = string }
When a person writes a document, SwiftUI calls the fileWrapper(configuration:) function to serialize the data model into a FileWrapper value that represents the data in the file system:
let data = Data(story.utf8) return .init(regularFileWithContents: data) }
Because the document type conforms to FileDocument, this sample handles undo actions automatically.
Export a custom document type
The app defines and exports a custom content type for the documents it creates. It declares this custom type in the project’s Information Property List file under the UTExportedTypeDeclarations key. This sample uses com.example.writingAppDocument as the identifier in the Info.plist file:
For convenience, you can also define the content type in code. For example:
extension UTType { static var writingapp: UTType { UTType(exportedAs: "com.example.writingAppDocument") } }
To make sure that the operating system knows that your application can open files with the format described in the Info.plist, it defines the file extension story for the content type. For more information about custom file and data types, see Defining file and data types for your app.
See Also
Related samples
Building a document-based app using SwiftData
Code along with the WWDC presenter to transform an app with SwiftData.
Related articles
Defining file and data types for your app
Declare uniform type identifiers to support your app’s proprietary data formats.
Customizing a document-based app’s launch experience
Add unique elements to your app’s document launch scene.
Related videos
https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata
- SwiftUI
- Documents
- Building a document-based app using SwiftData
Sample Code
Building a document-based app using SwiftData
Code along with the WWDC presenter to transform an app with SwiftData.
Download
Xcode 15.0+
Overview
Learn how to use @Query, @Bindable, .modelContainer, the .modelContext environment variable, and DocumentGroup to integrate with the SwiftData framework.
See Also
Creating a document
Building a document-based app with SwiftUI
Create, save, and open documents in a multiplatform app.
struct DocumentGroup
A scene that enables support for opening, creating, and saving documents.
https://developer.apple.com/documentation/swiftui/filedocumentconfiguration
- SwiftUI
- FileDocumentConfiguration
Structure
FileDocumentConfiguration
The properties of an open file document.
Overview
You receive an instance of this structure when you create a DocumentGroup with a value file type. Use it to access the document in your viewer or editor.
Topics
Getting and setting the document
var document: Document
The current document model.
Getting document properties
var fileURL: URL?
The URL of the open file document.
var isEditable: Bool
A Boolean that indicates whether you can edit the document.
See Also
Storing document data in a structure instance
protocol FileDocument
A type that you use to serialize documents to and from file.
https://developer.apple.com/documentation/swiftui/referencefiledocumentconfiguration
- SwiftUI
- ReferenceFileDocumentConfiguration
Structure
ReferenceFileDocumentConfiguration
The properties of an open reference file document.
@MainActor @preconcurrency
Overview
You receive an instance of this structure when you create a DocumentGroup with a reference file type. Use it to access the document in your viewer or editor.
Topics
Getting and setting the document
var document: Document
The current document model.
Getting document properties
var fileURL: URL?
The URL of the open file document.
var isEditable: Bool
A Boolean that indicates whether you can edit the document.
See Also
Storing document data in a class instance
protocol ReferenceFileDocument
A type that you use to serialize reference type documents to and from file.
var undoManager: UndoManager?
The undo manager used to register a view’s undo operations.
https://developer.apple.com/documentation/swiftui/environmentvalues/undomanager
- SwiftUI
- EnvironmentValues
- undoManager
Instance Property
undoManager
The undo manager used to register a view’s undo operations.
var undoManager: UndoManager? { get }
Discussion
This value is nil when the environment represents a context that doesn’t support undo and redo operations. You can skip registration of an undo operation when this value is nil.
See Also
Storing document data in a class instance
protocol ReferenceFileDocument
A type that you use to serialize reference type documents to and from file.
struct ReferenceFileDocumentConfiguration
The properties of an open reference file document.
https://developer.apple.com/documentation/swiftui/environmentvalues/documentconfiguration
- SwiftUI
- EnvironmentValues
- documentConfiguration
Instance Property
documentConfiguration
The configuration of a document in a DocumentGroup.
var documentConfiguration: DocumentConfiguration? { get }
Discussion
The value is nil for views that are not enclosed in a DocumentGroup.
For example, if the app shows the document path in the footer of each document, it can get the URL from the environment:
struct ContentView: View { @Binding var document: TextDocument @Environment(.documentConfiguration) private var configuration: DocumentConfiguration?
var body: some View { … Label( configuration?.fileURL?.path ?? "", systemImage: "folder.circle" ) } }
See Also
Accessing document configuration
struct DocumentConfiguration
https://developer.apple.com/documentation/swiftui/documentconfiguration
- SwiftUI
- DocumentConfiguration
Structure
DocumentConfiguration
struct DocumentConfiguration
Topics
Getting configuration values
var fileURL: URL?
A URL of an open document.
var isEditable: Bool
A Boolean value that indicates whether you can edit the document.
Relationships
Conforms To
SendableSendableMetatype
See Also
Accessing document configuration
var documentConfiguration: DocumentConfiguration?
The configuration of a document in a DocumentGroup.
https://developer.apple.com/documentation/swiftui/filedocumentreadconfiguration
- SwiftUI
- FileDocumentReadConfiguration
Structure
FileDocumentReadConfiguration
The configuration for reading file contents.
struct FileDocumentReadConfiguration
Topics
Reading the content
let contentType: UTType
The expected uniform type of the file contents.
let file: FileWrapper
The file wrapper containing the document content.
See Also
Reading and writing documents
struct FileDocumentWriteConfiguration
The configuration for serializing file contents.
https://developer.apple.com/documentation/swiftui/filedocumentwriteconfiguration
- SwiftUI
- FileDocumentWriteConfiguration
Structure
FileDocumentWriteConfiguration
The configuration for serializing file contents.
struct FileDocumentWriteConfiguration
Topics
Writing the content
let contentType: UTType
The expected uniform type of the file contents.
let existingFile: FileWrapper?
The file wrapper containing the current document content. nil if the document is unsaved.
See Also
Reading and writing documents
struct FileDocumentReadConfiguration
The configuration for reading file contents.
https://developer.apple.com/documentation/swiftui/environmentvalues/newdocument
- SwiftUI
- EnvironmentValues
- newDocument
Instance Property
newDocument
An action in the environment that presents a new document.
var newDocument: NewDocumentAction { get }
Discussion
Use the newDocument environment value to get the instance of the NewDocumentAction structure for a given Environment. Then call the instance to present a new document. You call the instance directly because it defines a callAsFunction(_:) method that Swift calls when you call the instance.
For example, you can define a button that creates a new document from the selected text:
struct NewDocumentFromSelection: View { @FocusedBinding(.selectedText) private var selectedText: String? @Environment(.newDocument) private var newDocument
var body: some View { Button("New Document With Selection") { newDocument(TextDocument(text: selectedText)) } .disabled(selectedText?.isEmpty != false) } }
The above example assumes that you define a TextDocument that conforms to the FileDocument or ReferenceFileDocument protocol, and a DocumentGroup that handles the associated file type.
See Also
Opening a document programmatically
struct NewDocumentAction
An action that presents a new document.
var openDocument: OpenDocumentAction
An action in the environment that presents an existing document.
struct OpenDocumentAction
An action that presents an existing document.
https://developer.apple.com/documentation/swiftui/newdocumentaction
- SwiftUI
- NewDocumentAction
Structure
NewDocumentAction
An action that presents a new document.
@MainActor @preconcurrency struct NewDocumentAction
Overview
Use the newDocument environment value to get the instance of this structure for a given Environment. Then call the instance to present a new document. You call the instance directly because it defines a callAsFunction(_:) method that Swift calls when you call the instance.
For example, you can define a button that creates a new document from the selected text:
struct NewDocumentFromSelection: View { @FocusedBinding(.selectedText) private var selectedText: String? @Environment(.newDocument) private var newDocument
var body: some View { Button("New Document With Selection") { newDocument(TextDocument(text: selectedText)) } .disabled(selectedText?.isEmpty != false) } }
The above example assumes that you define a TextDocument that conforms to the FileDocument or ReferenceFileDocument protocol, and a DocumentGroup that handles the associated file type.
Topics
Calling the action
func callAsFunction(_:)
Presents a new document window.
func callAsFunction(contentType: UTType)
Presents a new document window with preset contents.
Relationships
Conforms To
SendableSendableMetatype
See Also
Opening a document programmatically
var newDocument: NewDocumentAction
An action in the environment that presents a new document.
var openDocument: OpenDocumentAction
An action in the environment that presents an existing document.
struct OpenDocumentAction
An action that presents an existing document.
https://developer.apple.com/documentation/swiftui/environmentvalues/opendocument
- SwiftUI
- EnvironmentValues
- openDocument
Instance Property
openDocument
An action in the environment that presents an existing document.
var openDocument: OpenDocumentAction { get }
Discussion
Use the openDocument environment value to get the instance of the OpenDocumentAction structure for a given Environment. Then call the instance to present an existing document. You call the instance directly because it defines a callAsFunction(at:) method that Swift calls when you call the instance.
For example, you can create a button that opens the document at the specified URL:
struct OpenDocumentButton: View { var url: URL @Environment(.openDocument) private var openDocument
var body: some View { Button(url.deletingPathExtension().lastPathComponent) { Task { do { try await openDocument(at: url) } catch { // Handle error } } } } }
The above example uses a do-catch statement to handle any errors that the open document action might throw. It also places the action inside a task and awaits the result because the action operates asynchronously.
To present an existing document, your app must define a DocumentGroup that handles the content type of the specified file. For a document that’s already open, the system brings the existing window to the front. Otherwise, the system opens a new window.
See Also
Opening a document programmatically
var newDocument: NewDocumentAction
An action in the environment that presents a new document.
struct NewDocumentAction
An action that presents a new document.
struct OpenDocumentAction
An action that presents an existing document.
https://developer.apple.com/documentation/swiftui/opendocumentaction
- SwiftUI
- OpenDocumentAction
Structure
OpenDocumentAction
An action that presents an existing document.
@MainActor struct OpenDocumentAction
Overview
Use the openDocument environment value to get the instance of this structure for a given Environment. Then call the instance to present an existing document. You call the instance directly because it defines a callAsFunction(at:) method that Swift calls when you call the instance.
For example, you can create a button that opens the document at the specified URL:
struct OpenDocumentButton: View { var url: URL @Environment(.openDocument) private var openDocument
var body: some View { Button(url.deletingPathExtension().lastPathComponent) { Task { do { try await openDocument(at: url) } catch { // Handle error } } } } }
The above example uses a do-catch statement to handle any errors that the open document action might throw. It also places the action inside a task and awaits the result because the action operates asynchronously.
To present an existing document, your app must define a DocumentGroup that handles the content type of the specified file. For a document that’s already open, the system brings the existing window to the front. Otherwise, the system opens a new window.
Topics
Calling the action
func callAsFunction(at: URL) async throws
Opens the document at the specified file URL.
Relationships
Conforms To
SendableSendableMetatype
See Also
Opening a document programmatically
var newDocument: NewDocumentAction
An action in the environment that presents a new document.
struct NewDocumentAction
An action that presents a new document.
var openDocument: OpenDocumentAction
An action in the environment that presents an existing document.
https://developer.apple.com/documentation/swiftui/documentgrouplaunchscene
- SwiftUI
- DocumentGroupLaunchScene
Structure
DocumentGroupLaunchScene
A launch scene for document-based applications.
Overview
You can use this launch scene alongside DocumentGroup scenes. If you don’t implement a DocumentGroup in the app declaration, you can get the same design by implementing a DocumentLaunchView.
If you don’t provide the title of the scene, it displays the application name. If you don’t provide the actions builder, the scene has the default “Create Document” action that creates new documents. To customize the document launch experience, you can replace the standard screen background and title, add decorative views, and add custom actions.
A DocumentGroupLaunchScene configures the document browser on the bottom sheet to open content types from all the document groups in the app definition. A DocumentGroupLaunchScene also configures the document groups to create documents of the first content type that your application can create and write.
For more information, see FileDocument.writableContentTypes and ReferenceFileDocument.writableContentTypes.
Topics
Initializers
init(_:_:background:)
Creates a launch scene for document-based applications with a title, a set of actions, and a background.
init(_:_:background:backgroundAccessoryView:)
Creates a launch scene for document-based applications with a title, a set of actions, a background, and a background accessory view.
init(_:_:background:backgroundAccessoryView:overlayAccessoryView:)
init(_:_:background:overlayAccessoryView:)
Creates a launch scene for document-based applications with a title, a set of actions, a background, and an overlay accessory view.
init(_:backgroundStyle:_:)
Creates a launch scene for document-based applications with a title, a background style, and a set of actions.
init(_:backgroundStyle:_:backgroundAccessoryView:)
Creates a launch scene for document-based applications with a title, a background style, a set of actions, and a background accessory view.
init(_:backgroundStyle:_:backgroundAccessoryView:overlayAccessoryView:)
Creates a launch scene for document-based applications with a title, a background style, a set of actions, and background and overlay accessory views.
init(_:backgroundStyle:_:overlayAccessoryView:)
Creates a launch scene for document-based applications with a title, a background style, a set of actions, and an overlay accessory view.
Relationships
Conforms To
Scene
See Also
Configuring the document launch experience
struct DocumentLaunchView
A view to present when launching document-related user experience.
struct DocumentLaunchGeometryProxy
A proxy for access to the frame of the scene and its title view.
struct DefaultDocumentGroupLaunchActions
The default actions for the document group launch scene and the document launch view.
struct NewDocumentButton
A button that creates and opens new documents.
protocol DocumentBaseBox
A Box that allows setting its Document base not requiring the caller to know the exact types of the box and its base.
https://developer.apple.com/documentation/swiftui/documentlaunchview
- SwiftUI
- DocumentLaunchView
Structure
DocumentLaunchView
A view to present when launching document-related user experience.
Overview
Configure DocumentLaunchView to open and display files and trigger custom actions.
For example, an application that offers writing books can present the DocumentLaunchView as its launch view:
public import UniformTypeIdentifiers
struct BookEditorLaunchView: View {
var body: some View { DocumentLaunchView(for: [.book]) { NewDocumentButton("Start New Book") } onDocumentOpen: { url in BookEditor(url) } } }
struct BookEditor: View { init(_ url: URL) { } }
extension UTType { static var book = UTType(exportedAs: "com.example.bookEditor") }
Topics
Initializers
init(_:for:_:onDocumentOpen:)
Creates a view to present when launching document-related user experiences using a localized title and custom actions.
init(_:for:_:onDocumentOpen:background:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, and a background view.
init(_:for:_:onDocumentOpen:background:backgroundAccessoryView:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, a background view, and a background accessory view.
init(_:for:_:onDocumentOpen:background:backgroundAccessoryView:overlayAccessoryView:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, a background view, and accessory views.
init(_:for:_:onDocumentOpen:background:overlayAccessoryView:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, a background view, and an overlay accessory view.
init(_:for:_:onDocumentOpen:backgroundAccessoryView:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, and a background accessory view.
init(_:for:_:onDocumentOpen:backgroundAccessoryView:overlayAccessoryView:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, and accessory views.
init(_:for:_:onDocumentOpen:overlayAccessoryView:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, and an overlay accessory view.
init(_:for:backgroundStyle:_:onDocumentOpen:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, and a background style.
init(_:for:backgroundStyle:_:onDocumentOpen:backgroundAccessoryView:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, a background style, and a background accessory view.
init(_:for:backgroundStyle:_:onDocumentOpen:backgroundAccessoryView:overlayAccessoryView:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, a background style, and accessory views.
init(_:for:backgroundStyle:_:onDocumentOpen:overlayAccessoryView:)
Creates a view to present when launching document-related user experiences using a localized title, custom actions, a background style, and an overlay accessory view.
Instance Properties
var body: some View
The body of the view.
Relationships
Conforms To
View
See Also
Configuring the document launch experience
struct DocumentGroupLaunchScene
A launch scene for document-based applications.
struct DocumentLaunchGeometryProxy
A proxy for access to the frame of the scene and its title view.
struct DefaultDocumentGroupLaunchActions
The default actions for the document group launch scene and the document launch view.
struct NewDocumentButton
A button that creates and opens new documents.
protocol DocumentBaseBox
A Box that allows setting its Document base not requiring the caller to know the exact types of the box and its base.
https://developer.apple.com/documentation/swiftui/documentlaunchgeometryproxy
- SwiftUI
- DocumentLaunchGeometryProxy
Structure
DocumentLaunchGeometryProxy
A proxy for access to the frame of the scene and its title view.
struct DocumentLaunchGeometryProxy
Topics
Instance Properties
var frame: CGRect
Frame of the document launch interface.
var titleViewFrame: CGRect
Frame of the title view within the interface.
See Also
Configuring the document launch experience
struct DocumentGroupLaunchScene
A launch scene for document-based applications.
struct DocumentLaunchView
A view to present when launching document-related user experience.
struct DefaultDocumentGroupLaunchActions
The default actions for the document group launch scene and the document launch view.
struct NewDocumentButton
A button that creates and opens new documents.
protocol DocumentBaseBox
A Box that allows setting its Document base not requiring the caller to know the exact types of the box and its base.
https://developer.apple.com/documentation/swiftui/defaultdocumentgrouplaunchactions
- SwiftUI
- DefaultDocumentGroupLaunchActions
Structure
DefaultDocumentGroupLaunchActions
The default actions for the document group launch scene and the document launch view.
struct DefaultDocumentGroupLaunchActions
Overview
This View populates DocumentGroupLaunchScene and DocumentLaunchView with the default actions.
Topics
Initializers
init()
Relationships
Conforms To
View
See Also
Configuring the document launch experience
struct DocumentGroupLaunchScene
A launch scene for document-based applications.
struct DocumentLaunchView
A view to present when launching document-related user experience.
struct DocumentLaunchGeometryProxy
A proxy for access to the frame of the scene and its title view.
struct NewDocumentButton
A button that creates and opens new documents.
protocol DocumentBaseBox
A Box that allows setting its Document base not requiring the caller to know the exact types of the box and its base.
https://developer.apple.com/documentation/swiftui/newdocumentbutton
- SwiftUI
- NewDocumentButton
Structure
NewDocumentButton
A button that creates and opens new documents.
Overview
Use a new document button to give people the option to create documents in your app. In the following example, there are two new document buttons, both support Text labels. When the user taps or clicks the first button, the system creates a new document in the directory currently open in the document browser. The second button creates a new document from a template.
@State private var isTemplatePickerPresented = false @State private var documentCreationContinuation:
var body: some Scene { DocumentGroupLaunchScene("My Documents") { NewDocumentButton("Start Writing…") NewDocumentButton("Choose a Template", for: MyDocument.self) { try await withCheckedThrowingContinuation { continuation in documentCreationContinuation = continuation isTemplatePickerPresented = true } } .fullScreenCover(isPresented: $isTemplatePickerPresented) { TemplatePicker(continuation: $documentCreationContinuation) } } }
If you don’t provide a custom label, the system provides a button with the default “Create Document” label.
Topics
Initializers
init(_:contentType:)
Creates and opens new documents.
init(_:contentType:prepareDocumentURL:)
init(_:for:contentType:prepareDocument:)
Relationships
Conforms To
View
See Also
Configuring the document launch experience
struct DocumentGroupLaunchScene
A launch scene for document-based applications.
struct DocumentLaunchView
A view to present when launching document-related user experience.
struct DocumentLaunchGeometryProxy
A proxy for access to the frame of the scene and its title view.
struct DefaultDocumentGroupLaunchActions
The default actions for the document group launch scene and the document launch view.
protocol DocumentBaseBox
A Box that allows setting its Document base not requiring the caller to know the exact types of the box and its base.
https://developer.apple.com/documentation/swiftui/documentbasebox
- SwiftUI
- DocumentBaseBox
Protocol
DocumentBaseBox
A Box that allows setting its Document base not requiring the caller to know the exact types of the box and its base.
Topics
Associated Types
associatedtype Document
The underlying document type.
Required
Instance Properties
var base: Self.Document?
Updates the underlying document to a new value.
See Also
Configuring the document launch experience
struct DocumentGroupLaunchScene
A launch scene for document-based applications.
struct DocumentLaunchView
A view to present when launching document-related user experience.
struct DocumentLaunchGeometryProxy
A proxy for access to the frame of the scene and its title view.
struct DefaultDocumentGroupLaunchActions
The default actions for the document group launch scene and the document launch view.
struct NewDocumentButton
A button that creates and opens new documents.
https://developer.apple.com/documentation/swiftui/renamebutton
- SwiftUI
- RenameButton
Structure
RenameButton
A button that triggers a standard rename action.
Overview
A rename button receives its action from the environment. Use the renameAction(_:) modifier to set the action. The system disables the button if you don’t define an action.
struct RowView: View { @State private var text = "" @FocusState private var isFocused: Bool
var body: some View { TextField(text: $item.name) { Text("Prompt") } .focused($isFocused) .contextMenu { RenameButton() // ... your own custom actions } .renameAction { $isFocused = true } }
When someone taps the rename button in the context menu, the rename action focuses the text field by setting the isFocused property to true.
You can use this button inside of a navigation title menu and the navigation title modifier automatically configures the environment with the appropriate rename action.
ContentView() .navigationTitle($contentTitle) { // ... your own custom actions RenameButton() }
Topics
Creating an rename button
init()
Creates a rename button.
Relationships
Conforms To
View
See Also
Creating special-purpose buttons
struct EditButton
A button that toggles the edit mode environment value.
struct PasteButton
A system button that reads items from the pasteboard and delivers it to a closure.
https://developer.apple.com/documentation/swiftui/view/renameaction(_:)
https://developer.apple.com/documentation/swiftui/environmentvalues/rename
- SwiftUI
- EnvironmentValues
- rename
Instance Property
rename
An action that activates the standard rename interaction.
var rename: RenameAction? { get }
Discussion
Use the renameAction(_:) modifier to configure the rename action in the environment.
See Also
Renaming a document
struct RenameButton
A button that triggers a standard rename action.
func renameAction(_:)
Sets a closure to run for the rename action.
struct RenameAction
An action that activates a standard rename interaction.
https://developer.apple.com/documentation/swiftui/renameaction
- SwiftUI
- RenameAction
Structure
RenameAction
An action that activates a standard rename interaction.
struct RenameAction
Overview
Use the renameAction(_:) modifier to configure the rename action in the environment.
Topics
Calling the action
func callAsFunction()
Triggers the standard rename action provided through the environment.
See Also
Renaming a document
struct RenameButton
A button that triggers a standard rename action.
func renameAction(_:)
Sets a closure to run for the rename action.
var rename: RenameAction?
An action that activates the standard rename interaction.
https://developer.apple.com/documentation/swiftui/documentgroup)
https://developer.apple.com/documentation/swiftui/filedocument)
https://developer.apple.com/documentation/swiftui/referencefiledocument)
https://developer.apple.com/documentation/swiftui/documentgroup/init(editing:contenttype:editor:preparedocument:)).
).#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/filedocumentconfiguration)
https://developer.apple.com/documentation/swiftui/referencefiledocumentconfiguration)
https://developer.apple.com/documentation/swiftui/environmentvalues/undomanager)
https://developer.apple.com/documentation/swiftui/environmentvalues/documentconfiguration)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/documentgroup).
https://developer.apple.com/documentation/swiftui/documentconfiguration)
https://developer.apple.com/documentation/swiftui/filedocumentreadconfiguration)
https://developer.apple.com/documentation/swiftui/filedocumentwriteconfiguration)
https://developer.apple.com/documentation/swiftui/environmentvalues/newdocument)
https://developer.apple.com/documentation/swiftui/newdocumentaction)
https://developer.apple.com/documentation/swiftui/environmentvalues/opendocument)
https://developer.apple.com/documentation/swiftui/opendocumentaction)
https://developer.apple.com/documentation/swiftui/documentgrouplaunchscene)
https://developer.apple.com/documentation/swiftui/documentlaunchview)
https://developer.apple.com/documentation/swiftui/documentlaunchgeometryproxy)
https://developer.apple.com/documentation/swiftui/defaultdocumentgrouplaunchactions)
https://developer.apple.com/documentation/swiftui/newdocumentbutton)
https://developer.apple.com/documentation/swiftui/documentbasebox)
https://developer.apple.com/documentation/swiftui/renamebutton)
https://developer.apple.com/documentation/swiftui/view/renameaction(_:))
https://developer.apple.com/documentation/swiftui/environmentvalues/rename)
https://developer.apple.com/documentation/swiftui/renameaction)
https://developer.apple.com/documentation/swiftui/windowgroup
- SwiftUI
- WindowGroup
Structure
WindowGroup
A scene that presents a group of identically structured windows.
Mentioned in
Building and customizing the menu bar with SwiftUI
Overview
Use a WindowGroup as a container for a view hierarchy that your app presents. The hierarchy that you declare as the group’s content serves as a template for each window that the app creates from that group:
@main struct Mail: App { var body: some Scene { WindowGroup { MailViewer() // Define a view hierarchy for the window. } } }
SwiftUI takes care of certain platform-specific behaviors. For example, on platforms that support it, like macOS and iPadOS, people can open more than one window from the group simultaneously. In macOS, people can gather open windows together in a tabbed interface. Also in macOS, window groups automatically provide commands for standard window management.
Every window in the group maintains independent state. For example, the system allocates new storage for any State or StateObject variables instantiated by the scene’s view hierarchy for each window that it creates.
For document-based apps, use DocumentGroup to define windows instead.
Open windows programmatically
If you initialize a window group with an identifier, a presentation type, or both, you can programmatically open a window from the group. For example, you can give the mail viewer scene from the previous example an identifier:
WindowGroup(id: "mail-viewer") { // Identify the window group. MailViewer() }
Elsewhere in your code, you can use the openWindow action from the environment to create a new window from the group:
struct NewViewerButton: View { @Environment(.openWindow) private var openWindow
var body: some View { Button("Open new mail viewer") { openWindow(id: "mail-viewer") // Match the group's identifier. } } }
Be sure to use unique strings for identifiers that you apply to window groups in your app.
Present data in a window
If you initialize a window group with a presentation type, you can pass data of that type to the window when you open it. For example, you can define a second window group for the Mail app that displays a specified message:
@main struct Mail: App { var body: some Scene { WindowGroup { MailViewer(id: "mail-viewer") }
// A window group that displays messages. WindowGroup(for: Message.ID.self) { $messageID in MessageDetail(messageID: messageID) } } }
When you call the openWindow action with a value, SwiftUI finds the window group with the matching type and passes a binding to the value into the window group’s content closure. For example, you can define a button that opens a message by passing the message’s identifier:
struct NewMessageButton: View { var message: Message @Environment(.openWindow) private var openWindow
var body: some View { Button("Open message") { openWindow(value: message.id) } } }
Be sure that the type you present conforms to both the Hashable and Codable protocols. Also, prefer lightweight data for the presentation value. For model values that conform to the Identifiable protocol, the value’s identifier works well as a presentation type, as the above example demonstrates.
WindowGroup(for: Message.ID.self) { $messageID in MessageDetail(messageID: messageID) } defaultValue: { model.makeNewMessage().id // A new message that your model stores. }
SwiftUI persists the value of the binding for the purposes of state restoration, and reapplies the same value when restoring the window. If the restoration process results in an error, SwiftUI sets the binding to the default value if you provide one, or nil otherwise.
Title your app’s windows
To help people distinguish among windows from different groups, include a title as the first parameter in the group’s initializer:
WindowGroup("Message", for: Message.ID.self) { $messageID in MessageDetail(messageID: messageID) }
SwiftUI uses this title when referring to the window in:
-
The window’s title bar.
-
The list of open windows that the Window menu displays.
If you don’t provide a title for a window, the system refers to the window using the app’s name instead.
Distinguish windows that present like data
To programmatically distinguish between windows that present the same type of data, like when you use a UUID as the identifier for more than one model type, add the id parameter to the group’s initializer to provide a unique string identifier:
WindowGroup("Message", id: "message", for: UUID.self) { $uuid in MessageDetail(uuid: uuid) } WindowGroup("Account", id: "account-info", for: UUID.self) { $uuid in AccountDetail(uuid: uuid) }
Then use both the identifer and a value to open the window:
struct ActionButtons: View { var messageID: UUID var accountID: UUID
@Environment(.openWindow) private var openWindow
var body: some View { HStack { Button("Open message") { openWindow(id: "message", value: messageID) } Button("Edit account information") { openWindow(id: "account-info", value: accountID) } } } }
Dismiss a window programmatically
The system provides people with platform-appropriate controls to dismiss a window. You can also dismiss windows programmatically by calling the dismiss action from within the window’s view hierarchy. For example, you can include a button in the account detail view from the previous example that dismisses the view:
struct AccountDetail: View { var uuid: UUID? @Environment(.dismiss) private var dismiss
var body: some View { VStack { // ...
Button("Dismiss") { dismiss() } } } }
The dismiss action doesn’t close the window if you call it from a modal — like a sheet or a popover — that you present from the window. In that case, the action dismisses the modal presentation instead.
Topics
Creating a window group
Creates a window group.
Deprecated
init(_:content:)
Creates a window group with a text view title.
Identifying a window group
Creates a window group with an identifier.
init(_:id:content:)
Creates a window group with a text view title and an identifier.
Creating a data-driven window group
Creates a data-presenting window group.
init(_:for:content:)
Creates a data-presenting window group with a text view title.
Providing default data to a window group
Creates a data-presenting window group with a default value.
init(_:for:content:defaultValue:)
Creates a data-presenting window group with a text view title and a default value.
Identifying a data-driven window group
Creates a data-presenting window group with an identifier.
init(_:id:for:content:)
Creates a data-presenting window group with a text view title and an identifier.
Identifying a window group that has default data
Creates a data-presenting window group with an identifier and a default value.
init(_:id:for:content:defaultValue:)
Creates a data-presenting window group with a text view title, an identifier, and a default value.
Supporting types
struct PresentedWindowContent
A view that represents the content of a presented window.
Initializers
init(_:id:makeContent:)
init(_:makeContent:)
Relationships
Conforms To
Scene
See Also
Creating windows
struct Window
A scene that presents its content in a single, unique window.
struct UtilityWindow
A specialized window scene that provides secondary utility to the content of the main scenes of an application.
protocol WindowStyle
A specification for the appearance and interaction of a window.
Sets the style for windows created by this scene.
https://developer.apple.com/documentation/swiftui/window
- SwiftUI
- Window
Structure
Window
A scene that presents its content in a single, unique window.
Overview
Use a Window scene to augment the main interface of your app with a window that gives people access to supplemental functionality. For example, you can create a secondary window in a mail reader app that enables people to view the status of their account connections:
@main struct Mail: App { var body: some Scene { WindowGroup { MailViewer() } Window("Connection Doctor", id: "connection-doctor") { ConnectionDoctor() } } }
Provide a title as the first argument to the window’s intializer. The system uses the title to identify the window to people using your app in the window’s title bar or in the list of available singleton windows that the Windows menu displays automatically.
Open a window programmatically
People open the window by selecting it in the Windows menu, but you can also open the window programmatically using the openWindow action that you read from the environment. Use the id parameter that you initialize the window with to indicate which window to open. For example, you can create a button to open the window from the previous example:
struct OpenConnectionDoctorButton: View { @Environment(.openWindow) private var openWindow
var body: some View { Button("Connection doctor") { openWindow(id: "connection-doctor") // Match the window's identifier. } } }
If the window is already open when you call this action, the action brings the open window to the front. Be sure to use unique identifiers across all of the Window and WindowGroup instances that you define.
Dismiss a window programmatically
The system provides people with controls to close windows, but you can also close a window programmatically using the dismiss action from within the window’s view hierarchy. For example, you can include a button in the connection doctor view that dismisses the view:
struct ConnectionDoctor: View { @Environment(.dismiss) private var dismiss
var body: some View { VStack { // ...
Button("Dismiss") { dismiss() } } } }
The dismiss action doesn’t close the window if you call it from a modal — like a sheet or a popover — that you present from within the window. In that case, the action dismisses the modal presentation instead.
Use a window as the main scene
You can use a window as the main scene of your app when multi-window functionality isn’t appropriate. For example, it might not make sense to display more than one window for a video call app that relies on a hardware resource, like a camera:
@main struct VideoCall: App { var body: some Scene { Window("VideoCall", id: "main") { CameraView() } } }
If your app uses a single window as its primary scene, the app quits when the window closes. This behavior differs from an app that uses a WindowGroup as its primary scene, where the app continues to run even after closing all of its windows.
Topics
Creating a window
init(_:id:content:)
Creates a window with a title and an identifier.
Relationships
Conforms To
Scene
See Also
Creating windows
struct WindowGroup
A scene that presents a group of identically structured windows.
struct UtilityWindow
A specialized window scene that provides secondary utility to the content of the main scenes of an application.
protocol WindowStyle
A specification for the appearance and interaction of a window.
Sets the style for windows created by this scene.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/scene/windowstyle(_:)
#app-main)
- SwiftUI
- Scene
- windowStyle(_:)
Instance Method
windowStyle(_:)
Sets the style for windows created by this scene.
nonisolated
See Also
Creating windows
struct WindowGroup
A scene that presents a group of identically structured windows.
struct Window
A scene that presents its content in a single, unique window.
struct UtilityWindow
A specialized window scene that provides secondary utility to the content of the main scenes of an application.
protocol WindowStyle
A specification for the appearance and interaction of a window.
https://developer.apple.com/documentation/swiftui/scene/defaultposition(_:)
#app-main)
- SwiftUI
- Scene
- defaultPosition(_:)
Instance Method
defaultPosition(_:)
Sets a default position for a window.
nonisolated
Parameters
position
A UnitPoint that specifies where to place a newly opened window relative to the screen bounds.
Return Value
A scene that uses a default position for new windows.
Discussion
The first time your app opens a window from a particular scene declaration, the system places the window at the center of the screen by default. For scene types that support multiple simultaneous windows, the system offsets each additional window by a small amount to avoid completely obscuring existing windows.
You can override the default placement of the first window by applying a scene modifier that indicates where to place the window relative to the screen bounds. For example, you can request that the system place a new window in the bottom trailing corner of the screen:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } .defaultPosition(.bottomTrailing) } }
The system aligns the point in the window that corresponds to the specified UnitPoint with the point in the screen that corresponds to the same unit point.
You typically use one of the predefined unit points — like bottomTrailing in the above example — but you can also use a custom unit point. For example, the following modifier aligns the point that’s one quarter of the way from the leading edge of the window with the point that’s one quarter of the way from the leading edge of the screen, while centering the window in the y-dimension:
WindowGroup { ContentView() } .defaultPosition(UnitPoint(x: 0.25, y: 0.5))
The modifier affects any scene type that creates windows in macOS, namely:
-
WindowGroup -
Window -
DocumentGroup -
Settings
The value that you provide acts only as an initial default. During state restoration, the system restores the window to the position that it last occupied.
See Also
Positioning a window
struct WindowLevel
The level of a window.
Sets the window level of this scene.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Defines a function used for determining the default placement of windows.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowProxy
The proxy for an open window in the app.
struct DisplayProxy
A type which provides information about display hardware.
https://developer.apple.com/documentation/swiftui/view/presentedwindowstyle(_:)
#app-main)
- SwiftUI
- View
- presentedWindowStyle(_:)
Instance Method
presentedWindowStyle(_:)
Sets the style for windows created by interacting with this view.
nonisolated
See Also
Styling windows from a view inside the window
Sets the style for the toolbar in windows created by interacting with this view.
https://developer.apple.com/documentation/swiftui/customizing-window-styles-and-state-restoration-behavior-in-macos
- SwiftUI
- Windows
- Customizing window styles and state-restoration behavior in macOS
Sample Code
Customizing window styles and state-restoration behavior in macOS
Configure how your app’s windows look and function in macOS to provide an engaging and more coherent experience.
Download (1.2 GB)
Overview
The macOS target of Destination Video demonstrates how you can leverage the window and scene customization APIs (available in macOS 15 and later) to tailor an app’s experience in macOS. This includes changing a toolbar’s appearance and visibility, extending a window’s drag region, participating in a window’s zoom action, and modifying a window’s state restoration behavior.
Remove the title and background from the window’s toolbar
Destination Video uses a tab view as its main user interface component, and in macOS, this appears similar to a two-column navigation split view. In this configuration, each tab appears as an entry in the sidebar and participates in the app’s navigation. Because the sidebar provides a visual indication of where you are in that navigation hierarchy, and the app’s content doesn’t require any additional toolbar items, a toolbar isn’t necessary. Removing the toolbar can elevate the underlying content by letting it extend right up to the window’s edge.
To remove the toolbar’s background, ContentView calls the toolbarBackgroundVisibility(_:for:) view method:
.toolbarBackgroundVisibility(.hidden, for: .windowToolbar)
And then removes the toolbar’s title:
.toolbar(removing: .title)
In this instance, the app still requires the window control buttons to close or minimize the window or enter full-screen mode, so it uses individual view methods to remove only the title and bar background. To remove the toolbar entirely, use the toolbarVisibility(_:for:) view method instead.
It’s important to note that these are visual changes only. The system continues to provide the window’s title to accessibility tools such as screen readers, and the app’s Window menu continues to show the title while the window is open.
Extend the window’s drag region
To move a window in macOS, you typically drag that window’s toolbar. However, if you choose to remove the background from a toolbar, or hide the toolbar completely, use WindowDragGesture to extend that window’s drag region and make sure the window is still draggable.
Destination Video’s PlayerView adds this gesture to a transparent overlay and inserts the overlay between the video content and the playback controls. This enables you to safely drag the window and not interfere with the system playback UI that AVKit provides.
.gesture(WindowDragGesture())
The player also uses the allowsWindowActivationEvents(_:) view method to enable the installed window drag gesture to receive events that activate the window — for example, if the window is in the background and you click it and immediately drag.
.allowsWindowActivationEvents(true)
Customize the window’s zoom behavior
By default, a window’s toolbar provides buttons that close the window, minimize the window, and enter full-screen mode. If you press and hold the Option key and click the green button, the window zooms instead of going full screen.
Typically, a window zooms to either its defined maximum size, or as large as the display permits. However, you can use the windowIdealPlacement(_:) scene method to override this behavior and provide a size and position that’s more appropriate for the window’s contents. The app uses this method to provide a maximum size for the video player that maintains the video’s aspect ratio to prevent black bars appearing above and below it.
.windowIdealPlacement { proxy, context in let displayBounds = context.defaultDisplay.visibleRect let idealSize = proxy.sizeThatFits(.unspecified)
// Calculate the content's aspect ratio. let aspectRatio = aspectRatio(of: idealSize) // Determine the deltas between the display's size and the content's size. let deltas = deltas(of: displayBounds.size, idealSize)
// Calculate the window's zoomed size while maintaining the aspect ratio // of the content. let size = calculateZoomedSize( of: idealSize, inBounds: displayBounds, withAspectRatio: aspectRatio, andDeltas: deltas )
// Position the window in the center of the display and return the // corresponding window placement. let position = position(of: size, centeredIn: displayBounds) return WindowPlacement(position, size: size) }
This implementation also ensures the zoomed window appears in the center of the display while zooming.
Modify how the window participates in state restoration
In macOS, state restoration is optional and a person enables (or disables) it systemwide in System Settings. By default, your SwiftUI app respects this setting, but you can choose to override it and specify the preferred restoration behavior for each of your app’s windows. For example, you may want to opt out of state restoration for a window that represents a transient activity, or where it’s difficult or expensive to restore the underlying state from a previous session.
When running in macOS, Destination Video uses the SceneRestorationBehavior view modifier to disable state restoration for the video player view.
.restorationBehavior(.disabled)
As the app’s videos are brief, and a person’s interactions with them are short-lived, it doesn’t make sense to restore the video player on the next launch.
See Also
Related samples
Related videos
Essentials
Bringing multiple windows to your SwiftUI app
Compose rich views by reacting to state changes and customize your app’s scene presentation and behavior on iPadOS and macOS.
https://developer.apple.com/documentation/swiftui/bringing_multiple_windows_to_your_swiftui_app
- SwiftUI
- Bringing multiple windows to your SwiftUI app
Sample Code
Bringing multiple windows to your SwiftUI app
Compose rich views by reacting to state changes and customize your app’s scene presentation and behavior on iPadOS and macOS.
Download
Xcode 14.2+
Overview
Configure the sample code project
Before you run the sample code project in Xcode:
- To run the sample on an iOS device or Mac, make sure you select your team in the Signing & Capabilities tab in each target’s settings.
https://developer.apple.com/documentation/swiftui/utilitywindow
- SwiftUI
- UtilityWindow
Structure
UtilityWindow
A specialized window scene that provides secondary utility to the content of the main scenes of an application.
Overview
Utility windows are typically used to display controls, settings, or information associated the main content of an application, sometimes referred to as tool palettes or inspector windows. Because of this role, they have specialized behavior compared to all other windows:
-
They receive
FocusedValuesfrom the focused main scene in an application, similar to commands in the main menu, which can be used to display information on the active content as the user focuses on different scenes. -
They have a default window level of
.floatingso they remain visible when moving focus between the main scenes. -
They hide when the window is no longer active.
-
They only become focused when explicitly needed, such as clicking in the titlebar or on a focusable view.
-
When focused, they can be dismissed with the Escape key.
-
They are not minimizable by default.
@main struct PhotoBrowser: App { var body: some Scene { WindowGroup { PhotoGallery() }
UtilityWindow("Photo Info", id: "photo-info") { PhotoInfoViewer() } }
}
struct PhotoInfoViewer: View { // Automatically updates to the photo selection from whichever // photo gallery window is focused. @FocusedValue(PhotoSelection.self) private var selectedPhotos
var body: some View { Text("(selectedPhotos.count) photos selected") }
UtilityWindow will automatically add a menu item to show/hide itself in the “View” menu. This can be removed by applying commandsRemoved() to the utility window, and manually placing a WindowVisibilityToggle elsewhere in an app’s commands. Utility windows can also be programmatically presented with openWindow and dismissed using dismiss.
Topics
Initializers
init(_:id:content:)
Creates a utility window with a title and identifier.
Relationships
Conforms To
Scene
See Also
Creating windows
struct WindowGroup
A scene that presents a group of identically structured windows.
struct Window
A scene that presents its content in a single, unique window.
protocol WindowStyle
A specification for the appearance and interaction of a window.
Sets the style for windows created by this scene.
https://developer.apple.com/documentation/swiftui/windowstyle
- SwiftUI
- WindowStyle
Protocol
WindowStyle
A specification for the appearance and interaction of a window.
protocol WindowStyle
Topics
Getting built-in window styles
static var automatic: DefaultWindowStyle
The default window style.
static var hiddenTitleBar: HiddenTitleBarWindowStyle
A window style which hides both the window’s title and the backing of the titlebar area, allowing more of the window’s content to show.
static var plain: PlainWindowStyle
The plain window style.
static var titleBar: TitleBarWindowStyle
A window style which displays the title bar section of the window.
static var volumetric: VolumetricWindowStyle
A window style that creates a 3D volumetric window.
Supporting types
struct DefaultWindowStyle
struct HiddenTitleBarWindowStyle
struct PlainWindowStyle
struct TitleBarWindowStyle
struct VolumetricWindowStyle
Relationships
Conforming Types
DefaultWindowStyleHiddenTitleBarWindowStylePlainWindowStyleTitleBarWindowStyleVolumetricWindowStyle
See Also
Creating windows
struct WindowGroup
A scene that presents a group of identically structured windows.
struct Window
A scene that presents its content in a single, unique window.
struct UtilityWindow
A specialized window scene that provides secondary utility to the content of the main scenes of an application.
Sets the style for windows created by this scene.
https://developer.apple.com/documentation/swiftui/scene/windowtoolbarstyle(_:)
#app-main)
- SwiftUI
- Scene
- windowToolbarStyle(_:)
Instance Method
windowToolbarStyle(_:)
Sets the style for the toolbar defined within this scene.
nonisolated
See Also
Styling a toolbar
func toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
Specifies the preferred color scheme of a bar managed by SwiftUI.
Specifies the preferred foreground style of bars managed by SwiftUI.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
var toolbarLabelStyle: ToolbarLabelStyle?
The label style to apply to controls within a toolbar.
struct ToolbarLabelStyle
The label style of a toolbar.
struct SpacerSizing
A type which defines how spacers should size themselves.
Beta
https://developer.apple.com/documentation/swiftui/scene/windowtoolbarlabelstyle(_:)
#app-main)
- SwiftUI
- Scene
- windowToolbarLabelStyle(_:)
Instance Method
windowToolbarLabelStyle(_:)
Sets the label style of items in a toolbar and enables user customization.
nonisolated
Parameters
toolbarLabelStyle
The label style to apply.
Discussion
Use this modifier to bind a ToolbarLabelStyle to AppStorage. The toolbar will default to the label style specified but will also be user configurable.
@main struct MyApp: App { @AppStorage("ToolbarLabelStyle") private var labelStyle: ToolbarLabelStyle = .iconOnly
var body: some Scene { WindowGroup { ContentView() .toolbar(id: "browserToolbar") { ... } } .windowToolbarLabelStyle($labelStyle) } }
See Also
Styling the associated toolbar
Sets the style for the toolbar defined within this scene.
Sets the label style of items in a toolbar.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
https://developer.apple.com/documentation/swiftui/scene/windowtoolbarlabelstyle(fixed:)
#app-main)
- SwiftUI
- Scene
- windowToolbarLabelStyle(fixed:)
Instance Method
windowToolbarLabelStyle(fixed:)
Sets the label style of items in a toolbar.
nonisolated
Discussion
Use this modifier to set a static ToolbarLabelStyle the toolbar should use. The style will not be configurable by the user.
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .toolbar(id: "browserToolbar") { ... } } .windowToolbarLabelStyle(fixed: .iconOnly) } }
See Also
Styling the associated toolbar
Sets the style for the toolbar defined within this scene.
Sets the label style of items in a toolbar and enables user customization.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
https://developer.apple.com/documentation/swiftui/windowtoolbarstyle
- SwiftUI
- WindowToolbarStyle
Protocol
WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
protocol WindowToolbarStyle
Topics
Getting built-in window toolbar styles
static var automatic: DefaultWindowToolbarStyle
The automatic window toolbar style.
static var expanded: ExpandedWindowToolbarStyle
A window toolbar style which displays its title bar area above the toolbar.
static var unified: UnifiedWindowToolbarStyle
A window toolbar style which displays its toolbar and title bar inline.
static var unifiedCompact: UnifiedCompactWindowToolbarStyle
A window toolbar style similar to unified, but with a more compact vertical sizing.
Supporting types
struct DefaultWindowToolbarStyle
The default window toolbar style.
struct ExpandedWindowToolbarStyle
struct UnifiedWindowToolbarStyle
struct UnifiedCompactWindowToolbarStyle
Relationships
Conforming Types
DefaultWindowToolbarStyleExpandedWindowToolbarStyleUnifiedCompactWindowToolbarStyleUnifiedWindowToolbarStyle
See Also
Styling a toolbar
func toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
Specifies the preferred color scheme of a bar managed by SwiftUI.
Specifies the preferred foreground style of bars managed by SwiftUI.
Sets the style for the toolbar defined within this scene.
var toolbarLabelStyle: ToolbarLabelStyle?
The label style to apply to controls within a toolbar.
struct ToolbarLabelStyle
The label style of a toolbar.
struct SpacerSizing
A type which defines how spacers should size themselves.
Beta
https://developer.apple.com/documentation/swiftui/environmentvalues/supportsmultiplewindows
- SwiftUI
- EnvironmentValues
- supportsMultipleWindows
Instance Property
supportsMultipleWindows
A Boolean value that indicates whether the current platform supports opening multiple windows.
var supportsMultipleWindows: Bool { get }
Discussion
Read this property from the environment to determine if your app can use the openWindow action to open new windows:
struct NewMailViewerButton: View { @Environment(.supportsMultipleWindows) private var supportsMultipleWindows @Environment(.openWindow) private var openWindow
var body: some View { Button("Open New Window") { openWindow(id: "mail-viewer") } .disabled(!supportsMultipleWindows) } }
The reported value depends on both the platform and how you configure your app:
-
In macOS, this property returns
truefor any app that uses the SwiftUI app lifecycle. -
In iPadOS, this property returns
truefor any app that uses the SwiftUI app lifecycle and has the Information Property List keyUIApplicationSupportsMultipleScenesset totrue. -
For all other platforms and configurations, the value returns
false.
If the value is false and you try to open a window, SwiftUI ignores the action and logs a runtime error.
See Also
Opening windows
Presenting windows and spaces
Open and close the scenes that make up your app’s interface.
var openWindow: OpenWindowAction
A window presentation action stored in a view’s environment.
struct OpenWindowAction
An action that presents a window.
struct PushWindowAction
An action that opens the requested window in place of the window the action is called from.
https://developer.apple.com/documentation/swiftui/environmentvalues/openwindow
- SwiftUI
- EnvironmentValues
- openWindow
Instance Property
openWindow
A window presentation action stored in a view’s environment.
var openWindow: OpenWindowAction { get }
Discussion
Use the openWindow environment value to get an OpenWindowAction instance for a given Environment. Then call the instance to open a window. You call the instance directly because it defines a callAsFunction(id:) method that Swift calls when you call the instance.
For example, you can define a button that opens a new mail viewer window:
@main struct Mail: App { var body: some Scene { WindowGroup(id: "mail-viewer") { MailViewer() } } }
struct NewViewerButton: View { @Environment(.openWindow) private var openWindow
var body: some View { Button("Open new mail viewer") { openWindow(id: "mail-viewer") } } }
You indicate which scene to open by providing one of the following:
-
A string identifier that you pass through the
idparameter, as in the above example. -
A
valueparameter that has a type that matches the type that you specify in the scene’s initializer. -
Both an identifier and a value. This enables you to define multiple window groups that take input values of the same type like a
UUID.
Use the first option to target either a WindowGroup or a Window scene in your app that has a matching identifier. For a WindowGroup, the system creates a new window for the group. If the window group presents data, the system provides the default value or nil to the window’s root view. If the targeted scene is a Window, the system orders it to the front.
Use the other two options to target a WindowGroup and provide a value to present. If the interface already has a window from the group that’s presenting the specified value, the system brings the window to the front. Otherwise, the system creates a new window and passes a binding to the specified value.
See Also
Opening windows
Presenting windows and spaces
Open and close the scenes that make up your app’s interface.
var supportsMultipleWindows: Bool
A Boolean value that indicates whether the current platform supports opening multiple windows.
struct OpenWindowAction
An action that presents a window.
struct PushWindowAction
An action that opens the requested window in place of the window the action is called from.
https://developer.apple.com/documentation/swiftui/openwindowaction
- SwiftUI
- OpenWindowAction
Structure
OpenWindowAction
An action that presents a window.
@MainActor @preconcurrency struct OpenWindowAction
Overview
Use the openWindow environment value to get the instance of this structure for a given Environment. Then call the instance to open a window. You call the instance directly because it defines a callAsFunction(id:) method that Swift calls when you call the instance.
For example, you can define a button that opens a new mail viewer window:
@main struct Mail: App { var body: some Scene { WindowGroup(id: "mail-viewer") { MailViewer() } } }
struct NewViewerButton: View { @Environment(.openWindow) private var openWindow
var body: some View { Button("Open new mail viewer") { openWindow(id: "mail-viewer") } } }
You indicate which scene to open by providing one of the following:
-
A string identifier that you pass through the
idparameter, as in the above example. -
A
valueparameter that has a type that matches the type that you specify in the scene’s initializer. -
Both an identifier and a value. This enables you to define multiple window groups that take input values of the same type, like a
UUID.
Use the first option to target either a WindowGroup or a Window scene in your app that has a matching identifier. For a WindowGroup, the system creates a new window for the group. If the window group presents data, the system provides the default value or nil to the window’s root view. If the targeted scene is a Window, the system orders it to the front.
Use the other two options to target a WindowGroup and provide a value to present. If the interface already has a window from the group that’s presenting the specified value, the system brings the window to the front. Otherwise, the system creates a new window and passes a binding to the specified value.
Topics
Calling the action
func callAsFunction(id: String)
Opens a window that’s associated with the specified identifier.
Opens a window defined by the window group that presents the specified value type and that’s associated with the specified identifier.
Opens a window defined by a window group that presents the type of the specified value.
Structures
struct SharingBehavior
Instance Methods
func callAsFunction(id: String, sharingBehavior: OpenWindowAction.SharingBehavior) async throws
Opens a window that’s associated with the specified identifier, using the specified sharing sharingBehavior..
Opens a window defined by the window group that presents the specified value type and that’s associated with the specified identifier, using the specified sharingBehavior.
Opens a window defined by a window group that presents the type of the specified value, using the specified sharingBehavior.
Relationships
Conforms To
SendableSendableMetatype
See Also
Opening windows
Presenting windows and spaces
Open and close the scenes that make up your app’s interface.
var supportsMultipleWindows: Bool
A Boolean value that indicates whether the current platform supports opening multiple windows.
var openWindow: OpenWindowAction
A window presentation action stored in a view’s environment.
struct PushWindowAction
An action that opens the requested window in place of the window the action is called from.
https://developer.apple.com/documentation/swiftui/pushwindowaction
- SwiftUI
- PushWindowAction
Structure
PushWindowAction
An action that opens the requested window in place of the window the action is called from.
@MainActor struct PushWindowAction
Overview
The scene this action is called from will be backgrounded. The requested scene will be center-aligned with the backgrounded scene. The requested scene will have a default size that matches the size of the backgrounded scene. Closing the requested window will result in the backgrounded scene reappearing.
Call dismissWindow from the pushed window to dismiss the pushed window and show the backgrounded window.
Calling this action from a pushed window is not allowed.
Use the pushWindow environment value to get the instance of this structure for a given Environment. Then call the instance to push a window. You call the instance directly because it defines a callAsFunction(id:) method that Swift calls when you call the instance.
For example, you can define a button that pushes a video preview from an editor window:
@main struct VideoEditor: App { var body: some Scene { WindowGroup(id: "editor") { EditorView() }
WindowGroup(id: "viewer") { VideoView() } } }
struct EditorView: View { @Environment(.pushWindow) private var pushWindow
var body: some View { Button("Play", systemImage: "play.fill") { pushWindow(id: "viewer") } } }
You indicate which scene to push by providing one of the following:
-
A string identifier that you pass through the
idparameter, as in the above example. -
A
valueparameter that has a type that matches the type that you specify in the scene’s initializer. -
Both an identifier and a value. This enables you to define multiple window groups that take input values of the same type, like a
UUID.
Use the first option to target either a WindowGroup or a Window scene in your app that has a matching identifier. For a WindowGroup, the system creates a new window for the group. If the window group presents data, the system provides the default value or nil to the window’s root view. If the targeted scene is a Window, the system orders it to the front.
Use the other two options to target a WindowGroup and provide a value to present. If the interface already has a window from the group that is presenting the specified value, the system brings the window to the front. Otherwise, the system creates a new window and passes a binding to the specified value.
Topics
Instance Methods
func callAsFunction(id: String)
Pushes a window that is associated with the specified identifier.
Pushes a window defined by the window group that presents the specified value type and that is associated with the specified identifier.
Pushes a window defined by a window group that presents the type of the specified value.
Relationships
Conforms To
SendableSendableMetatype
See Also
Opening windows
Presenting windows and spaces
Open and close the scenes that make up your app’s interface.
var supportsMultipleWindows: Bool
A Boolean value that indicates whether the current platform supports opening multiple windows.
var openWindow: OpenWindowAction
A window presentation action stored in a view’s environment.
struct OpenWindowAction
An action that presents a window.
https://developer.apple.com/documentation/swiftui/environmentvalues/dismisswindow
- SwiftUI
- EnvironmentValues
- dismissWindow
Instance Property
dismissWindow
A window dismissal action stored in a view’s environment.
var dismissWindow: DismissWindowAction { get }
Discussion
Use the dismissWindow environment value to get an DismissWindowAction instance for a given Environment. Then call the instance to dismiss a window. You call the instance directly because it defines a callAsFunction(id:) method that Swift calls when you call the instance.
For example, you can define a button that dismisses an auxiliary window:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } #if os(macOS) Window("Auxiliary", id: "auxiliary") { AuxiliaryContentView() } #endif } }
struct DismissWindowButton: View { @Environment(.dismissWindow) private var dismissWindow
var body: some View { Button("Close Auxiliary Window") { dismissWindow(id: "auxiliary") } } }
If the window was opened with pushWindow, the presenting window will reappear when this action is performed.
See Also
Closing windows
struct DismissWindowAction
An action that dismisses a window associated to a particular scene.
var dismiss: DismissAction
An action that dismisses the current presentation.
struct DismissAction
An action that dismisses a presentation.
struct DismissBehavior
Programmatic window dismissal behaviors.
https://developer.apple.com/documentation/swiftui/dismisswindowaction
- SwiftUI
- DismissWindowAction
Structure
DismissWindowAction
An action that dismisses a window associated to a particular scene.
@MainActor @preconcurrency struct DismissWindowAction
Overview
Use the dismissWindow environment value to get the instance of this structure for a given Environment. Then call the instance to dismiss a window. You call the instance directly because it defines a callAsFunction(id:) method that Swift calls when you call the instance.
For example, you can define a button that closes an auxiliary window:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } #if os(macOS) Window("Auxiliary", id: "auxiliary") { AuxiliaryContentView() } #endif } }
struct DismissWindowButton: View { @Environment(.dismissWindow) private var dismissWindow
var body: some View { Button("Close Auxiliary Window") { dismissWindow(id: "auxiliary") } } }
If the window was opened with pushWindow, the original presenting will reappear when this action is performed.
Topics
Calling the action
func callAsFunction()
Dismisses the current window.
func callAsFunction(id: String)
Dismisses the window that’s associated with the specified identifier.
Dismisses the window defined by the window group that is presenting the specified value type and that’s associated with the specified identifier.
Dismisses the window defined by the window group that is presenting the specified value type.
Relationships
Conforms To
SendableSendableMetatype
See Also
Closing windows
var dismissWindow: DismissWindowAction
A window dismissal action stored in a view’s environment.
var dismiss: DismissAction
An action that dismisses the current presentation.
struct DismissAction
An action that dismisses a presentation.
struct DismissBehavior
Programmatic window dismissal behaviors.
https://developer.apple.com/documentation/swiftui/environmentvalues/dismiss
- SwiftUI
- EnvironmentValues
- dismiss
Instance Property
dismiss
An action that dismisses the current presentation.
var dismiss: DismissAction { get }
Mentioned in
Managing search interface activation
Discussion
Use this environment value to get the DismissAction instance for the current Environment. Then call the instance to perform the dismissal. You call the instance directly because it defines a callAsFunction() method that Swift calls when you call the instance.
You can use this action to:
-
Dismiss a modal presentation, like a sheet or a popover.
-
Pop the current view from a
NavigationStack.
On apps targetting iOS 18 and aligned releases, you also use the dismiss action to pop the implicit stack of a collapsed NavigationSplitView, or clear the equivalent state in an expanded split view.
The specific behavior of the action depends on where you call it from. For example, you can create a button that calls the DismissAction inside a view that acts as a sheet:
private struct SheetContents: View { @Environment(.dismiss) private var dismiss
var body: some View { Button("Done") { dismiss() } } }
When you present the SheetContents view, someone can dismiss the sheet by tapping or clicking the sheet’s button:
private struct DetailView: View { @State private var isSheetPresented = false
var body: some View { Button("Show Sheet") { isSheetPresented = true } .sheet(isPresented: $isSheetPresented) { SheetContents() } } }
Be sure that you define the action in the appropriate environment. For example, don’t reorganize the DetailView in the example above so that it creates the dismiss property and calls it from the sheet(item:onDismiss:content:) view modifier’s content closure:
private struct DetailView: View { @State private var isSheetPresented = false @Environment(.dismiss) private var dismiss // Applies to DetailView.
var body: some View { Button("Show Sheet") { isSheetPresented = true } .sheet(isPresented: $isSheetPresented) { Button("Done") { dismiss() // Fails to dismiss the sheet. } } } }
If you do this, the sheet fails to dismiss because the action applies to the environment where you declared it, which is that of the detail view, rather than the sheet. In fact, in macOS and iPadOS, if the DetailView is the root view of a window, the dismiss action closes the window instead.
The dismiss action has no effect on a view that isn’t currently presented. If you need to query whether SwiftUI is currently presenting a view, read the isPresented environment value.
See Also
Dismissing a presentation
var isPresented: Bool
A Boolean value that indicates whether the view associated with this environment is currently presented.
struct DismissAction
An action that dismisses a presentation.
Conditionally prevents interactive dismissal of presentations like popovers, sheets, and inspectors.
https://developer.apple.com/documentation/swiftui/dismissaction
- SwiftUI
- DismissAction
Structure
DismissAction
An action that dismisses a presentation.
@MainActor @preconcurrency struct DismissAction
Overview
Use the dismiss environment value to get the instance of this structure for a given Environment. Then call the instance to perform the dismissal. You call the instance directly because it defines a callAsFunction() method that Swift calls when you call the instance.
You can use this action to:
-
Dismiss a modal presentation, like a sheet or a popover.
-
Pop the current view from a
NavigationStack.
On apps targeting iOS 18 and aligned releases, you also use the dismiss action to pop the implicit stack of a collapsed NavigationSplitView, or clear the equivalent state in an expanded split view.
The specific behavior of the action depends on where you call it from. For example, you can create a button that calls the DismissAction inside a view that acts as a sheet:
private struct SheetContents: View { @Environment(.dismiss) private var dismiss
var body: some View { Button("Done") { dismiss() } } }
When you present the SheetContents view, someone can dismiss the sheet by tapping or clicking the sheet’s button:
private struct DetailView: View { @State private var isSheetPresented = false
var body: some View { Button("Show Sheet") { isSheetPresented = true } .sheet(isPresented: $isSheetPresented) { SheetContents() } } }
Be sure that you define the action in the appropriate environment. For example, don’t reorganize the DetailView in the example above so that it creates the dismiss property and calls it from the sheet(item:onDismiss:content:) view modifier’s content closure:
private struct DetailView: View { @State private var isSheetPresented = false @Environment(.dismiss) private var dismiss // Applies to DetailView.
var body: some View { Button("Show Sheet") { isSheetPresented = true } .sheet(isPresented: $isSheetPresented) { Button("Done") { dismiss() // Fails to dismiss the sheet. } } } }
If you do this, the sheet fails to dismiss because the action applies to the environment where you declared it, which is that of the detail view, rather than the sheet. In fact, in macOS and iPadOS, if the DetailView is the root view of a window, the dismiss action closes the window instead.
The dismiss action has no effect on a view that isn’t currently presented. If you need to query whether SwiftUI is currently presenting a view, read the isPresented environment value.
Topics
Calling the action
func callAsFunction()
Dismisses the view if it is currently presented.
Relationships
Conforms To
SendableSendableMetatype
See Also
Dismissing a presentation
var isPresented: Bool
A Boolean value that indicates whether the view associated with this environment is currently presented.
var dismiss: DismissAction
An action that dismisses the current presentation.
Conditionally prevents interactive dismissal of presentations like popovers, sheets, and inspectors.
https://developer.apple.com/documentation/swiftui/dismissbehavior
- SwiftUI
- DismissBehavior
Structure
DismissBehavior
Programmatic window dismissal behaviors.
struct DismissBehavior
Overview
Use values of this type to control window dismissal during the current transaction.
For example, to dismiss windows showing a modal presentation that would otherwise prohibit dismissal, use the destructive behavior:
struct DismissWindowButton: View { @Environment(.dismissWindow) private var dismissWindow
var body: some View { Button("Close Auxiliary Window") { withTransaction(.dismissBehavior, .destructive) { dismissWindow(id: "auxiliary") } } } }
Topics
Getting behaviors
static let destructive: DismissBehavior
The destructive dismiss behavior.
static let interactive: DismissBehavior
The interactive dismiss behavior.
Relationships
Conforms To
SendableSendableMetatype
See Also
Closing windows
var dismissWindow: DismissWindowAction
A window dismissal action stored in a view’s environment.
struct DismissWindowAction
An action that dismisses a window associated to a particular scene.
var dismiss: DismissAction
An action that dismisses the current presentation.
struct DismissAction
An action that dismisses a presentation.
https://developer.apple.com/documentation/swiftui/scene/defaultsize(_:)
#app-main)
- SwiftUI
- Scene
- defaultSize(_:)
Instance Method
defaultSize(_:)
Sets a default size for a window.
nonisolated
Show all declarations
Parameters
size
The default size for new windows created from a scene.
Return Value
A scene that uses a default size for new windows.
Discussion
Use this scene modifier to indicate a default initial size for a new window that the system creates from a Scene declaration. For example, you can request that new windows that a WindowGroup generates occupy 600 points in the x-dimension and 400 points in the y-dimension:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } .defaultSize(CGSize(width: 600, height: 400)) } }
The size that you specify acts only as a default for when the window first appears. People can later resize the window using interface controls that the system provides. Also, during state restoration, the system restores windows to their most recent size rather than the default size.
If you specify a default size that’s outside the range of the window’s inherent resizability in one or both dimensions, the system clamps the affected dimension to keep it in range. You can configure the resizability of a scene using the windowResizability(_:) modifier.
The default size modifier affects any scene type that creates windows in macOS, namely:
-
WindowGroup -
Window -
DocumentGroup -
Settings
If you want to specify the input directly in terms of width and height, use defaultSize(width:height:) instead.
See Also
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
Sets a default width and height for a window.
Sets a default size for a volumetric window.
Sets the kind of resizability to use for a window.
struct WindowResizability
The resizability of a window.
Specifies how windows derived form this scene should determine their size when zooming.
struct WindowIdealSize
A type which defines the size a window should use when zooming.
https://developer.apple.com/documentation/swiftui/scene/defaultsize(width:height:)
#app-main)
- SwiftUI
- Scene
- defaultSize(width:height:)
Instance Method
defaultSize(width:height:)
Sets a default width and height for a window.
nonisolated func defaultSize( width: CGFloat, height: CGFloat
Parameters
width
The default width for windows created from a scene.
height
The default height for windows created from a scene.
Return Value
A scene that uses a default size for new windows.
Discussion
Use this scene modifier to indicate a default initial size for a new window that the system creates from a Scene declaration. For example, you can request that new windows that a WindowGroup generates occupy 600 points in the x-dimension and 400 points in the y-dimension:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } .defaultSize(width: 600, height: 400) } }
The size that you specify acts only as a default for when the window first appears. People can later resize the window using interface controls that the system provides. Also, during state restoration, the system restores windows to their most recent size rather than the default size.
If you specify a default size that’s outside the range of the window’s inherent resizability in one or both dimensions, the system clamps the affected dimension to keep it in range. You can configure the resizability of a scene using the windowResizability(_:) modifier.
The default size modifier affects any scene type that creates windows in macOS, namely:
-
WindowGroup -
Window -
DocumentGroup -
Settings
If you want to specify the size input in terms of size instance, use defaultSize(_:) instead.
See Also
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
func defaultSize(_:)
Sets a default size for a window.
Sets a default size for a volumetric window.
Sets the kind of resizability to use for a window.
struct WindowResizability
The resizability of a window.
Specifies how windows derived form this scene should determine their size when zooming.
struct WindowIdealSize
A type which defines the size a window should use when zooming.
https://developer.apple.com/documentation/swiftui/scene/defaultsize(width:height:depth:)
#app-main)
- SwiftUI
- Scene
- defaultSize(width:height:depth:)
Instance Method
defaultSize(width:height:depth:)
Sets a default size for a volumetric window.
nonisolated func defaultSize( width: CGFloat, height: CGFloat, depth: CGFloat
Parameters
width
The default width for the created window.
height
The default height for the created window.
depth
The default depth for the created volumetric window.
Return Value
A scene that uses a default size for new windows.
Discussion
Use this modifier to indicate the default initial size for a new 3D window created from a Scene using VolumetricWindowStyle:
WindowGroup { ContentView() } .windowStyle(.volumetric) .defaultSize(width: 600, height: 400, depth: 600)
Each parameter is specified in points. The size of a volumetric scene is immutable after creation.
This modifier affects only windows that have the volumetric style in visionOS.
See Also
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
func defaultSize(_:)
Sets a default size for a window.
Sets a default width and height for a window.
Sets the kind of resizability to use for a window.
struct WindowResizability
The resizability of a window.
Specifies how windows derived form this scene should determine their size when zooming.
struct WindowIdealSize
A type which defines the size a window should use when zooming.
https://developer.apple.com/documentation/swiftui/scene/defaultsize(_:in:)
#app-main)
- SwiftUI
- Scene
- defaultSize(_:in:)
Instance Method
defaultSize(_:in:)
Sets a default size for a volumetric window.
nonisolated func defaultSize( _ size: Size3D, in unit: UnitLength
Parameters
unit
The unit of length the dimensions of the window are specified in.
Return Value
A scene that uses a default size for new windows.
Discussion
Use this modifier to indicate the default initial size for a new 3D window created from a Scene using VolumetricWindowStyle:
WindowGroup { ContentView() } .windowStyle(.volumetric) .defaultSize(Size3D(width: 1, height: 1, depth: 0.5), in: .meters)
Each parameter is specified in the unit you provide. The size of a volumetric scene is immutable after creation.
This modifier affects only windows that have the volumetric style in visionOS.
See Also
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
func defaultSize(_:)
Sets a default size for a window.
Sets a default width and height for a window.
Sets the kind of resizability to use for a window.
struct WindowResizability
The resizability of a window.
Specifies how windows derived form this scene should determine their size when zooming.
struct WindowIdealSize
A type which defines the size a window should use when zooming.
https://developer.apple.com/documentation/swiftui/scene/defaultsize(width:height:depth:in:)
#app-main)
- SwiftUI
- Scene
- defaultSize(width:height:depth:in:)
Instance Method
defaultSize(width:height:depth:in:)
Sets a default size for a volumetric window.
nonisolated func defaultSize( width: CGFloat, height: CGFloat, depth: CGFloat, in unit: UnitLength
Parameters
width
The default width for the created window.
height
The default height for the created window.
depth
The default depth for the created volumetric window.
unit
The unit of length the dimensions of the window are specified in.
Return Value
A scene that uses a default size for new windows.
Discussion
Use this modifier to indicate the default initial size for a new 3D window created from a Scene using VolumetricWindowStyle:
WindowGroup { ContentView() } .windowStyle(.volumetric) .defaultSize(width: 1, height: 1, depth: 0.5, in: .meters)
Each parameter is specified in the unit you provide. The size of a volumetric scene is immutable after creation.
This modifier affects only windows that have the volumetric style in visionOS.
See Also
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
func defaultSize(_:)
Sets a default size for a window.
Sets a default width and height for a window.
Sets the kind of resizability to use for a window.
struct WindowResizability
The resizability of a window.
Specifies how windows derived form this scene should determine their size when zooming.
struct WindowIdealSize
A type which defines the size a window should use when zooming.
https://developer.apple.com/documentation/swiftui/scene/windowresizability(_:)
#app-main)
- SwiftUI
- Scene
- windowResizability(_:)
Instance Method
windowResizability(_:)
Sets the kind of resizability to use for a window.
nonisolated
Parameters
resizability
The resizability to use for windows created by this scene.
Return Value
A scene that uses the specified resizability strategy.
Discussion
Use this scene modifier to apply a value of type WindowResizability to a Scene that you define in your App declaration. The value that you specify indicates the strategy the system uses to place minimum and maximum size restrictions on windows that it creates from that scene.
For example, you can create a window group that people can resize to between 100 and 400 points in both dimensions by applying both a frame with those constraints to the scene’s content, and the contentSize resizability to the scene:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .frame( minWidth: 100, maxWidth: 400, minHeight: 100, maxHeight: 400) } .windowResizability(.contentSize) } }
The default value for all scenes if you don’t apply the modifier is automatic. With that strategy, Settings windows use the contentSize strategy, while all others use contentMinSize.
See Also
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
func defaultSize(_:)
Sets a default size for a window.
Sets a default width and height for a window.
Sets a default size for a volumetric window.
struct WindowResizability
The resizability of a window.
Specifies how windows derived form this scene should determine their size when zooming.
struct WindowIdealSize
A type which defines the size a window should use when zooming.
https://developer.apple.com/documentation/swiftui/windowresizability
- SwiftUI
- WindowResizability
Structure
WindowResizability
The resizability of a window.
struct WindowResizability
Overview
Use the windowResizability(_:) scene modifier to apply a value of this type to a Scene that you define in your App declaration. The value that you specify indicates the strategy the system uses to place minimum and maximum size restrictions on windows that it creates from that scene.
For example, you can create a window group that people can resize to between 100 and 400 points in both dimensions by applying both a frame with those constraints to the scene’s content, and the contentSize resizability to the scene:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .frame( minWidth: 100, maxWidth: 400, minHeight: 100, maxHeight: 400) } .windowResizability(.contentSize) } }
The default value for all scenes if you don’t apply the modifier is automatic. With that strategy, Settings windows use the contentSize strategy, while all others use contentMinSize. Windows on visionOS with a window style of volumetric also use the contentSize strategy.
Topics
Getting the resizability
static var automatic: WindowResizability
The automatic window resizability.
static var contentMinSize: WindowResizability
A window resizability that’s partially derived from the window’s content.
static var contentSize: WindowResizability
A window resizability that’s derived from the window’s content.
Relationships
Conforms To
SendableSendableMetatype
See Also
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
func defaultSize(_:)
Sets a default size for a window.
Sets a default width and height for a window.
Sets a default size for a volumetric window.
Sets the kind of resizability to use for a window.
Specifies how windows derived form this scene should determine their size when zooming.
struct WindowIdealSize
A type which defines the size a window should use when zooming.
https://developer.apple.com/documentation/swiftui/scene/windowidealsize(_:)
#app-main)
- SwiftUI
- Scene
- windowIdealSize(_:)
Instance Method
windowIdealSize(_:)
Specifies how windows derived form this scene should determine their size when zooming.
nonisolated
Parameters
idealSize
A value which determines how windows derived from this scene should size themselves when zooming.
Discussion
The default behavior will size the window to its maximum size, or the bounds of the display, whichever is smaller. By overriding this behavior, you can provide a size that is appropriate for the contents of your window.
For example, you can define a window group where the window has an ideal width of 800 points and an ideal height of 600 points:
struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .frame(idealWidth: 800, idealHeight: 600) } .windowIdealSize(.fitToContent) } }
See Also
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
func defaultSize(_:)
Sets a default size for a window.
Sets a default width and height for a window.
Sets a default size for a volumetric window.
Sets the kind of resizability to use for a window.
struct WindowResizability
The resizability of a window.
struct WindowIdealSize
A type which defines the size a window should use when zooming.
https://developer.apple.com/documentation/swiftui/windowidealsize
- SwiftUI
- WindowIdealSize
Structure
WindowIdealSize
A type which defines the size a window should use when zooming.
struct WindowIdealSize
Overview
Use this type in conjunction with the Scene.windowIdealSize(_:) modifier to override the default behavior for how windows behave when performing a zoom.
For example, you can define a window group where the window has an ideal width of 800 points and an ideal height of 600 points:
struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .frame(idealWidth: 800, idealHeight: 600) } .windowIdealSize(.fitToContent) } }
Topics
Type Properties
static let automatic: WindowIdealSize
The automatic window ideal size. Windows will use the system behavior when determining the size to use when zooming.
static let fitToContent: WindowIdealSize
A window ideal size which uses the ideal size of the window’s contents.
static let maximum: WindowIdealSize
A window ideal size which uses the maximum size of the window’s contents.
Relationships
Conforms To
SendableSendableMetatype
See Also
Sizing a window
Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
func defaultSize(_:)
Sets a default size for a window.
Sets a default width and height for a window.
Sets a default size for a volumetric window.
Sets the kind of resizability to use for a window.
struct WindowResizability
The resizability of a window.
Specifies how windows derived form this scene should determine their size when zooming.
https://developer.apple.com/documentation/swiftui/windowlevel
- SwiftUI
- WindowLevel
Structure
WindowLevel
The level of a window.
struct WindowLevel
Overview
Use this in conjunction with the .windowLevel(_:) modifier to control window levels.
Topics
Type Properties
static var automatic: WindowLevel
Automatic window level.
static var desktop: WindowLevel
Desktop window level.
static var floating: WindowLevel
Floating window level.
static var normal: WindowLevel
Normal window level.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Positioning a window
Sets a default position for a window.
Sets the window level of this scene.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Defines a function used for determining the default placement of windows.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowProxy
The proxy for an open window in the app.
struct DisplayProxy
A type which provides information about display hardware.
https://developer.apple.com/documentation/swiftui/scene/windowlevel(_:)
#app-main)
- SwiftUI
- Scene
- windowLevel(_:)
Instance Method
windowLevel(_:)
Sets the window level of this scene.
nonisolated
Parameters
level
The desired window level
Discussion
Window("Utility Window", id: "...") { UtilityContent() } .windowLevel(.floating)
See Also
Positioning a window
Sets a default position for a window.
struct WindowLevel
The level of a window.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Defines a function used for determining the default placement of windows.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowProxy
The proxy for an open window in the app.
struct DisplayProxy
A type which provides information about display hardware.
https://developer.apple.com/documentation/swiftui/windowlayoutroot
- SwiftUI
- WindowLayoutRoot
Structure
WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowLayoutRoot
Overview
This type acts like a proxy for the contents of the window defined by a SwiftUI Scene. The Scene.defaultWindowPlacement(_:) modifier receives an instance of this type, representing the contents of the window being created.
Use this proxy to get information about the window’s contents, like it’s size.
Topics
Instance Methods
Asks the window’s content for its size.
See Also
Positioning a window
Sets a default position for a window.
struct WindowLevel
The level of a window.
Sets the window level of this scene.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Defines a function used for determining the default placement of windows.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowProxy
The proxy for an open window in the app.
struct DisplayProxy
A type which provides information about display hardware.
https://developer.apple.com/documentation/swiftui/windowplacement
- SwiftUI
- WindowPlacement
Structure
WindowPlacement
A type which represents a preferred size and position for a window.
struct WindowPlacement
Overview
When using the Scene.defaultWindowPlacement(_:) modifier, you return an instance of a WindowPlacement in the closure you provide.
When constructing a window placement, many initial parameters are optional. Any value not specified will fall
Structures
struct Position
A semantic or positional value for the location of a window.
Initializers
init(WindowPlacement.Position?)
Creates a new window placement with an optional position.
init(WindowPlacement.Position?, size3D: Size3D?)
Creates a new window placement with an optional position and 3D size. Depth is ignored on scenes that don’t support it.
init(_:size:)
Creates a new window placement with an absolute position and optional size.
init(UnitPoint, width: CGFloat?, height: CGFloat?)
Creates a new window placement with a display-relative position, with an optional width and height.
init(WindowPlacement.Position?, width: CGFloat?, height: CGFloat?, depth: CGFloat?)
Creates a new window placement with an optional position and 3D size. Depth is ignored on scenes or platforms that don’t support it.
init(x: CGFloat?, y: CGFloat?, width: CGFloat?, height: CGFloat?)
Creates a new window placement with an optional position and size.
Relationships
Conforms To
Equatable
See Also
Positioning a window
Sets a default position for a window.
struct WindowLevel
The level of a window.
Sets the window level of this scene.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
Defines a function used for determining the default placement of windows.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowProxy
The proxy for an open window in the app.
struct DisplayProxy
A type which provides information about display hardware.
https://developer.apple.com/documentation/swiftui/scene/defaultwindowplacement(_:)
#app-main)
- SwiftUI
- Scene
- defaultWindowPlacement(_:)
Instance Method
defaultWindowPlacement(_:)
Defines a function used for determining the default placement of windows.
nonisolated
Parameters
makePlacement
A closure to generate the default window placement.
Discussion
Use this scene modifier to indicate a default initial size and position for a new window that the system creates from a Scene declaration.
On macOS, you can use the screen’s bounds to place the window. For example, you can specify that the window is always placed 140 points from the bottom of the screen:
struct MyApp: App { var body: some Scene { ...
Window("Status", id: "status") { StatusView() } .windowResizability(.contentSize) .defaultWindowPlacement { content, context in let displayBounds = context.defaultDisplay.visibleRect let size = content.sizeThatFits(.unspecified) let position = CGPoint( x: displayBounds.midX - (size.width / 2), y: displayBounds.maxY - size.height - 140) return WindowPlacement(position: position, size: size) } } }
On visionOS, the system always places the first window relative to where the person is looking. The system ignores calls to defaultWindowPlacement(_:).
You can place any subsequent windows relative to existing ones by returning one of the methods defined by WindowPlacement.Position with the existing window. For example, you can align the new window with the trailing edge of the Content window:
struct MyApp: App { @Environment(.openWindow) private var openWindow
var body: some Scene { WindowGroup("Content", id: "content") { Button("Open status window") { openWindow(id: "status") } }
WindowGroup("Status", id: "status") { StatusView() } .windowResizability(.contentSize) .defaultWindowPlacement { content, context in if let contentWindow = context.windows.first( where: { $0.id == "content" }) { WindowPlacement(.trailing(contentWindow)) } else { WindowPlacement() } } } }
The placement that your function returns acts as a default for when the window first appears. People can later resize and move the window using interface controls that the system provides. Also, during state restoration, the system restores the window to it’s most recent size and position, rather than the default placement.
For more information on configuring how scenes behave with state restoration, see Scene.stateRestoration(_:).
See Also
Positioning a window
Sets a default position for a window.
struct WindowLevel
The level of a window.
Sets the window level of this scene.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowProxy
The proxy for an open window in the app.
struct DisplayProxy
A type which provides information about display hardware.
https://developer.apple.com/documentation/swiftui/scene/windowidealplacement(_:)
#app-main)
- SwiftUI
- Scene
- windowIdealPlacement(_:)
Instance Method
windowIdealPlacement(_:)
Provides a function which determines a placement to use when windows of a scene zoom.
nonisolated
Parameters
makePlacement
A closure which returns the ideal placement for a window derived from this scene.
Discussion
The default behavior will size the window to its maximum size, or the bounds of the display, whichever is smaller. By overriding this behavior, you can provide a size that is appropriate for the contents of your window.
For example, you can provide a placement with a height equal to the display bounds, and a width based on your content’s ideal width:
struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } .windowIdealPlacement { content, context in let displayBounds = context.defaultDisplay.visibleRect let proposal = ProposedViewSize( width: nil, height: displayBounds.height) let contentSize = content.sizeThatFits(proposal) return .init( width: contentSize.width, height: contentSize.height) } } }
See Also
Positioning a window
Sets a default position for a window.
struct WindowLevel
The level of a window.
Sets the window level of this scene.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Defines a function used for determining the default placement of windows.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowProxy
The proxy for an open window in the app.
struct DisplayProxy
A type which provides information about display hardware.
https://developer.apple.com/documentation/swiftui/windowplacementcontext
- SwiftUI
- WindowPlacementContext
Structure
WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowPlacementContext
Overview
The placement context provides information to be used when providing a new placement via the closure provided to the defaultWindowPlacement(_:) modifier.
Topics
Instance Properties
var defaultDisplay: DisplayProxy
The display on which new windows will be presented by default.
The list of current active scenes
See Also
Positioning a window
Sets a default position for a window.
struct WindowLevel
The level of a window.
Sets the window level of this scene.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Defines a function used for determining the default placement of windows.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowProxy
The proxy for an open window in the app.
struct DisplayProxy
A type which provides information about display hardware.
https://developer.apple.com/documentation/swiftui/windowproxy
- SwiftUI
- WindowProxy
Structure
WindowProxy
The proxy for an open window in the app.
struct WindowProxy
Topics
Instance Properties
var id: String?
The ID for the window, if one was provided.
var phase: ScenePhase
The window’s current ScenePhase.
See Also
Positioning a window
Sets a default position for a window.
struct WindowLevel
The level of a window.
Sets the window level of this scene.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Defines a function used for determining the default placement of windows.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct DisplayProxy
A type which provides information about display hardware.
https://developer.apple.com/documentation/swiftui/displayproxy
- SwiftUI
- DisplayProxy
Structure
DisplayProxy
A type which provides information about display hardware.
struct DisplayProxy
Overview
You can use this type with your custom window layouts to size and position windows relative to a display’s bounds.
For example, your custom window layout can position a window 140 points from the bottom of the screen’s visible area:
Window("Status", id: "status") { StatusView() } .windowResizability(.contentSize) .defaultWindowPlacement { content, context in let displayBounds = context.defaultDisplay.visibleRect let size = content.sizeThatFits(.unspecified) let position = CGPoint( x: displayBounds.midX - (size.width / 2), y: displayBounds.maxY - size.height - 140) return WindowPlacement(position: position, size: size) }
Topics
Instance Properties
let bounds: CGRect
The full dimensions of the display, including any space occupied by system interface elements.
let safeAreaInsets: EdgeInsets
The safe area inset of this display.
let visibleRect: CGRect
The portion of the display where it is safe to place windows.
Relationships
Conforms To
Equatable
See Also
Positioning a window
Sets a default position for a window.
struct WindowLevel
The level of a window.
Sets the window level of this scene.
struct WindowLayoutRoot
A proxy which represents the root contents of a window.
struct WindowPlacement
A type which represents a preferred size and position for a window.
Defines a function used for determining the default placement of windows.
Provides a function which determines a placement to use when windows of a scene zoom.
struct WindowPlacementContext
A type which represents contextual information used for sizing and positioning windows.
struct WindowProxy
The proxy for an open window in the app.
https://developer.apple.com/documentation/swiftui/windowvisibilitytoggle
- SwiftUI
- WindowVisibilityToggle
Structure
WindowVisibilityToggle
A specialized button for toggling the visibility of a window.
Overview
This is most commonly used in the main menu, where it can toggle the visibility of Window and UtilityWindow windows. The default label uses the title of the window in the format of “Show ” and “Hide ” depending on the current visibility of the window.
A keyboard shortcut can be assigned to this button.
The below example demonstrates how a main menu can be constructed with visibility buttons, replacing the default commands added by Window and Utility Window:
struct PhotoEditor: App { var body: some Scene { WindowGroup { PhotoEditor() } .commands { CommandGroup(before: .textFormatting) { Section { WindowVisibilityToggle(windowID: "formatting") .keyboardShortcut("t", modifiers: [.command, .shift])
// other custom/image formatting controls } } CommandGroup(before: .sidebar) { Section { WindowVisibilityToggle(windowID: "photo-library")
// other controls for showing/hiding UI } } }
UtilityWindow("Formatting Style", id: "formatting") { TextAndImageFormatForm() } .commandsRemoved()
Window("Photo Library", id: "photo-library") { PhotoInfoViewer() } .commandsRemoved() } }
Topics
Creating a window visibility toggle
init(windowID: String)
Create a window visibility toggle to alter the visibility of a specific window.
Supporting types
struct DefaultWindowVisibilityToggleLabel
The default label of a window visibility toggle.
Relationships
Conforms To
View
See Also
Configuring window visibility
Sets the default launch behavior for this scene.
Sets the restoration behavior for this scene.
struct SceneLaunchBehavior
The launch behavior for a scene.
struct SceneRestorationBehavior
The restoration behavior for a scene.
Sets the preferred visibility of the non-transient system views overlaying the app.
Configures the visibility of the window toolbar when the window enters full screen mode.
struct WindowToolbarFullScreenVisibility
The visibility of the window toolbar with respect to full screen mode.
https://developer.apple.com/documentation/swiftui/scene/defaultlaunchbehavior(_:)
#app-main)
- SwiftUI
- Scene
- defaultLaunchBehavior(_:)
Instance Method
defaultLaunchBehavior(_:)
Sets the default launch behavior for this scene.
nonisolated
Discussion
This behavior can be used to define if a scene is shown on application launch in the absence of any previously saved state.
On platforms that do not support multiple windows, this value is ignored.
On platforms other than macOS, there must be at least one scene that presents itself. If no scenes are defined to present, the first scene will be presented, regardless of the value provided to this modifier.
On macOS, this behavior will also be used to determine which scene is presented when clicking on the icon of a running application with no visible windows.
On visionOS, the system may background the last dismissed scene instead of closing it. Thus, the suppressed behavior additionally specifies that the scene should not be presented when tapping on the application icon with no visible windows.
For example, you may wish to present a welcome window on launch of your app when there are no previous document windows being restored:
@main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: MyDocument()) { configuration in DocumentEditor(configuration.$document) }
Window("Welcome to My App", id: "welcome") { WelcomeView() } .defaultLaunchBehavior(.presented) } }
The default value for all scenes if you do not apply this modifier is automatic. With that strategy, a scene will only present itself if it is the first scene defined by the app, and no other scenes have presented themselves.
See Also
Configuring window visibility
struct WindowVisibilityToggle
A specialized button for toggling the visibility of a window.
Sets the restoration behavior for this scene.
struct SceneLaunchBehavior
The launch behavior for a scene.
struct SceneRestorationBehavior
The restoration behavior for a scene.
Sets the preferred visibility of the non-transient system views overlaying the app.
Configures the visibility of the window toolbar when the window enters full screen mode.
struct WindowToolbarFullScreenVisibility
The visibility of the window toolbar with respect to full screen mode.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/scene/restorationbehavior(_:)
#app-main)
- SwiftUI
- Scene
- restorationBehavior(_:)
Instance Method
restorationBehavior(_:)
Sets the restoration behavior for this scene.
nonisolated
Discussion
Use this scene modifier to apply a value of this type to a Scene you define in your App declaration. The value you specify determines how the system will restore windows from a previous run of your application.
For example, you may have a scene that you do not wish to be restored on launch:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } Window(id: "network-test", "Network Connection Test") { NetworkTestView() } .restorationBehavior(.disabled) } }
The default value for all scenes if you do not apply the modifier is automatic. With that strategy, scenes will restore themselves depending on the default behavior for the platform.
See Also
Configuring window visibility
struct WindowVisibilityToggle
A specialized button for toggling the visibility of a window.
Sets the default launch behavior for this scene.
struct SceneLaunchBehavior
The launch behavior for a scene.
struct SceneRestorationBehavior
The restoration behavior for a scene.
Sets the preferred visibility of the non-transient system views overlaying the app.
Configures the visibility of the window toolbar when the window enters full screen mode.
struct WindowToolbarFullScreenVisibility
The visibility of the window toolbar with respect to full screen mode.
https://developer.apple.com/documentation/swiftui/scenelaunchbehavior
- SwiftUI
- SceneLaunchBehavior
Structure
SceneLaunchBehavior
The launch behavior for a scene.
struct SceneLaunchBehavior
Overview
Use the defaultLaunchBehavior(_:) modifier to apply a value of this type to a Scene you specify in your App. The value you specify determines how the system will present the scene in the absense of any previously restored scenes on launch of your application.
For example, you may wish to present a welcome window on launch of your app when there are no previous document windows being restored:
@main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: MyDocument()) { configuration in DocumentEditor(configuration.$document) }
Window("Welcome to My App", id: "welcome") { WelcomeView() } .defaultLaunchBehavior(.presented) } }
Topics
Type Properties
static let automatic: SceneLaunchBehavior
The automatic behavior.
static let presented: SceneLaunchBehavior
The presented behavior. The scene will present itself in the absence of any previously restored scenes.
static let suppressed: SceneLaunchBehavior
The suppressed behavior. The scene will not present itself in the absence of any previously restored scenes.
Relationships
Conforms To
SendableSendableMetatype
See Also
Configuring window visibility
struct WindowVisibilityToggle
A specialized button for toggling the visibility of a window.
Sets the default launch behavior for this scene.
Sets the restoration behavior for this scene.
struct SceneRestorationBehavior
The restoration behavior for a scene.
Sets the preferred visibility of the non-transient system views overlaying the app.
Configures the visibility of the window toolbar when the window enters full screen mode.
struct WindowToolbarFullScreenVisibility
The visibility of the window toolbar with respect to full screen mode.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/scenerestorationbehavior
- SwiftUI
- SceneRestorationBehavior
Structure
SceneRestorationBehavior
The restoration behavior for a scene.
struct SceneRestorationBehavior
Overview
Use the restorationBehavior(_:) scene modifier to apply a value of this type to a Scene you define in your App declaration. The value you specify determines how the system will restore windows from a previous run of your application.
For example, you may have a scene that you do not wish to be restored on launch:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } Window(id: "network-test", "Network Connection Test") { NetworkTestView() } .restorationBehavior(.disabled) } }
Topics
Type Properties
static let automatic: SceneRestorationBehavior
The automatic behavior. The scene’s windows will be restored as defined by the underlying platform.
static let disabled: SceneRestorationBehavior
The disabled behavior. The scene’s windows will not be restored.
Relationships
Conforms To
SendableSendableMetatype
See Also
Configuring window visibility
struct WindowVisibilityToggle
A specialized button for toggling the visibility of a window.
Sets the default launch behavior for this scene.
Sets the restoration behavior for this scene.
struct SceneLaunchBehavior
The launch behavior for a scene.
Sets the preferred visibility of the non-transient system views overlaying the app.
Configures the visibility of the window toolbar when the window enters full screen mode.
struct WindowToolbarFullScreenVisibility
The visibility of the window toolbar with respect to full screen mode.
https://developer.apple.com/documentation/swiftui/scene/persistentsystemoverlays(_:)
#app-main)
- SwiftUI
- Scene
- persistentSystemOverlays(_:)
Instance Method
persistentSystemOverlays(_:)
Sets the preferred visibility of the non-transient system views overlaying the app.
nonisolated
Discussion
Use this modifier to influence the appearance of system overlays in your app. The behavior varies by platform.
In iOS, the following example hides every persistent system overlay. In visionOS 2 and later, the SharePlay Indicator hides if the scene is shared through SharePlay, or not shared at all. During screen sharing, the indicator always remains visible. The Home indicator doesn’t appear without specific user intent when you set visibility to hidden. For a WindowGroup, the modifier affects the visibility of the window chrome. For an ImmersiveSpace, it affects the Home indicator.
struct ImmersiveView: View { var body: some View { Text("Maximum immersion") .persistentSystemOverlays(.hidden) } }
Affected non-transient system views can include, but are not limited to:
-
The Home indicator.
-
The SharePlay indicator.
-
The Multitasking Controls button and Picture in Picture on iPad.
See Also
Configuring window visibility
struct WindowVisibilityToggle
A specialized button for toggling the visibility of a window.
Sets the default launch behavior for this scene.
Sets the restoration behavior for this scene.
struct SceneLaunchBehavior
The launch behavior for a scene.
struct SceneRestorationBehavior
The restoration behavior for a scene.
Configures the visibility of the window toolbar when the window enters full screen mode.
struct WindowToolbarFullScreenVisibility
The visibility of the window toolbar with respect to full screen mode.
https://developer.apple.com/documentation/swiftui/view/windowtoolbarfullscreenvisibility(_:)
#app-main)
- SwiftUI
- View
- windowToolbarFullScreenVisibility(_:)
Instance Method
windowToolbarFullScreenVisibility(_:)
Configures the visibility of the window toolbar when the window enters full screen mode.
nonisolated
Parameters
visibility
The visibility to use for the window toolbar in full screen mode.
Discussion
By default, the window toolbar will show at the top of the display, above the window’s contents.
You can use this modifier to override the default behavior.
For example, you can specify that the window toolbar should be hidden by default, and only show once the mouse moves into the area occupied by the menu bar:
struct RootView: View { var body: some View { ContentView() .toolbar { ... } .windowToolbarFullScreenVisibility(.onHover) } }
See Also
Configuring window visibility
struct WindowVisibilityToggle
A specialized button for toggling the visibility of a window.
Sets the default launch behavior for this scene.
Sets the restoration behavior for this scene.
struct SceneLaunchBehavior
The launch behavior for a scene.
struct SceneRestorationBehavior
The restoration behavior for a scene.
Sets the preferred visibility of the non-transient system views overlaying the app.
struct WindowToolbarFullScreenVisibility
The visibility of the window toolbar with respect to full screen mode.
https://developer.apple.com/documentation/swiftui/windowtoolbarfullscreenvisibility
- SwiftUI
- WindowToolbarFullScreenVisibility
Structure
WindowToolbarFullScreenVisibility
The visibility of the window toolbar with respect to full screen mode.
struct WindowToolbarFullScreenVisibility
Overview
Use values of this type in conjunction with the windowToolbarFullScreenVisibility(_:) modifier to configure how the window toolbar displays itself when the window enters full screen mode.
For example, you can specify that the window toolbar should be hidden by default, and only show when the mouse moves into the area occupied by the menu bar:
struct RootView: View { var body: some View { ContentView() .toolbar { ... } .windowToolbarFullScreenVisibility(.onHover) } }
Topics
Type Properties
static let automatic: WindowToolbarFullScreenVisibility
The window toolbar visibility will be defined by the system default behavior.
static let onHover: WindowToolbarFullScreenVisibility
Hide the window toolbar in full screen mode by default. It will reveal itself when the mouse moves into the area occupied by the menu bar.
static let visible: WindowToolbarFullScreenVisibility
Prefer to show window toolbar when the window is in full screen mode.
Relationships
Conforms To
SendableSendableMetatype
See Also
Configuring window visibility
struct WindowVisibilityToggle
A specialized button for toggling the visibility of a window.
Sets the default launch behavior for this scene.
Sets the restoration behavior for this scene.
struct SceneLaunchBehavior
The launch behavior for a scene.
struct SceneRestorationBehavior
The restoration behavior for a scene.
Sets the preferred visibility of the non-transient system views overlaying the app.
Configures the visibility of the window toolbar when the window enters full screen mode.
https://developer.apple.com/documentation/swiftui/windowmanagerrole
- SwiftUI
- WindowManagerRole
Structure
WindowManagerRole
Options for defining how a scene’s windows behave when used within a managed window context, such as full screen mode and Stage Manager.
struct WindowManagerRole
Overview
Use values of this type in conjunction with the windowManagerRole(_:) modifier to override the default system behavior.
For example, you can specify that a secondary Window scene should use the principal role for full screen and Stage Manager:
struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } Window("Organizer", id: "organizer") { OrganizerView() } .windowManagerRole(.principal) } }
Topics
Type Properties
static let associated: WindowManagerRole
The associated role. Windows derived from this scene can be shown alongside windows with a .principal role in either full screen or Stage Manager, but do not participate in those modes on their own.
static let automatic: WindowManagerRole
The automatic role. The type and configuration of the scene will be used to determine how its windows behave in full screen and Stage Manager.
static let principal: WindowManagerRole
The principal role. Windows derived from this scene will show in full screen, if enabled, or in Stage Manager.
Relationships
Conforms To
SendableSendableMetatype
See Also
Managing window behavior
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
struct WindowInteractionBehavior
Options for enabling and disabling window interaction behaviors.
Configures the dismiss functionality for the window enclosing self.
Configures the full screen functionality for the window enclosing self.
Configures the minimize functionality for the window enclosing self.
Configures the resize functionality for the window enclosing self.
Configures the behavior of dragging a window by its background.
https://developer.apple.com/documentation/swiftui/scene/windowmanagerrole(_:)
#app-main)
- SwiftUI
- Scene
- windowManagerRole(_:)
Instance Method
windowManagerRole(_:)
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
nonisolated
Discussion
By default, the type of Scene and its placement within the app’s definition will determine the behavior of its windows within a window management context.
You can use this modifier to override the default behaivor.
For example, you can specify that a secondary Window scene should use the principal behavior for full screen and Stage Manager:
struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } Window("Organizer", id: "organizer") { OrganizerView() } .windowManagerRole(.principal) } }
See Also
Managing window behavior
struct WindowManagerRole
Options for defining how a scene’s windows behave when used within a managed window context, such as full screen mode and Stage Manager.
struct WindowInteractionBehavior
Options for enabling and disabling window interaction behaviors.
Configures the dismiss functionality for the window enclosing self.
Configures the full screen functionality for the window enclosing self.
Configures the minimize functionality for the window enclosing self.
Configures the resize functionality for the window enclosing self.
Configures the behavior of dragging a window by its background.
https://developer.apple.com/documentation/swiftui/windowinteractionbehavior
- SwiftUI
- WindowInteractionBehavior
Structure
WindowInteractionBehavior
Options for enabling and disabling window interaction behaviors.
struct WindowInteractionBehavior
Overview
Use values of this type in conjunction with the following view and scene modifiers to adjust the supported functionality for the window:
-
windowDismissBehavior(_:) -
windowMinimizeBehavior(_:) -
windowFullScreenBehavior(_:) -
windowResizeBehavior(_:) -
windowBackgroundDragBehavior(_:)
For example, you can create a custom “About” window which only allows for dismissal:
struct MyApp: App { var body: some Scene { ... Window("About MyApp", id: "about") { AboutView() .windowMinimizeBehavior(.disabled) .windowResizeBehavior(.disabled) } .windowResizability(.contentSize) } }
Topics
Type Properties
static let automatic: WindowInteractionBehavior
The automatic behavior. The associated window behavior will be enabled or disabled depending on the configuration of the enclosing Scene.
static let disabled: WindowInteractionBehavior
The disabled behavior. The associated window interaction behavior will be disabled.
static let enabled: WindowInteractionBehavior
The enabled behavior. The associated window interaction behavior will be enabled.
Relationships
Conforms To
SendableSendableMetatype
See Also
Managing window behavior
struct WindowManagerRole
Options for defining how a scene’s windows behave when used within a managed window context, such as full screen mode and Stage Manager.
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
Configures the dismiss functionality for the window enclosing self.
Configures the full screen functionality for the window enclosing self.
Configures the minimize functionality for the window enclosing self.
Configures the resize functionality for the window enclosing self.
Configures the behavior of dragging a window by its background.
https://developer.apple.com/documentation/swiftui/view/windowdismissbehavior(_:)
#app-main)
- SwiftUI
- View
- windowDismissBehavior(_:)
Instance Method
windowDismissBehavior(_:)
Configures the dismiss functionality for the window enclosing self.
nonisolated
Parameters
behavior
The dismiss behavior.
Discussion
By default, the window dismiss functionality is determined by the scene, as well as any modifiers applied to it.
You can use this modifier to override the default behavior.
For example, you can create a welcome workflow window which disables the dismiss functionality:
struct MyApp: App { var body: some Scene { ... Window("Welcome", id: "welcome") { WelcomeView() .windowDismissBehavior(.disabled) } } }
See Also
Managing window behavior
struct WindowManagerRole
Options for defining how a scene’s windows behave when used within a managed window context, such as full screen mode and Stage Manager.
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
struct WindowInteractionBehavior
Options for enabling and disabling window interaction behaviors.
Configures the full screen functionality for the window enclosing self.
Configures the minimize functionality for the window enclosing self.
Configures the resize functionality for the window enclosing self.
Configures the behavior of dragging a window by its background.
https://developer.apple.com/documentation/swiftui/view/windowfullscreenbehavior(_:)
#app-main)
- SwiftUI
- View
- windowFullScreenBehavior(_:)
Instance Method
windowFullScreenBehavior(_:)
Configures the full screen functionality for the window enclosing self.
nonisolated
Parameters
behavior
The full screen behavior.
Discussion
By default, the window full screen functionality is determined by the scene, as well as any modifiers applied to it. Additionally, when using the windowResizability(_:) modifier, the maximum size of the window’s contents will also determine whether a window can be made full screen.
You can use this modifier to override the default behavior.
For example, you can specify that a window cannot enter full screen mode:
struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .windowFullScreenBehavior(.disabled) } } }
See Also
Managing window behavior
struct WindowManagerRole
Options for defining how a scene’s windows behave when used within a managed window context, such as full screen mode and Stage Manager.
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
struct WindowInteractionBehavior
Options for enabling and disabling window interaction behaviors.
Configures the dismiss functionality for the window enclosing self.
Configures the minimize functionality for the window enclosing self.
Configures the resize functionality for the window enclosing self.
Configures the behavior of dragging a window by its background.
https://developer.apple.com/documentation/swiftui/view/windowminimizebehavior(_:)
#app-main)
- SwiftUI
- View
- windowMinimizeBehavior(_:)
Instance Method
windowMinimizeBehavior(_:)
Configures the minimize functionality for the window enclosing self.
nonisolated
Parameters
behavior
The resize behavior.
Discussion
On macOS, windows which support being minimized will move into the Dock when the minimize button is clicked, or the corresponding menu item is selected.
By default, the window minimize functionality is determined by the scene, as well as any modifiers applied to it.
You can use this modifier to override the default behavior.
For example, you can create a custom “About” window which disables the minimize functionality:
struct MyApp: App { var body: some Scene { ... Window("About MyApp", id: "about") { AboutView() .windowResizeBehavior(.disabled) .windowMinimizeBehavior(.disabled) } .windowResizability(.contentSize) } }
See Also
Managing window behavior
struct WindowManagerRole
Options for defining how a scene’s windows behave when used within a managed window context, such as full screen mode and Stage Manager.
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
struct WindowInteractionBehavior
Options for enabling and disabling window interaction behaviors.
Configures the dismiss functionality for the window enclosing self.
Configures the full screen functionality for the window enclosing self.
Configures the resize functionality for the window enclosing self.
Configures the behavior of dragging a window by its background.
https://developer.apple.com/documentation/swiftui/view/windowresizebehavior(_:)
#app-main)
- SwiftUI
- View
- windowResizeBehavior(_:)
Instance Method
windowResizeBehavior(_:)
Configures the resize functionality for the window enclosing self.
nonisolated
Parameters
behavior
The resize behavior.
Discussion
By default, the window resizability functionality is determined by the scene, as well as any modifiers applied to it. Additionally, when using the windowResizability(_:) modifier, the minimum and maximum size of the window’s contents will also determine the resizability behavior.
You can use this modifier to override the default behavior.
For example, you can create a custom “About” window which only allows for dismissal:
struct MyApp: App { var body: some Scene { ... Window("About MyApp", id: "about") { AboutView() .windowResizeBehavior(.disabled) .windowMinimizeBehavior(.disabled) } .windowResizability(.contentSize) } }
See Also
Managing window behavior
struct WindowManagerRole
Options for defining how a scene’s windows behave when used within a managed window context, such as full screen mode and Stage Manager.
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
struct WindowInteractionBehavior
Options for enabling and disabling window interaction behaviors.
Configures the dismiss functionality for the window enclosing self.
Configures the full screen functionality for the window enclosing self.
Configures the minimize functionality for the window enclosing self.
Configures the behavior of dragging a window by its background.
https://developer.apple.com/documentation/swiftui/scene/windowbackgrounddragbehavior(_:)
#app-main)
- SwiftUI
- Scene
- windowBackgroundDragBehavior(_:)
Instance Method
windowBackgroundDragBehavior(_:)
Configures the behavior of dragging a window by its background.
nonisolated
Parameters
behavior
The behavior of dragging the modified window by its background.
Return Value
A scene configured with the specified behavior of dragging it by its background background.
Discussion
By default, or when you apply the automatic behavior, the system will determine the best suitable behavior based on the configuration of the modified scene.
You can use this modifier to override the default behavior. For example, to always enable dragging a window by its background:
struct MyApp: App { var body: some Scene { Window("About MyApp", id: "about") { AboutView() } .windowBackgroundDragBehavior(.enabled) } }
If you want to let your users drag your window by a specific view instead of (or in addition to) letting them drag it by its background, use WindowDragGesture.
Applying the enabled behavior is equivalent to adding a WindowDragGesture to the window’s background view.
See Also
Managing window behavior
struct WindowManagerRole
Options for defining how a scene’s windows behave when used within a managed window context, such as full screen mode and Stage Manager.
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
struct WindowInteractionBehavior
Options for enabling and disabling window interaction behaviors.
Configures the dismiss functionality for the window enclosing self.
Configures the full screen functionality for the window enclosing self.
Configures the minimize functionality for the window enclosing self.
Configures the resize functionality for the window enclosing self.
https://developer.apple.com/documentation/swiftui/view/onvolumeviewpointchange(updatestrategy:initial:_:)
#app-main)
- SwiftUI
- View
- onVolumeViewpointChange(updateStrategy:initial:_:)
Instance Method
onVolumeViewpointChange(updateStrategy:initial:_:)
Adds an action to perform when the viewpoint of the volume changes.
@MainActor @preconcurrency func onVolumeViewpointChange( updateStrategy: VolumeViewpointUpdateStrategy = .supported, initial: Bool = true,
Parameters
updateStrategy
Whether the action should be run for all viewpoint changes or only for supported viewpoint changes.
initial
Whether the action should be run when this view initially appears.
action
A closure to run when the viewpoint changes. The closure is also run when the volume is first opened if initial is true.
Discussion
Use the provided Viewpoint3D to update the content of the volume:
struct RobotContentView: View { @State var robotRotation: Rotation3D = .identity
var body: some View { Model3D(named: "robot") .onVolumeViewpointChange { _, newValue in robotRotation = Rotation3D.slerp( from: robotRotation, to: newValue.squareAzimuth.orientation, t: 1.0, along: .shortest ) } .rotation3DEffect(robotRotation) .animation(.easeInOut, value: robotRotation) } }
By default, the action will only be run when the new viewpoint is equivalent to one of the values provided through supportedVolumeViewpoints(_:). The viewpoint will be equivalent to where the window bar and ornaments are presented for a volume. Providing .all for the updateStrategy argument will result in the action being called without regard to the supported viewpoints.
To determine if the volume is being viewed from an unsupported viewpoint, provide .all for the updateStrategy argument and check if the viewpoint is not within the supported viewpoints:
struct ContentView: View { @State var showingMoveToFrontSign = false @State var moveToFrontSignViewpoint: Viewpoint3D = .standard
let supportedViewpoints = [SquareAzimuth.front]
var body: some View { MoveToFrontSignView(viewpoint: moveToFrontSignViewpoint) .opacity(showingMoveToFrontSign ? 1.0 : 0.0) .animation(.easeInOut, value: showingMoveToFrontSign) .onVolumeViewpointChange(updateStrategy: .all) { _, newValue in
moveToFrontSignViewpoint = newViewpoint
let isSupported = supportedViewpoints.contains( newViewpoint.squareAzimuth) showingMoveToFrontSign = !isSupported } .supportedVolumeViewpoints(supportedViewpoints) } }
The old and new Viewpoint3D provided to the action are relative to the center of the volume.
Reading this value is only valid inside a View that inherits the environment of a Scene created with a VolumetricWindowStyle.
See Also
Interacting with volumes
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/view/supportedvolumeviewpoints(_:)
#app-main)
- SwiftUI
- View
- supportedVolumeViewpoints(_:)
Instance Method
supportedVolumeViewpoints(_:)
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
nonisolated
Discussion
This defaults to all viewpoints and determines which viewpoints the window bar and ornaments will ‘follow’ the user to as they move around the volume.
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/volumeviewpointupdatestrategy
- SwiftUI
- VolumeViewpointUpdateStrategy
Structure
VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct VolumeViewpointUpdateStrategy
Topics
Type Properties
static let all: VolumeViewpointUpdateStrategy
The action should be run for all viewpoint changes.
static let supported: VolumeViewpointUpdateStrategy
The action should only be run when the new viewpoint is equivalent to one of the values provided through supportedVolumeViewpoints(_:).
Relationships
Conforms To
EquatableSendableSendableMetatype
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/viewpoint3d
- SwiftUI
- Viewpoint3D
Structure
Viewpoint3D
A type describing what direction something is being viewed from.
struct Viewpoint3D
Topics
Instance Properties
var squareAzimuth: SquareAzimuth
A value describing what direction something is being viewed from along the horizontal plane.
Type Properties
static let standard: Viewpoint3D
A value that represents being viewed from the front middle.
Relationships
Conforms To
CustomDebugStringConvertibleEquatableSendableSendableMetatype
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/squareazimuth
- SwiftUI
- SquareAzimuth
Enumeration
SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
@frozen enum SquareAzimuth
Topics
Structures
struct Set
Enumeration Cases
case back
Has an orientation with an horizontal angle equal to 180°
case front
Has an orientation with an horizontal angle equal to 0°.
case left
Has an orientation with an horizontal angle equal to 270°.
case right
Has an orientation with an horizontal angle equal to 90°.
Initializers
init(closestToAzimuth: Angle)
Creates a SquareAzimuth case with an orientation that has a horizontal angle closest to the provided azimuth.
Instance Properties
var orientation: Rotation3D
A 3D rotation that is snapped to the center of one of the four sides.
Relationships
Conforms To
BitwiseCopyableCaseIterableCopyableEquatableHashableSendableSendableMetatype
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/worldalignmentbehavior
- SwiftUI
- WorldAlignmentBehavior
Structure
WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
struct WorldAlignmentBehavior
Overview
A value of this type can be provided to the volumeWorldAlignment(_:) scene modifier to control the world alignment volumes should maintain as they are repositioned. The default value is automatic.
Topics
Type Properties
static var adaptive: WorldAlignmentBehavior
When lifted above eye level, the volume will tilt so the front remains fully visible.
static var automatic: WorldAlignmentBehavior
The world alignment behavior that is standard for the system.
static var gravityAligned: WorldAlignmentBehavior
The volume will not tilt so as to remain aligned with gravity.
Relationships
Conforms To
EquatableSendableSendableMetatype
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/scene/volumeworldalignment(_:)
#app-main)
- SwiftUI
- Scene
- volumeWorldAlignment(_:)
Instance Method
volumeWorldAlignment(_:)
Specifies how a volume should be aligned when moved in the world.
nonisolated
Discussion
For example, you can create a volume that remains parallel to the floor even when lifted up high above eye level by applying a gravityAligned alignment to the scene:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } .windowStyle(.volumetric) .volumeWorldAlignment(.gravityAligned) } }
The default value if you don’t apply the modifier is automatic. With that strategy, volumes will tilt themselves so the front remains fully visible while being repositioned.
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/worldscalingbehavior
- SwiftUI
- WorldScalingBehavior
Structure
WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
struct WorldScalingBehavior
Overview
By default, a regular WindowGroup uses a scaling behavior of dynamic, and a window with volumetric has a fixed scale.
Dynamic scale means the window will scale larger as it moves further away, maintaining the same angular size. Fixed scale means the window will keep its physical size in the world.
For further information, see Spatial layout in the Human Interface Guidelines.
Topics
Type Properties
static var automatic: WorldScalingBehavior
The scaling behavior that is standard for the window’s style.
static var dynamic: WorldScalingBehavior
The window will scale up as it moves further away, maintaining the same angular size.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/scene/defaultworldscaling(_:)
#app-main)
- SwiftUI
- Scene
- defaultWorldScaling(_:)
Instance Method
defaultWorldScaling(_:)
Specify the world scaling behavior for the window.
nonisolated
Discussion
By default, regular windows increase their physical size as they move further away, ensuring they remain at the same angular size. This preserves legibility and ease of use for text and controls. Volumes render with a fixed physical size, because they are most commonly used for 3D content which is meant to behave with greater physical accuracy.
This modifier overrides the physical scaling behavior for volumes, so they scale like windows while still maintaining other volumetric behaviors.
This modifier has no effect on immersive spaces or windows without a window style of volumetric.
@main struct SampleApp: App { var body: some Scene { WindowGroup { ContentView() } .windowStyle(.volumetric) .defaultWorldScaling(.dynamic) } }
For further information, see Spatial layout in the Human Interface Guidelines.
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/worldscalingcompensation
- SwiftUI
- WorldScalingCompensation
Structure
WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
struct WorldScalingCompensation
Overview
On visionOS, a window scene or a volume scene with the defaultWorldScaling(_:) modifier may scale dynamically when the user repositions it. In those cases, the metrics returned by a PhysicalMetric or PhysicalMetricsConverter value may or may not correspond to the units of a RealityView.
World scale compensation lets you specify if this scaling is taken into account. If the values are unscaled, they will correspond to the physical metrics of the user’s surroundings, regardless of dynamic scale. If scaled, they will be scaled appropriately for the scene, which means they will match the default coordinate system of a RealityView in that scene.
Topics
Type Properties
static let scaled: WorldScalingCompensation
Returns metrics that are scaled appropriately to match the coordinate system of their scene, including any world scaling behavior.
static let unscaled: WorldScalingCompensation
Returns metrics that match the scale of the user’s surroundings, regardless of the world scaling behavior of their scene.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
https://developer.apple.com/documentation/swiftui/environmentvalues/worldtrackinglimitations
- SwiftUI
- EnvironmentValues
- worldTrackingLimitations
Instance Property
worldTrackingLimitations
The current limitations of the device tracking the user’s surroundings.
Discussion
Read this environment value from within a view to obtain the current limitations of the device tracking the user’s surroundings. The device’s capabilities may be limited due to physical circumstances such as the lighting. If any of the limitations occur due to changing circumstances, the set is updated accordingly. For example, the following Text view automatically updates when the world tracking limitations change:
@Environment(.worldTrackingLimitations) private var worldTrackingLimitations
var body: some View { Text("Can track translation?" + worldTrackingLimitations .contains(.translation) ? "No" : "Yes") }
When the device’s world tracking capabilities are limited, don’t prevent the user from experiencing your app entirely. Instead, try to adapt the user experience to the current circumstances in order to provide a meaningful experience at all times.
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/worldtrackinglimitation
- SwiftUI
- WorldTrackingLimitation
Structure
WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
struct WorldTrackingLimitation
Overview
You receive a set of world tracking limitations when you read the worldTrackingLimitations environment value. The value tells you which limitations the device currently is facing. If any of the limitations occur due to changing circumstances, e.g., the lighting, the set is updated accordingly. For example, the following Text view automatically updates when the world tracking limitations change:
@Environment(.worldTrackingLimitations) private var worldTrackingLimitations
var body: some View { Text("Can track translation?" + worldTrackingLimitations .contains(.translation) ? "No" : "Yes") }
Topics
Type Properties
static let orientation: WorldTrackingLimitation
The device capabilities of tracking orientation changes in all dimensions are currently limited.
static let translation: WorldTrackingLimitation
The device capabilities of tracking translation changes in all dimensions are currently limited.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct SurfaceSnappingInfo
A type representing information about the window scenes snap state.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/surfacesnappinginfo
- SwiftUI
- SurfaceSnappingInfo Beta
Structure
SurfaceSnappingInfo
A type representing information about the window scenes snap state.
struct SurfaceSnappingInfo
Overview
Use the provided SurfaceSnappingInfo to modify the contents of your view.
struct LightFixtureView: View { @Environment(.surfaceSnappingInfo) var snappingInfo: SurfaceSnappingInfo
var body: some View { if snappingInfo.isSnapped { switch SurfaceSnappingInfo.authorizationStatus { case .authorized: switch snappingInfo.classification { case .table: LampView() case .floor: FloorLampView() default: DefaultLampView() } default: DefaultLampView() } } else { FloatingOrbLampView() } } }
The bottom of volumes may snap to horizontal surfaces and the back of windows may snap to vertical surfaces.
Topics
Instance Properties
var classification: SurfaceClassification?
A type that provides information about the surface classification the scene is snapped to. This property only has a value if the scene is snapped and authorizationStatus is .authorized.
var isSnapped: Bool
A value that represents whether the scene is currently snapped to a physical surface or not.
Type Properties
static var authorizationStatus: SurfaceSnappingInfo.AuthorizationStatus
A value that represents whether the user has authorized providing more detailed information about the surface scenes are snapped to. To request this detailed surface information, in your Info.plist file, set UIWantsDetailedSurfaceInfo to YES and set NSWorldSensingUsageDescription to provide a description of why your app is requesting this information.
Enumerations
enum AuthorizationStatus
A type representing whether the user has granted permissions to provide more detailed information about the surface a scene is snapped to.
Relationships
Conforms To
CustomDebugStringConvertibleEquatableSendableSendableMetatype
See Also
Interacting with volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
struct VolumeViewpointUpdateStrategy
A type describing when the action provided to onVolumeViewpointChange(updateStrategy:initial:_:) should be called.
struct Viewpoint3D
A type describing what direction something is being viewed from.
enum SquareAzimuth
A type describing what direction something is being viewed from along the horizontal plane and snapped to 4 directions.
struct WorldAlignmentBehavior
A type representing the world alignment behavior for a scene.
Specifies how a volume should be aligned when moved in the world.
struct WorldScalingBehavior
Specifies the scaling behavior a window should have within the world.
Specify the world scaling behavior for the window.
struct WorldScalingCompensation
Indicates whether returned metrics will take dynamic scaling into account.
The current limitations of the device tracking the user’s surroundings.
struct WorldTrackingLimitation
A structure to represent limitations of tracking the user’s surroundings.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/controlactivestate
- SwiftUI
- ControlActiveState Deprecated
Enumeration
ControlActiveState
The active appearance expected of controls in a window.
macOS 10.15–26.0Deprecated
enum ControlActiveState
Overview
ControlActiveState and EnvironmentValues.controlActiveState are deprecated, use EnvironmentValues.appearsActive instead.
Topics
Getting control active states
case key
case active
case inactive
Relationships
Conforms To
CaseIterableCopyableEquatableHashableSendableSendableMetatype
https://developer.apple.com/documentation/swiftui/windowgroup),
https://developer.apple.com/documentation/swiftui/window)
https://developer.apple.com/documentation/swiftui/scene/windowstyle(_:))
https://developer.apple.com/documentation/swiftui/scene/defaultposition(_:)).
https://developer.apple.com/documentation/swiftui/view/presentedwindowstyle(_:))
https://developer.apple.com/documentation/swiftui/customizing-window-styles-and-state-restoration-behavior-in-macos)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/bringing_multiple_windows_to_your_swiftui_app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/windowgroup)
https://developer.apple.com/documentation/swiftui/utilitywindow)
https://developer.apple.com/documentation/swiftui/windowstyle)
https://developer.apple.com/documentation/swiftui/scene/windowtoolbarstyle(_:))
https://developer.apple.com/documentation/swiftui/scene/windowtoolbarlabelstyle(_:))
https://developer.apple.com/documentation/swiftui/scene/windowtoolbarlabelstyle(fixed:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/windowtoolbarstyle)
https://developer.apple.com/documentation/swiftui/environmentvalues/supportsmultiplewindows)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/environmentvalues/openwindow)
https://developer.apple.com/documentation/swiftui/openwindowaction)
https://developer.apple.com/documentation/swiftui/pushwindowaction)
https://developer.apple.com/documentation/swiftui/environmentvalues/dismisswindow)
https://developer.apple.com/documentation/swiftui/dismisswindowaction)
https://developer.apple.com/documentation/swiftui/environmentvalues/dismiss)
https://developer.apple.com/documentation/swiftui/dismissaction)
https://developer.apple.com/documentation/swiftui/dismissbehavior)
https://developer.apple.com/documentation/swiftui/scene/defaultsize(_:))
https://developer.apple.com/documentation/swiftui/scene/defaultsize(width:height:))
https://developer.apple.com/documentation/swiftui/scene/defaultsize(width:height:depth:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/scene/defaultsize(_:in:))
https://developer.apple.com/documentation/swiftui/scene/defaultsize(width:height:depth:in:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/scene/windowresizability(_:))
https://developer.apple.com/documentation/swiftui/windowresizability)
https://developer.apple.com/documentation/swiftui/scene/windowidealsize(_:))
https://developer.apple.com/documentation/swiftui/windowidealsize)
https://developer.apple.com/documentation/swiftui/scene/defaultposition(_:))
https://developer.apple.com/documentation/swiftui/windowlevel)
https://developer.apple.com/documentation/swiftui/scene/windowlevel(_:))
https://developer.apple.com/documentation/swiftui/windowlayoutroot)
https://developer.apple.com/documentation/swiftui/windowplacement)
https://developer.apple.com/documentation/swiftui/scene/defaultwindowplacement(_:))
https://developer.apple.com/documentation/swiftui/scene/windowidealplacement(_:))
https://developer.apple.com/documentation/swiftui/windowplacementcontext)
https://developer.apple.com/documentation/swiftui/windowproxy)
https://developer.apple.com/documentation/swiftui/displayproxy)
https://developer.apple.com/documentation/swiftui/windowvisibilitytoggle)
https://developer.apple.com/documentation/swiftui/scene/defaultlaunchbehavior(_:))
https://developer.apple.com/documentation/swiftui/scene/restorationbehavior(_:))
https://developer.apple.com/documentation/swiftui/scenelaunchbehavior)
https://developer.apple.com/documentation/swiftui/scenerestorationbehavior)
https://developer.apple.com/documentation/swiftui/scene/persistentsystemoverlays(_:))
https://developer.apple.com/documentation/swiftui/view/windowtoolbarfullscreenvisibility(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/windowtoolbarfullscreenvisibility)
https://developer.apple.com/documentation/swiftui/windowmanagerrole)
https://developer.apple.com/documentation/swiftui/scene/windowmanagerrole(_:))
https://developer.apple.com/documentation/swiftui/windowinteractionbehavior)
https://developer.apple.com/documentation/swiftui/view/windowdismissbehavior(_:))
https://developer.apple.com/documentation/swiftui/view/windowfullscreenbehavior(_:))
https://developer.apple.com/documentation/swiftui/view/windowminimizebehavior(_:))
https://developer.apple.com/documentation/swiftui/view/windowresizebehavior(_:))
https://developer.apple.com/documentation/swiftui/scene/windowbackgrounddragbehavior(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/onvolumeviewpointchange(updatestrategy:initial:_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/supportedvolumeviewpoints(_:))
https://developer.apple.com/documentation/swiftui/volumeviewpointupdatestrategy)
https://developer.apple.com/documentation/swiftui/viewpoint3d)
https://developer.apple.com/documentation/swiftui/squareazimuth)
https://developer.apple.com/documentation/swiftui/worldalignmentbehavior)
https://developer.apple.com/documentation/swiftui/scene/volumeworldalignment(_:))
https://developer.apple.com/documentation/swiftui/worldscalingbehavior)
https://developer.apple.com/documentation/swiftui/scene/defaultworldscaling(_:))
https://developer.apple.com/documentation/swiftui/worldscalingcompensation)
https://developer.apple.com/documentation/swiftui/environmentvalues/worldtrackinglimitations)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/worldtrackinglimitation)
https://developer.apple.com/documentation/swiftui/surfacesnappinginfo)
https://developer.apple.com/documentation/swiftui/controlactivestate)
https://developer.apple.com/documentation/swiftui/navigationsplitview
- SwiftUI
- NavigationSplitView
Structure
NavigationSplitView
A view that presents views in two or three columns, where selections in leading columns control presentations in subsequent columns.
Mentioned in
Migrating to new navigation types
Adding a search interface to your app
Overview
You create a navigation split view with two or three columns, and typically use it as the root view in a Scene. People choose one or more items in a leading column to display details about those items in subsequent columns.
To create a two-column navigation split view, use the init(sidebar:detail:) initializer:
var body: some View { NavigationSplitView { List(model.employees, selection: $employeeIds) { employee in Text(employee.name) } } detail: { EmployeeDetails(for: employeeIds) } }
In the above example, the navigation split view coordinates with the List in its first column, so that when people make a selection, the detail view updates accordingly. Programmatic changes that you make to the selection property also affect both the list appearance and the presented detail view.
To create a three-column view, use the init(sidebar:content:detail:) initializer. The selection in the first column affects the second, and the selection in the second column affects the third. For example, you can show a list of departments, the list of employees in the selected department, and the details about all of the selected employees:
@State private var departmentId: Department.ID? // Single selection.
var body: some View { NavigationSplitView { List(model.departments, selection: $departmentId) { department in Text(department.name) } } content: { if let department = model.department(id: departmentId) { List(department.employees, selection: $employeeIds) { employee in Text(employee.name) } } else { Text("Select a department") } } detail: { EmployeeDetails(for: employeeIds) } }
You can also embed a NavigationStack in a column. Tapping or clicking a NavigationLink that appears in an earlier column sets the view that the stack displays over its root view. Activating a link in the same column adds a view to the stack. Either way, the link must present a data type for which the stack has a corresponding navigationDestination(for:destination:) modifier.
On watchOS and tvOS, and with narrow sizes like on iPhone or on iPad in Slide Over, the navigation split view collapses all of its columns into a stack, and shows the last column that displays useful information. For example, the three-column example above shows the list of departments to start, the employees in the department after someone selects a department, and the employee details when someone selects an employee. For rows in a list that have NavigationLink instances, the list draws disclosure chevrons while in the collapsed state.
Control column visibility
You can programmatically control the visibility of navigation split view columns by creating a State value of type NavigationSplitViewVisibility. Then pass a Binding to that state to the appropriate initializer — such as init(columnVisibility:sidebar:detail:) for two columns, or the init(columnVisibility:sidebar:content:detail:) for three columns.
The following code updates the first example above to always hide the first column when the view appears:
@State private var columnVisibility = NavigationSplitViewVisibility.detailOnly
var body: some View { NavigationSplitView(columnVisibility: $columnVisibility) { List(model.employees, selection: $employeeIds) { employee in Text(employee.name) } } detail: { EmployeeDetails(for: employeeIds) } }
The split view ignores the visibility control when it collapses its columns into a stack.
Collapsed split views
At narrow size classes, such as on iPhone or Apple Watch, a navigation split view collapses into a single stack. Typically SwiftUI automatically chooses the view to show on top of this single stack, based on the content of the split view’s columns.
For custom navigation experiences, you can provide more information to help SwiftUI choose the right column. Create a State value of type NavigationSplitViewColumn. Then pass a Binding to that state to the appropriate initializer, such as init(preferredCompactColumn:sidebar:detail:) or init(preferredCompactColumn:sidebar:content:detail:).
The following code shows the blue detail view when run on iPhone. When the person using the app taps the back button, they’ll see the yellow view. The value of preferredPreferredCompactColumn will change from .detail to .sidebar:
@State private var preferredColumn = NavigationSplitViewColumn.detail
var body: some View { NavigationSplitView(preferredCompactColumn: $preferredColumn) { Color.yellow } detail: { Color.blue } }
Customize a split view
To specify a preferred column width in a navigation split view, use the navigationSplitViewColumnWidth(_:) modifier. To set minimum, maximum, and ideal sizes for a column, use navigationSplitViewColumnWidth(min:ideal:max:). You can specify a different modifier in each column. The navigation split view does its best to accommodate the preferences that you specify, but might make adjustments based on other constraints.
To specify how columns in a navigation split view interact, use the navigationSplitViewStyle(_:) modifier with a NavigationSplitViewStyle value. For example, you can specify whether to emphasize the detail column or to give all of the columns equal prominence.
On some platforms, NavigationSplitView adds a sidebarToggle toolbar item. Use the toolbar(removing:) modifier to remove the default item.
Topics
Creating a navigation split view
Creates a two-column navigation split view.
Creates a three-column navigation split view.
Hiding columns in a navigation split view
Creates a two-column navigation split view that enables programmatic control of the sidebar’s visibility.
Creates a three-column navigation split view that enables programmatic control of leading columns’ visibility.
Specifying a preferred compact column
Creates a two-column navigation split view that enables programmatic control over which column appears on top when the view collapses into a single column in narrow sizes.
Creates a three-column navigation split view that enables programmatic control over which column appears on top when the view collapses into a single column in narrow sizes.
Specifying a preferred compact column and column visibility
Creates a two-column navigation split view that enables programmatic control of the sidebar’s visibility in regular sizes and which column appears on top when the view collapses into a single column in narrow sizes.
Creates a three-column navigation split view that enables programmatic control of leading columns’ visibility in regular sizes and which column appears on top when the view collapses into a single column in narrow sizes.
Relationships
Conforms To
View
See Also
Presenting views in columns
Bringing robust navigation structure to your SwiftUI app
Use navigation links, stacks, destinations, and paths to provide a streamlined experience for all platforms, as well as behaviors such as deep linking and state restoration.
Improve navigation behavior in your app by replacing navigation views with navigation stacks and navigation split views.
Sets the style for navigation split views within this view.
Sets a fixed, preferred width for the column containing this view.
Sets a flexible, preferred width for the column containing this view.
struct NavigationSplitViewVisibility
The visibility of the leading columns in a navigation split view.
struct NavigationLink
A view that controls a navigation presentation.
https://developer.apple.com/documentation/swiftui/image
https://developer.apple.com/documentation/swiftui/view/backgroundextensioneffect()
https://developer.apple.com/documentation/swiftui/landmarks-applying-a-background-extension-effect
https://developer.apple.com/documentation/swiftui/landmarks-extending-horizontal-scrolling-under-a-sidebar-or-inspector
- SwiftUI
- Landmarks: Building an app with Liquid Glass
- Landmarks: Extending horizontal scrolling under a sidebar or inspector Beta
Sample Code
Landmarks: Extending horizontal scrolling under a sidebar or inspector
Improve your horizontal scrollbar’s appearance by extending it under a sidebar or inspector.
Download
Xcode 26.0+Beta
Overview
The Landmarks app lets people explore interesting sites around the world. Whether it’s a national park near their home or a far-flung location on a different continent, the app provides a way for people to organize and mark their adventures and receive custom activity badges along the way.
This sample demonstrates how to extend horizontal scrolling under a sidebar or inspector. Within each continent section in LandmarksView, an instance of LandmarkHorizontalListView shows a horizontally scrolling list of landmark views. When open, the landmark views can scroll underneath the sidebar or inspector.
Configure the scroll view
To achieve this effect, the sample configures the LandmarkHorizontalListView so it touches the leading and trailing edges. When a scroll view touches the sidebar or inspector, the system automatically adjusts it to scroll under the sidebar or inspector and then off the edge of the screen.
The sample adds a Spacer at the beginning of the ScrollView to inset the content so it aligns with the title padding:
ScrollView(.horizontal, showsIndicators: false) { LazyHStack(spacing: Constants.standardPadding) { Spacer() .frame(width: Constants.standardPadding) ForEach(landmarkList) { landmark in //... } } }
See Also
App features
Landmarks: Applying a background extension effect
Configure an image to blur and extend under a sidebar or inspector panel.
Landmarks: Refining the system provided Liquid Glass effect in toolbars
Organize toolbars into related groupings to improve their appearance and utility.
Landmarks: Displaying custom activity badges
Provide people with a way to mark their adventures by displaying animated custom activity badges.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/landmarks-refining-the-system-provided-glass-effect-in-toolbars
- SwiftUI
- Landmarks: Building an app with Liquid Glass
- Landmarks: Refining the system provided Liquid Glass effect in toolbars Beta
Sample Code
Landmarks: Refining the system provided Liquid Glass effect in toolbars
Organize toolbars into related groupings to improve their appearance and utility.
Download
Xcode 26.0+Beta
Overview
The Landmarks app lets people explore interesting sites around the world. Whether it’s a national park near their home or a far-flung location on a different continent, the app provides a way for people to organize and mark their adventures and receive custom activity badges along the way.
This sample demonstrates how to refine the system provided glass effect in toolbars. In LandmarkDetailView, the sample adds toolbar items for:
-
sharing a landmark
-
adding or removing a landmark from a list of Favorites
-
adding or removing a landmark from Collections
-
showing or hiding the inspector
The system applies Liquid Glass to the toolbar items automatically.
Organize the toolbar items into logical groupings
To organize the toolbar items into logical groupings, the sample adds ToolbarSpacer items and passes fixed as the sizing parameter to divide the toolbar into sections:
.toolbar { ToolbarSpacer(.flexible)
ToolbarItem { ShareLink(item: landmark, preview: landmark.sharePreview) }
ToolbarSpacer(.fixed)
ToolbarItemGroup { LandmarkFavoriteButton(landmark: landmark) LandmarkCollectionsMenu(landmark: landmark) }
ToolbarItem { Button("Info", systemImage: "info") { modelData.selectedLandmark = landmark modelData.isLandmarkInspectorPresented.toggle() } } }
See Also
App features
Landmarks: Applying a background extension effect
Configure an image to blur and extend under a sidebar or inspector panel.
Landmarks: Extending horizontal scrolling under a sidebar or inspector
Improve your horizontal scrollbar’s appearance by extending it under a sidebar or inspector.
Landmarks: Displaying custom activity badges
Provide people with a way to mark their adventures by displaying animated custom activity badges.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/glasseffect(_:in:isenabled:)
#app-main)
- SwiftUI
- View
- glassEffect(_:in:isEnabled:) Beta
Instance Method
glassEffect(_:in:isEnabled:)
Applies the Liquid Glass effect to a view.
nonisolated func glassEffect( _ glass: Glass = .regular, in shape: some Shape = .capsule, isEnabled: Bool = true
Mentioned in
Applying Liquid Glass to custom views
Discussion
When you use this effect, the system:
-
Renders a shape anchored behind a view with the Liquid Glass material.
-
Applies the foreground effects of Liquid Glass over a view.
For example, to add this effect to a Text:
Text("Hello, World!") .font(.title) .padding() .glassEffect()
SwiftUI uses the regular variant by default along with a Capsule shape.
SwiftUI anchors the Liquid Glass to a view’s bounds. For the example above, the material fills the entirety of the Text frame, which includes the padding.
You typically use this modifier with a GlassEffectContainer to combine multiple Liquid Glass shapes into a single shape that can morph into one another.
See Also
Styling views with Liquid Glass
Configure, combine, and morph views using Liquid Glass effects.
Landmarks: Building an app with Liquid Glass
Enhance your app experience with system-provided and custom Liquid Glass.
Returns a copy of the structure configured to be interactive.
Beta
struct GlassEffectContainer
A view that combines multiple Liquid Glass shapes into a single shape that can morph individual shapes into one another.
struct GlassEffectTransition
A structure that describes changes to apply when a glass effect is added or removed from the view hierarchy.
struct GlassButtonStyle
A button style that applies glass border artwork based on the button’s context.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/glasseffectcontainer
https://developer.apple.com/documentation/swiftui/view/glasseffectid(_:in:)
#app-main)
- SwiftUI
- View
- glassEffectID(_:in:) Beta
Instance Method
glassEffectID(_:in:)
Associates an identity value to Liquid Glass effects defined within this view.
nonisolated func glassEffectID( _ id: (some Hashable & Sendable)?, in namespace: Namespace.ID
Mentioned in
Applying Liquid Glass to custom views
Discussion
You use this modifier with the glassEffect(_:in:isEnabled:) view modifier and a GlassEffectContainer view. When used together, SwiftUI uses the identifier to animate shapes to and from each other during transitions.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/landmarks-displaying-custom-activity-badges
https://developer.apple.com/documentation/swiftui/applying-liquid-glass-to-custom-views
- SwiftUI
- View styles
- Applying Liquid Glass to custom views
Article
Applying Liquid Glass to custom views
Configure, combine, and morph views using Liquid Glass effects.
Overview
Interfaces across Apple platforms feature a new dynamic material called Liquid Glass, which combines the optical properties of glass with a sense of fluidity. Liquid Glass is a material that blurs content behind it, reflects color and light of surrounding content, and reacts to touch and pointer interactions in real time. Standard components in SwiftUI use Liquid Glass. Adopt Liquid Glass on custom components to move, combine, and morph them into one another with unique animations and transitions.
To learn about Liquid Glass and more, see Landmarks: Building an app with Liquid Glass.
Apply and configure Liquid Glass effects
Use the glassEffect(_:in:isEnabled:) modifier to add Liquid Glass effects to a view. By default, the modifier uses the regular variant of Glass and applies the given effect within a Capsule shape behind the view’s content.
Configure the effect to customize your components in a variety of ways:
-
Use different shapes to have a consistent look and feel across custom components in your app. For example, use a rounded rectangle if you’re applying the effect to larger components that would look odd as a
CapsuleorCircle. -
Define a tint color to suggest prominence.
-
Add
interactive(_:)to custom components to make them react to touch and pointer interactions. This applies the same responsive and fluid reactions thatglassprovides to standard buttons.
In the examples below, observe how to apply Liquid Glass effects to a view, use an alternate shape with a specific corner radius, and create a tinted view that responds to interactivity:
Video with custom controls.
Content description: A video showing examples including a Text view with Liquid Glass effects applied, a Text view with a custom shape, corner radius effect, and Liquid Glass effects applied, and a Text view with an orange tint color effect that responds to interactivity, with Liquid Glass effects applied.
Play
Text("Hello, World!") .font(.title) .padding() .glassEffect()
Text("Hello, World!") .font(.title) .padding() .glassEffect(in: .rect(cornerRadius: 16.0))
Text("Hello, World!") .font(.title) .padding() .glassEffect(.regular.tint(.orange).interactive())
Combine multiple views with Liquid Glass containers
Use GlassEffectContainer when applying Liquid Glass effects on multiple views to achieve the best rendering performance. A container also allows views with Liquid Glass effects to blend their shapes together and to morph in and out of each other during transitions. Inside a container, each view with the glassEffect(_:in:isEnabled:) modifier renders with the effects behind it.
Customize the spacing on the container to set layout spacing between views and to affect how the Liquid Glass effects behind views interact with one another. Views close to one another merge their effects into a single shape. The farther views are from each other, the sooner the shapes merge into each other.
The .glassEffect() modifier captures the content to send to the container to render. Apply the .glassEffect() modifier after other modifiers that will affect the appearance of the view.
In the example below, two images are placed close to each other and the Liquid Glass effects begin to blend their shapes together. This creates a fluid animation as components move around each other within a container:
GlassEffectContainer(spacing: 40.0) { HStack(spacing: 40.0) { Image(systemName: "scribble.variable") .frame(width: 80.0, height: 80.0) .font(.system(size: 36)) .glassEffect()
Image(systemName: "eraser.fill") .frame(width: 80.0, height: 80.0) .font(.system(size: 36)) .glassEffect()
// An offset shows how Liquid Glass effects react to each other in a container.
// Use animations and components appearing and disappearing to obtain effects that look purposeful.
.offset(x: -40.0, y: 0.0)
}
}
In some cases, you want the geometries of multiple views to contribute to a single Liquid Glass effect capsule, even when your content is at rest. Use the glassEffectUnion(id:namespace:) modifier to specify that a view contributes to a united effect with a particular ID. This combines all effects with a similar shape, Liquid Glass effect, and ID into a single shape with the applied Liquid Glass material. This is especially useful when creating views dynamically, or with views that live outside of an HStack or VStack.
let symbolSet: [String] = ["cloud.bolt.rain.fill", "sun.rain.fill", "moon.stars.fill", "moon.fill"]
GlassEffectContainer(spacing: 20.0) { HStack(spacing: 20.0) { ForEach(symbolSet.indices, id: .self) { item in Image(systemName: symbolSet[item]) .frame(width: 80.0, height: 80.0) .font(.system(size: 36)) .glassEffect() .glassEffectUnion(id: item < 2 ? "1" : "2", namespace: namespace) } } }
Morph Liquid Glass effects during transitions
Morphing effects occur during transitions between views with Liquid Glass effects. Add these transitions to views with effects in a container by using the glassEffectID(_:in:) modifier.
Associate each Liquid Glass effect with a unique identifier within a namespace the Namespace property wrapper provides. These IDs ensure SwiftUI animates the same shapes correctly when a shape appears or disappears due to view hierarchy changes. SwiftUI uses the spacing provided to the effect container along with the geometry of the shapes themselves to determine appropriate shapes to morph into and out of.
In the example below, the eraser image transitions into and out of the pencil image when the isExpanded variable changes. The GlassEffectContainer has a spacing value of 40.0, and the HStack within it has a spacing of 40.0. This morphs the eraser image into the pencil image when the eraser’s nearest edge is less than or equal to the container’s spacing.
Content description: A video which shows two views, a scribble symbol on the left and a eraser symbol on the right, with Liquid Glass effects morphing in and out of each other as a button below them is pressed.
@State private var isExpanded: Bool = false @Namespace private var namespace
var body: some View { GlassEffectContainer(spacing: 40.0) { HStack(spacing: 40.0) { Image(systemName: "scribble.variable") .frame(width: 80.0, height: 80.0) .font(.system(size: 36)) .glassEffect() .glassEffectID("pencil", in: namespace)
if isExpanded { Image(systemName: "eraser.fill") .frame(width: 80.0, height: 80.0) .font(.system(size: 36)) .glassEffect() .glassEffectID("eraser", in: namespace) } } }
Button("Toggle") { withAnimation { isExpanded.toggle() } } .buttonStyle(.glass) }
See Also
Styling views with Liquid Glass
Landmarks: Building an app with Liquid Glass
Enhance your app experience with system-provided and custom Liquid Glass.
Applies the Liquid Glass effect to a view.
Beta
Returns a copy of the structure configured to be interactive.
struct GlassEffectContainer
A view that combines multiple Liquid Glass shapes into a single shape that can morph individual shapes into one another.
struct GlassEffectTransition
A structure that describes changes to apply when a glass effect is added or removed from the view hierarchy.
struct GlassButtonStyle
A button style that applies glass border artwork based on the button’s context.
https://developer.apple.com/documentation/swiftui/navigationsplitview)
https://developer.apple.com/documentation/swiftui/image)
https://developer.apple.com/documentation/swiftui/view/backgroundextensioneffect())
https://developer.apple.com/documentation/swiftui/landmarks-applying-a-background-extension-effect).
https://developer.apple.com/documentation/swiftui/landmarks-extending-horizontal-scrolling-under-a-sidebar-or-inspector).
.#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/landmarks-refining-the-system-provided-glass-effect-in-toolbars).
.#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/glasseffect(_:in:isenabled:))
https://developer.apple.com/documentation/swiftui/glasseffectcontainer),
https://developer.apple.com/documentation/swiftui/view/glasseffectid(_:in:)).
https://developer.apple.com/documentation/swiftui/landmarks-displaying-custom-activity-badges).
https://developer.apple.com/documentation/swiftui/applying-liquid-glass-to-custom-views).
.#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/landmarks-applying-a-background-extension-effect)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/landmarks-extending-horizontal-scrolling-under-a-sidebar-or-inspector)
https://developer.apple.com/documentation/swiftui/landmarks-refining-the-system-provided-glass-effect-in-toolbars)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/landmarks-displaying-custom-activity-badges)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/uiapplicationdelegateadaptor
- SwiftUI
- UIApplicationDelegateAdaptor
Structure
UIApplicationDelegateAdaptor
A property wrapper type that you use to create a UIKit app delegate.
@MainActor @preconcurrency @propertyWrapper
Mentioned in
Migrating to the SwiftUI life cycle
Overview
To handle app delegate callbacks in an app that uses the SwiftUI life cycle, define a type that conforms to the UIApplicationDelegate protocol, and implement the delegate methods that you need. For example, you can implement the application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method to handle remote notification registration:
class MyAppDelegate: NSObject, UIApplicationDelegate, ObservableObject { func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { // Record the device token. } }
Then use the UIApplicationDelegateAdaptor property wrapper inside your App declaration to tell SwiftUI about the delegate type:
@main struct MyApp: App { @UIApplicationDelegateAdaptor private var appDelegate: MyAppDelegate
var body: some Scene { ... } }
SwiftUI instantiates the delegate and calls the delegate’s methods in response to life cycle events. Define the delegate adaptor only in your App declaration, and only once for a given app. If you declare it more than once, SwiftUI generates a runtime error.
If your app delegate conforms to the ObservableObject protocol, as in the example above, then SwiftUI puts the delegate it creates into the Environment. You can access the delegate from any scene or view in your app using the EnvironmentObject property wrapper:
@EnvironmentObject private var appDelegate: MyAppDelegate
This enables you to use the dollar sign ( $) prefix to get a binding to published properties that you declare in the delegate. For more information, see projectedValue.
Scene delegates
Some iOS apps define a UIWindowSceneDelegate to handle scene-based events, like app shortcuts:
class MySceneDelegate: NSObject, UIWindowSceneDelegate, ObservableObject { func windowScene( _ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem
// Do something with the shortcut...
return true } }
You can provide this kind of delegate to a SwiftUI app by returning the scene delegate’s type from the application(_:configurationForConnecting:options:) method inside your app delegate:
extension MyAppDelegate { func application( _ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions
let configuration = UISceneConfiguration( name: nil, sessionRole: connectingSceneSession.role) if connectingSceneSession.role == .windowApplication { configuration.delegateClass = MySceneDelegate.self } return configuration } }
When you configure the UISceneConfiguration instance, you only need to indicate the delegate class, and not a scene class or storyboard. SwiftUI creates and manages the delegate instance, and sends it any relevant delegate callbacks.
As with the app delegate, if you make your scene delegate an observable object, SwiftUI automatically puts it in the Environment, from where you can access it with the EnvironmentObject property wrapper, and create bindings to its published properties.
Topics
Creating a delegate adaptor
init(_:)
Creates a UIKit app delegate adaptor using an observable delegate.
Getting the delegate adaptor
A projection of the observed object that provides bindings to its properties.
var wrappedValue: DelegateType
The underlying app delegate.
Relationships
Conforms To
DynamicPropertySendableSendableMetatype
See Also
Targeting iOS and iPadOS
UILaunchScreen
The user interface to show while an app launches.
UILaunchScreens
The user interfaces to show while an app launches in response to different URL schemes.
https://developer.apple.com/documentation/swiftui/backyard-birds-sample
- SwiftUI
- App organization
- Backyard Birds: Building an app with SwiftData and widgets
Sample Code
Backyard Birds: Building an app with SwiftData and widgets
Create an app with persistent data, interactive widgets, and an all new in-app purchase experience.
Download
Xcode 15.1+
Overview
Backyard Birds offers a rich environment in which you can watch the birds that visit your backyard garden. You can monitor their water and food supply to ensure they always have fresh water and plenty to eat, or upgrade the game using an in-app purchase to provide tastier food for the birds to eat.
The sample implements its data model using SwiftData for persistence, and integrates seamlessly with SwiftUI using the Observable protocol. The game’s widgets implement App Intents for interactive and configurable widgets. The in-app purchase experience uses the ProductView and SubscriptionStoreView from StoreKit.
You can access the source code for this sample on GitHub.
Configure the sample code project
To configure the Backyard Birds app to run on your devices, follow these steps:
-
Open the project in Xcode 15 or later.
-
Edit the multiplatform target’s scheme, and on the Options tab, choose the
Store.storekitfile for StoreKit configuration. -
Repeat the previous step for the watchOS target’s scheme.
-
Select the top-level Backyard Birds project.
-
For all targets, choose your team from the Team menu in the Signing & Capabilities pane so Xcode can automatically manage your provisioning profile.
Create a data-driven app
The app defines its data model by conforming the model objects to PersistentModel using the Model macro. Using the Attribute macro with the unique option ensures that the id property is unique.
@Model public class BirdSpecies { @Attribute(.unique) public var id: String public var naturalScale: Double public var isEarlyAccess: Bool public var parts: [BirdPart]
@Relationship(deleteRule: .cascade, inverse: \Bird.species) public var birds: [Bird] = []
public var info: BirdSpeciesInfo { BirdSpeciesInfo(rawValue: id) }
public init(info: BirdSpeciesInfo, naturalScale: Double = 1, isEarlyAccess: Bool = false, parts: [BirdPart]) { self.id = info.rawValue self.naturalScale = naturalScale self.isEarlyAccess = isEarlyAccess self.parts = parts } }
Construct interactive widgets
Backyard Birds displays interactive widgets by presenting a Button to refill a backyard’s supplies when the water and food are running low. The app does this by placing a Button in the widget’s view, and passing a ResupplyBackyardIntent instance to the init(intent:label:) initializer:
Button(intent: ResupplyBackyardIntent(backyard: BackyardEntity(from: snapshot.backyard))) { Label("Refill Water", systemImage: "arrow.clockwise") .foregroundStyle(.secondary) .frame(maxWidth: .infinity) .padding(.vertical, 8) .padding(.horizontal, 12) .background(.quaternary, in: .containerRelative) }
The app allows for configuration of the widget by implementing the WidgetConfigurationIntent protocol:
struct BackyardWidgetIntent: WidgetConfigurationIntent { static let title: LocalizedStringResource = "Backyard" static let description = IntentDescription("Keep track of your backyards.")
@Parameter(title: "Backyards", default: BackyardWidgetContent.all) var backyards: BackyardWidgetContent
@Parameter(title: "Backyard") var specificBackyard: BackyardEntity?
init(backyards: BackyardWidgetContent = .all, specificBackyard: BackyardEntity? = nil) { self.backyards = backyards self.specificBackyard = specificBackyard }
init() { }
static var parameterSummary: some ParameterSummary { When(.$backyards, .equalTo, BackyardWidgetContent.specific) { Summary { .$backyards .$specificBackyard } } otherwise: { Summary { .$backyards } } } }
Provide a new in-app purchase experience
The sample app uses ProductView to display several different bird food upgrades available for purchase on a store shelf. To prominently feature an in-app purchase item, the app uses the .productViewStyle(.large) modifier:
ProductView(id: product.id) { BirdFoodProductIcon(birdFood: birdFood, quantity: product.quantity) .bestBirdFoodValueBadge() } .padding(.vertical) .background(.background.secondary, in: .rect(cornerRadius: 20)) .productViewStyle(.large)
The Backyard Birds Pass page displays renewable subscriptions using the SubscriptionStoreView view. The app uses the PassMarketingContent view as the content of the SubscriptionStoreView:
SubscriptionStoreView( groupID: passGroupID, visibleRelationships: showPremiumUpgrade ? .upgrade : .all ) { PassMarketingContent(showPremiumUpgrade: showPremiumUpgrade) #if !os(watchOS) .containerBackground(for: .subscriptionStoreFullHeight) { SkyBackground() } #endif }
See Also
Creating an app
Destination Video
Leverage SwiftUI to build an immersive media experience in a multiplatform app.
Hello World
Use windows, volumes, and immersive spaces to teach people about the Earth.
Food Truck: Building a SwiftUI multiplatform app
Create a single codebase and app target for Mac, iPad, and iPhone.
Fruta: Building a Feature-Rich App with SwiftUI
Create a shared codebase to build a multiplatform app that offers widgets and an App Clip.
Migrating to the SwiftUI life cycle
Use a scene-based life cycle in SwiftUI while keeping your existing codebase.
protocol App
A type that represents the structure and behavior of an app.
https://developer.apple.com/documentation/swiftui/food_truck_building_a_swiftui_multiplatform_app
- SwiftUI
- Food Truck: Building a SwiftUI multiplatform app
Sample Code
Food Truck: Building a SwiftUI multiplatform app
Create a single codebase and app target for Mac, iPad, and iPhone.
Download
Xcode 14.3+
Overview
Using the Food Truck app, someone who operates a food truck can keep track of orders, discover the most-popular menu items, and check the weather at their destination. The sample implements the new NavigationSplitView to manage the app’s views, Layout modifiers to show the main interface and pending orders, Swift Charts to show trends, and WeatherService to get weather data. Food Truck also implements Live Activities to show the remaining order preparation time with ActivityKit on the lock screen, and with DynamicIsland on the home screen.
You can access the source code for this sample on GitHub.
The Food Truck sample project contains two types of app targets:
-
Simple app target you can build using personal team signing. This app runs in Simulator, and only requires a standard Apple ID to install on a device. It includes in-app purchase, and a widget extension that enable users to add a widget to their iOS Home Screen or the macOS Notification Center.
-
Full-featured Food Truck All app target. The full app runs in Simulator, and on devices with an Apple Developer membership. It also allows you to create and sign in with passkeys.
Configure the sample code project
To configure the Food Truck app without an Apple Developer account, follow these steps:
-
In the Food Truck target’s Signing & Capabilities panes click Add Account, and log in with your Apple ID.
-
Chose Your Name (Personal Team) from the team menu for the Food Truck and Widgets targets.
-
Build and run your app.
To configure the Food Truck All app to run on your devices, follow these steps:
-
Open the sample with Xcode 14.3 or later.
-
Select the top-level Food Truck project.
-
For all targets, choose your team from the Team menu in the Signing & Capabilities pane, so Xcode can automatically manage your provisioning profile.
-
Add the Associated Domains capability, and specify your domain with the
webcredentialsservice. For more information about thewebcredentialsservice, seeAssociated Domains Entitlement. -
Ensure an
apple-app-site-association(AASA) file is present on your domain, in the.well-knowndirectory, and it contains an entry for this app’s App ID for thewebcredentialsservice. For more information about theapple-app-site-associationfile, see Supporting associated domains. -
In the
AccountManager.swiftfile, replace all occurrences ofexample.comwith the name of your domain.
Create a multiplatform app
Food Truck is a multiplatform app, and there are no separate targets to run on macOS or iOS. Instead, there is only one app target that builds for macOS, iPadOS, and iOS.
Define a default navigation destination
The sample’s navigation interface consists of a NavigationSplitView with a Sidebar view, and a NavigationStack:
NavigationSplitView { Sidebar(selection: $selection) } detail: { NavigationStack(path: $path) { DetailColumn(selection: $selection, model: model) } }
At app launch, the sample presents the TruckView as the default view. The Panel enum encodes the views the user can select in the sidebar, and hence appear in the detail view. The value corresponding to TruckView is .truck, and the app sets this to be the default selection.
@State private var selection: Panel? = Panel.truck
Construct a dynamic layout
In the Truck view, the New Orders panel shows the five most-recent orders, and each order shows a DonutStackView, which is a diagonal stack of donut thumbnails. The Layout modifiers protocol allows the app to define a DiagonalDonutStackLayout that arranges the donut thumbnails into the diagonal layout. The layout’s placeSubviews(in:proposal:subviews:cache:) implementation calculates the donuts’ positions.
for index in subviews.indices { switch (index, subviews.count) { case (_, 1): subviews[index].place( at: center, anchor: .center, proposal: ProposedViewSize(size) )
case (_, 2): let direction = index == 0 ? -1.0 : 1.0 let offsetX = minBound * direction * 0.15 let offsetY = minBound * direction * 0.20 subviews[index].place( at: CGPoint(x: center.x + offsetX, y: center.y + offsetY), anchor: .center, proposal: ProposedViewSize(CGSize(width: size.width * 0.7, height: size.height * 0.7)) ) case (1, 3): subviews[index].place( at: center, anchor: .center, proposal: ProposedViewSize(CGSize(width: size.width * 0.65, height: size.height * 0.65)) )
case (_, 3): let direction = index == 0 ? -1.0 : 1.0 let offsetX = minBound * direction * 0.15 let offsetY = minBound * direction * 0.23 subviews[index].place( at: CGPoint(x: center.x + offsetX, y: center.y + offsetY), anchor: .center, proposal: ProposedViewSize(CGSize(width: size.width * 0.7, height: size.height * 0.65)) )
Display a chart of popular items
The sample contains several charts. The most popular items are shown on the TopFiveDonutsView. This chart is implemented in TopDonutSalesChart, which uses a BarMark to construct a bar chart.
Chart { ForEach(sortedSales) { sale in BarMark( x: .value("Donut", sale.donut.name), y: .value("Sales", sale.sales) ) .cornerRadius(6, style: .continuous) .foregroundStyle(.linearGradient(colors: [Color("BarBottomColor"), .accentColor], startPoint: .bottom, endPoint: .top)) .annotation(position: .top, alignment: .top) { Text(sale.sales.formatted()) .padding(.vertical, 4) .padding(.horizontal, 8) .background(.quaternary.opacity(0.5), in: Capsule()) .background(in: Capsule()) .font(.caption) } } }
The x axis of the chart shows labels with the names and thumbnails of the items that correspond to each data point.
.chartXAxis { AxisMarks { value in AxisValueLabel { let donut = donutFromAxisValue(for: value) VStack { DonutView(donut: donut) .frame(height: 35)
Text(donut.name) .lineLimit(2, reservesSpace: true) .multilineTextAlignment(.center) } .frame(idealWidth: 80) .padding(.horizontal, 4)
} } }
Obtain a weather forecast
The app shows a forecasted temperature graph in the Forecast panel in the Truck view. The app obtains this data from the WeatherKit framework.
.task(id: city.id) { for parkingSpot in city.parkingSpots { do { let weather = try await WeatherService.shared.weather(for: parkingSpot.location) condition = weather.currentWeather.condition
cloudCover = weather.currentWeather.cloudCover temperature = weather.currentWeather.temperature symbolName = weather.currentWeather.symbolName
let attribution = try await WeatherService.shared.attribution attributionLink = attribution.legalPageURL attributionLogo = colorScheme == .light ? attribution.combinedMarkLightURL : attribution.combinedMarkDarkURL
if willRainSoon == false { spot = parkingSpot break } } catch { print("Could not gather weather information...", error.localizedDescription) condition = .clear willRainSoon = false cloudCover = 0.15 } } }
Configure the project for WeatherKit
The data from the WeatherService instance in WeatherKit requires additional configuration for the Food Truck All target. If you don’t configure WeatherKit, the sample will detect an error and use static data in the project instead.
-
Create a unique App ID on the Provisioning Portal, and select the WeatherKit service on the App Services tab.
-
In Xcode, for the Food Truck All target on the Signing & Capabilities tab, change the bundle ID to be the same as the App ID from step 1, and add the WeatherKit capability.
-
For the Widgets target on the Signing & Capabilities tab, change the bundle ID to make the part before
.Widgetsthe same as the bundle ID for the Food Truck All target. -
Wait 30 minutes while the service registers your app’s bundle ID.
-
Build and run the Food Truck All target.
Track preparation time with Live Activity
The app allows the food truck operator to keep track of order preparation time, which is guaranteed to be 60 seconds or less. To facilitate this, the app implements a toolbar button on the order details screen for orders with placed status. Tapping this button changes the order status to preparing, and creates an Activity instance to start a Live Activity, which shows the countdown timer and order details on an iPhone lock screen.
let timerSeconds = 60 let activityAttributes = TruckActivityAttributes( orderID: String(order.id.dropFirst(6)), order: order.donuts.map(.id), sales: order.sales, activityName: "Order preparation activity." )
let future = Date(timeIntervalSinceNow: Double(timerSeconds))
let initialContentState = TruckActivityAttributes.ContentState(timerRange: Date.now...future)
let activityContent = ActivityContent(state: initialContentState, staleDate: Calendar.current.date(byAdding: .minute, value: 2, to: Date())!)
do {
pushType: nil) print(" Requested MyActivity live activity. ID: (myActivity.id)") postNotification() } catch let error { print("Error requesting live activity: (error.localizedDescription)") }
The app also implements DynamicIsland to show the same information as on the lock screen in the Dynamic Island on iPhone 14 Pro devices.
DynamicIsland { DynamicIslandExpandedRegion(.leading) { ExpandedLeadingView() }
DynamicIslandExpandedRegion(.trailing, priority: 1) { ExpandedTrailingView(orderNumber: context.attributes.orderID, timerInterval: context.state.timerRange) .dynamicIsland(verticalPlacement: .belowIfTooWide) } } compactLeading: { Image("IslandCompactIcon") .padding(4) .background(.indigo.gradient, in: ContainerRelativeShape())
} compactTrailing: { Text(timerInterval: context.state.timerRange, countsDown: true) .monospacedDigit() .foregroundColor(Color("LightIndigo")) .frame(width: 40) } minimal: { Image("IslandCompactIcon") .padding(4) .background(.indigo.gradient, in: ContainerRelativeShape()) } .contentMargins(.trailing, 32, for: .expanded) .contentMargins([.leading, .top, .bottom], 6, for: .compactLeading) .contentMargins(.all, 6, for: .minimal) .widgetURL(URL(string: "foodtruck://order/(context.attributes.orderID)"))
Tapping the same button again changes the status to complete, and ends the Live Activity. This removes the Live Activity from the lock screen and from the Dynamic Island.
Task {
// Check if this is the activity associated with this order. if activity.attributes.orderID == String(order.id.dropFirst(6)) { await activity.end(nil, dismissalPolicy: .immediate) } } }
https://developer.apple.com/documentation/swiftui/migrating-to-the-swiftui-life-cycle
- SwiftUI
- App organization
- Migrating to the SwiftUI life cycle
Article
Migrating to the SwiftUI life cycle
Use a scene-based life cycle in SwiftUI while keeping your existing codebase.
Overview
Take advantage of the declarative syntax in SwiftUI and its compatibility with spatial frameworks by moving your app to the SwiftUI life cycle.
Moving to the SwiftUI life cycle requires several steps, including changing your app’s entry point, configuring the launch of your app, and monitoring life-cycle changes with the methods that SwiftUI provides.
Change your app’s entry point
The UIKit framework defines the AppDelegate file as the entry point of your app with the annotation @main. For more information on @main, see the Attributes section in The Swift Programming Language. To indicate the entry of a SwiftUI app, you’ll need to create a new file that defines your app’s structure.
-
Open your project in Xcode.
-
Add
import SwiftUIat the top of the file. -
Annotate the app structure with the
@mainattribute to indicate the entry point of the SwiftUI app, as shown in the code snippet below.
Use following code to create the SwiftUI app structure. To learn more about this structure, follow the tutorial in Exploring the structure of a SwiftUI app.
import SwiftUI
@main struct MyExampleApp: App { var body: some Scene { WindowGroup { ContentView() } } }
Support app delegate methods
To continue using methods in your app delegate, use the UIApplicationDelegateAdaptor property wrapper. To tell SwiftUI about a delegate that conforms to the UIApplicationDelegate protocol, place this property wrapper inside your App declaration:
@main struct MyExampleApp: App { @UIApplicationDelegateAdaptor private var appDelegate: MyAppDelegate var body: some Scene { ... } }
This example marks a custom app delegate named MyAppDelegate as the delegate adaptor. Be sure to implement any necessary delegate methods in that type.
Configure the launch of your app
If you’re migrating an app that contains storyboards to SwiftUI, make sure to remove them when they’re no longer needed.
-
Remove
Main.storyboardfrom the project navigator. -
Choose your app’s target.
-
Open the
Info.plistfile. -
Remove the
Main storyboard file base namekey.
This figure shows the structure of the Info.plist file before removing these keys.
The scene delegate continues to be called after removing the keys from the Info.plist file, so you can still handle other scene-based life cycle changes in this file. If you were previously launching your app in your scene delegate, remove the scene(_:willConnectTo:options:) method from your scene delegate.
If you didn’t previously support scenes in your app and rely on your app delegate to respond to the launch of your app, ensure you’re no longer setting a root view controller in application(_:didFinishLaunchingWithOptions:). Instead, return true.
Monitor life cycle changes
You will no longer be able to monitor life-cycle changes in your app delegate due to the scene-based nature of SwiftUI (see Scene). Prefer to handle these changes in ScenePhase, the life cycle enumeration that SwiftUI provides to monitor the phases of a scene. Observe the Environment value to initiate actions when the phase changes.
@Environment(.scenePhase) private var scenePhase
Interpret the value differently based on where you read it from. If you read the phase from inside a View instance, the value reflects the phase of the scene that contains the view. If you read the phase from within an App instance, the value reflects an aggregation of the phases of all of the scenes in your app.
To handle scene-based events with a scene delegate, provide your scene delegate to your SwiftUI app inside your app delegate. For more information, see the “Scene delegates” section of UIApplicationDelegateAdaptor.
For more information on handling scene-based life cycle events, see Managing your app’s life cycle.
See Also
Creating an app
Destination Video
Leverage SwiftUI to build an immersive media experience in a multiplatform app.
Hello World
Use windows, volumes, and immersive spaces to teach people about the Earth.
Backyard Birds: Building an app with SwiftData and widgets
Create an app with persistent data, interactive widgets, and an all new in-app purchase experience.
Food Truck: Building a SwiftUI multiplatform app
Create a single codebase and app target for Mac, iPad, and iPhone.
Fruta: Building a Feature-Rich App with SwiftUI
Create a shared codebase to build a multiplatform app that offers widgets and an App Clip.
protocol App
A type that represents the structure and behavior of an app.
https://developer.apple.com/documentation/swiftui/nsapplicationdelegateadaptor
- SwiftUI
- NSApplicationDelegateAdaptor
Structure
NSApplicationDelegateAdaptor
A property wrapper type that you use to create an AppKit app delegate.
@MainActor @preconcurrency @propertyWrapper
Mentioned in
Migrating to the SwiftUI life cycle
Overview
To handle app delegate callbacks in an app that uses the SwiftUI life cycle, define a type that conforms to the NSApplicationDelegate protocol, and implement the delegate methods that you need. For example, you can implement the application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method to handle remote notification registration:
class MyAppDelegate: NSObject, NSApplicationDelegate, ObservableObject { func application( _ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { // Record the device token. } }
Then use the NSApplicationDelegateAdaptor property wrapper inside your App declaration to tell SwiftUI about the delegate type:
@main struct MyApp: App { @NSApplicationDelegateAdaptor private var appDelegate: MyAppDelegate
var body: some Scene { ... } }
SwiftUI instantiates the delegate and calls the delegate’s methods in response to life cycle events. Define the delegate adaptor only in your App declaration, and only once for a given app. If you declare it more than once, SwiftUI generates a runtime error.
If your app delegate conforms to the ObservableObject protocol, as in the example above, then SwiftUI puts the delegate it creates into the Environment. You can access the delegate from any scene or view in your app using the EnvironmentObject property wrapper:
@EnvironmentObject private var appDelegate: MyAppDelegate
This enables you to use the dollar sign ( $) prefix to get a binding to published properties that you declare in the delegate. For more information, see projectedValue.
Topics
Creating a delegate adaptor
init(_:)
Creates an AppKit app delegate adaptor using an observable delegate.
Getting the delegate adaptor
A projection of the observed object that provides bindings to its properties.
var wrappedValue: DelegateType
The underlying delegate.
Relationships
Conforms To
DynamicPropertySendableSendableMetatype
https://developer.apple.com/documentation/swiftui/wkapplicationdelegateadaptor
- SwiftUI
- WKApplicationDelegateAdaptor
Structure
WKApplicationDelegateAdaptor
A property wrapper that is used in App to provide a delegate from WatchKit.
@MainActor @preconcurrency @propertyWrapper
Mentioned in
Migrating to the SwiftUI life cycle
Topics
Creating a delegate adaptor
init(_:)
Creates an WKApplicationDelegateAdaptor using a WatchKit Application Delegate.
Getting the delegate adaptor
A projection of the observed object that creates bindings to its properties using dynamic member lookup.
var wrappedValue: DelegateType
The underlying delegate.
Relationships
Conforms To
DynamicPropertySendableSendableMetatype
See Also
Targeting watchOS
struct WKExtensionDelegateAdaptor
A property wrapper type that you use to create a WatchKit extension delegate.
https://developer.apple.com/documentation/swiftui/wkextensiondelegateadaptor
- SwiftUI
- WKExtensionDelegateAdaptor
Structure
WKExtensionDelegateAdaptor
A property wrapper type that you use to create a WatchKit extension delegate.
@MainActor @preconcurrency @propertyWrapper
Overview
To handle extension delegate callbacks in an extension that uses the SwiftUI life cycle, define a type that conforms to the WKExtensionDelegate protocol, and implement the delegate methods that you need. For example, you can implement the didRegisterForRemoteNotifications(withDeviceToken:) method to handle remote notification registration:
class MyExtensionDelegate: NSObject, WKExtensionDelegate, ObservableObject { func didRegisterForRemoteNotifications(withDeviceToken: Data) { // Record the device token. } }
Then use the WKExtensionDelegateAdaptor property wrapper inside your App declaration to tell SwiftUI about the delegate type:
@main struct MyApp: App { @WKExtensionDelegateAdaptor private var extensionDelegate: MyExtensionDelegate
var body: some Scene { ... } }
SwiftUI instantiates the delegate and calls the delegate’s methods in response to life cycle events. Define the delegate adaptor only in your App declaration, and only once for a given extension. If you declare it more than once, SwiftUI generates a runtime error.
If your extension delegate conforms to the ObservableObject protocol, as in the example above, then SwiftUI puts the delegate it creates into the Environment. You can access the delegate from any scene or view in your extension using the EnvironmentObject property wrapper:
@EnvironmentObject private var extensionDelegate: MyExtensionDelegate
This enables you to use the dollar sign ( $) prefix to get a binding to published properties that you declare in the delegate. For more information, see projectedValue.
Topics
Creating a delegate adaptor
init(_:)
Creates a WatchKit extension delegate adaptor using an observable delegate.
Getting the delegate adaptor
A projection of the observed object that provides bindings to its properties.
var wrappedValue: DelegateType
The underlying delegate.
Relationships
Conforms To
DynamicPropertySendableSendableMetatype
See Also
Targeting watchOS
struct WKApplicationDelegateAdaptor
A property wrapper that is used in App to provide a delegate from WatchKit.
https://developer.apple.com/documentation/swiftui/creating-a-tvos-media-catalog-app-in-swiftui
- SwiftUI
- App organization
- Creating a tvOS media catalog app in SwiftUI
Sample Code
Creating a tvOS media catalog app in SwiftUI
Build standard content lockups and rows of content shelves for your tvOS app.
Download
Xcode 16.0+
Overview
This sample code project shows how to create the standard content lockups for tvOS, and provides best practices for building out rows of content shelves. It also includes examples for product pages, search views, and tab views, including the new sidebar adaptive tab view style that provides a sidebar in tvOS.
The sample project contains the following examples:
-
StackViewimplements an example landing page for a content catalog app, defining several shelves with a showcase or hero header area above them. It also gives an example of an above- and below-the-fold switching animation. -
ButtonsViewprovides a showcase of the various button styles available in tvOS. -
DescriptionViewprovides an example of how to build a product page similar to those you see on the Apple TV app, with a custom material blur. -
SearchViewshows an example of a simple search page using thesearchable(text:placement:prompt:)andsearchSuggestions(_:)modifiers. -
SidebarContentViewshows how to make a sectioned sidebar using the new tab bar APIs in tvOS 18. -
HeroHeaderViewgives an example of creating a material gradient to blur content in a certain area, fading it into unblurred content.
Create content lockups
The borderless button style provides the primary lockup style you use in tvOS, including all the focus interactions and hover effects. The button’s title and any nearby section titles automatically move out of the way of the button’s image as it scales up on focus.
Provide a separate Image and Text view in the button’s label closure to ensure the correct vertical appearance. Using a Label usually results in a horizontal layout, and, depending on the current label style, may not give you the appearance you expect.
Button { /* action */ } label: { Image("discovery_portrait") .resizable() .frame(width: 250, height: 375) Text("Borderless Portrait") }
By default, the button style locates the first Image within the button’s label and attaches a highlight hover effect to it, providing lift, a specular highlight, and gimbal motion effects.
To ensure the hover effect applies to exactly the right view, you can manually attach it to a particular subview of the button’s label using the hoverEffect(_:) modifier. For instance, to ensure an SF Symbols image hovers along with its background, do the following:
Button { /* action */ } label: { Image(systemName: "person.circle") .font(.title) .background(Color.blue.grayscale(0.7)) .hoverEffect(.highlight) Text("Shaped") } .buttonBorderShape(.circle)
You can also attach the hover effect to a custom view.
Button { /* action */ } label: { CodeSampleArtwork(size: .appIconSize) .frame(width: 400, height: 240) .hoverEffect(.highlight) Text("Custom Icon View") }
Show information-dense lockups
For lockups with more dense information, consider using the card button style, which provides a platter and a more subtle motion effect on focus. Providing containers with padding as the button’s label gives you something similar to the search result lockups on the Apple TV app.
Button { /* action */ } label: { HStack(alignment: .top, spacing: 10) { Image( . . . ) .resizable() .aspectRatio(contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 12))
VStack(alignment: .leading) { Text(asset.title) .font(.body) Text("Subtitle text goes here, limited to two lines.") .font(.caption2) .foregroundStyle(.secondary) .lineLimit(2) Spacer(minLength: 0) HStack(spacing: 4) { ForEach(1..<4) { _ in Image(systemName: "ellipsis.rectangle.fill") } } .foregroundStyle(.secondary) } } .padding(12) }
You can also use a custom LabelStyle to create a standard card-based lockup appearance while keeping your button’s declarations clean at the point of use.
struct CardOverlayLabelStyle: LabelStyle {
ZStack(alignment: .bottomLeading) {
configuration.icon
.resizable()
.aspectRatio(400/240, contentMode: .fit)
.overlay {
LinearGradient(
stops: [
.init(color: .black.opacity(0.6), location: 0.1),
.init(color: .black.opacity(0.2), location: 0.25),
.init(color: .black.opacity(0), location: 0.4)
],
startPoint: .bottom, endPoint: .top
)
}
.overlay {
RoundedRectangle(cornerRadius: 12)
.stroke(lineWidth: 2)
.foregroundStyle(.quaternary)
}
configuration.title .font(.caption.bold()) .foregroundStyle(.secondary) .padding(6) } .frame(maxWidth: 400) } }
Button { /* action */ } label: { Label("Title at the bottom", image: "discovery_landscape") }
Display content shelves
Content shelves are usually horizontal stacks in scroll views.
Disabling scroll clipping is necessary to allow the focus effects to scale up and lift each lockup. Shelves typically contain only a single style of lockup, so assign your button style on the outside of the shelf container.
ScrollView(.horizontal) { LazyHStack(spacing: 40) { ForEach(Asset.allCases) { asset in // . . . } } } .scrollClipDisabled() .buttonStyle(.borderless)
To arrange your lockups nicely, use the containerRelativeFrame(_:count:span:spacing:alignment:) modifier to let SwiftUI determine the best size for each. You can specify how many lockups you want on the screen, and the amount of spacing your stack view provides. Then SwiftUI arranges the content so that the edges of the leading and trailing items align with the leading and trailing safe area insets of its container.
For borderless buttons, you can attach the modifier to the Image instance within the button’s label closure to make the image the source of the frame calculations and alignments.
asset.portraitImage .resizable() .aspectRatio(250 / 375, contentMode: .fit) .containerRelativeFrame(.horizontal, count: 6, spacing: 40) Text(asset.title)
Show content above and below the fold
For a landing page you can implement above- and below-the-fold appearances through a combination of ScrollTargetBehavior and a background view with a gradient mask.
Define your showcase or header section as a stack with a container relative frame to make it take up a particular percentage of the available space. Attach a focusSection() modifier to the stack as well, so that its full width can act as a target for focus movement, which it then diverts to its content. Otherwise, moving focus up from the right side of the shelves below might fail, or might jump all the way to the tab bar because the focus engine searches for the nearest focusable view along a straight line from the currently focused item.
VStack(alignment: .leading) { // Header content. } .frame(maxWidth: .infinity, alignment: .leading) .focusSection() .containerRelativeFrame(.vertical, alignment: .topLeading) { length, _ in length * 0.8 }
The code above is the above-the-fold section. To detect when focus moves below the fold, use onScrollVisibilityChange(threshold:_:) to detect when the header view moves more than halfway off the screen.
.onScrollVisibilityChange { visible in // When the header scrolls more than 50% offscreen, toggle // to the below-the-fold state. withAnimation { belowFold = !visible } }
You can define the background of your landing page using a full-screen image with a material in an overlay. Then you can turn the material into a gradient by masking it with a LinearGradient, and you can adjust the opacity of that gradient’s stops according to the view’s above- or below-the-fold status.
Image("beach_landscape")
.resizable()
.aspectRatio(contentMode: .fill)
.overlay {
// Build the gradient material by filling an area with a material, and
// then masking that area using a linear gradient.
Rectangle()
.fill(.regularMaterial)
.mask {
LinearGradient(
stops: [
.init(color: .black, location: 0.25),
.init(color: .black.opacity(belowFold ? 1 : 0.3), location: 0.375),
.init(color: .black.opacity(belowFold ? 1 : 0), location: 0.5)
],
startPoint: .bottom, endPoint: .top
)
}
}
.ignoresSafeArea()
By adjusting the opacity of the gradient stops, rather than swapping out the mask view, you achieve a smooth animation between the above-the-fold appearance, where the material fades out above a certain height to reveal the image behind, and the below-the-fold appearance where the entire image blurs.
Snap at the fold point
You can implement a custom ScrollTargetBehavior to create a fold-snapping effect. Then add a check to determine whether the target of a scroll event is crossing a fold threshold, and update that target to either the top of the page (if moving upward) or to the top of your first content shelf (if moving downward). With your view already tracking the above/below fold state, it can pass that information into the behavior to indicate which operation to check for.
ScrollView { // . . . } .scrollTargetBehavior( FoldSnappingScrollTargetBehavior( aboveFold: !belowFold, showcaseHeight: showcaseHeight))
struct FoldSnappingScrollTargetBehavior: ScrollTargetBehavior { var aboveFold: Bool var showcaseHeight: CGFloat
func updateTarget(_ target: inout ScrollTarget, context: TargetContext) { // The view is above the fold and not moving far enough down, so make no // change. if aboveFold && target.rect.minY < showcaseHeight * 0.3 { return }
// The view is below the fold, and the header isn't coming onscreen, so // make no change.
return }
// Upward movement: Require revealing over 30% of the header, or don't let // the scroll go upward. let showcaseRevealThreshold = showcaseHeight * 0.7 let snapToHideRange = showcaseRevealThreshold...showcaseHeight
if aboveFold || snapToHideRange.contains(target.rect.origin.y) { // Snap to align the first content shelf at the top of the screen. target.rect.origin.y = showcaseHeight } else { // Snap upward to reveal the header. target.rect.origin.y = 0 } } }
Provide product highlight pages
It’s common for product pages to use a material gradient appearance with above- and below-the-fold snapping. You most likely need to tune the gradient a little differently to account for a taller bar of content at the bottom of the screen, but you typically want to keep the content’s showcase image, with a suitable blur, as a background for the view when scrolling below.
This makes each product’s page unique, with its defining artwork tinting the content. This is the same effect that root screen on the Apple TV uses — the system blurs the most recently displayed top-shelf image and uses it as the background of the tvOS home screen.
In your description view, you may want to display a stack of bordered buttons, and stretch each to the same width. SwiftUI implements bordered buttons by attaching a background to their labels, so increasing the size of the button view isn’t necessarily going to cause the background platter to grow. Instead, you need to specify that the label content is able to expand, and its background then expands as well. Attaching a frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:) modifier to the button’s label content achieves this for you.
VStack(spacing: 12) { Button { /* action */ } label: { Text("Sign Up") .font(.body.bold()) .frame(maxWidth: .infinity) }
Button { /* action */ } label: { Text("Buy or Rent") .font(.body.bold()) .frame(maxWidth: .infinity) }
Button { /* action */ } label: { Label("Add to Up Next", systemImage: "plus") .font(.body.bold()) .frame(maxWidth: .infinity) } }
When displaying your content’s description, allow it to truncate on the page, and place it within a Button using the .plain style. People can then select it, and you can present the full description using an overlay view that you attach with the fullScreenCover(isPresented:onDismiss:content:) modifier.
.fullScreenCover(isPresented: $showDescription) { VStack(alignment: .center) { Text(loremIpsum) .frame(maxWidth: 600) } }
Search for content
For your search page, prefer using a LazyVGrid to contain your results, and a landscape orientation for the lockups themselves. This allows more content to appear onscreen at one time, with several rows of three to five items per row. A tall content container area makes it much easier to see the effects of changes to your search term.
The search implementation consists of simple view modifiers that function identically on each Apple platform. The searchable(text:placement:prompt:) modifier provides the entire search UI for you, binding the search field to the provided text. By attaching a searchSuggestions(_:) modifier, you can present a list of potential search keyword completions. These are commonly Text instances, but Button and Label also work.
Be sure to sort your search results so that the content of your grid is stable and predictable.
ScrollView(.vertical) { LazyVGrid( columns: Array(repeating: .init(.flexible(), spacing: 40), count: 4), spacing: 40 ) { ForEach(/* matching assets, sorted /) { asset in Button { / action / } label: { asset.landscapeImage .resizable() .aspectRatio(16 / 9, contentMode: .fit) Text(asset.title) } } } .buttonStyle(.borderless) } .scrollClipDisabled() .searchable(text: $searchTerm) .searchSuggestions { ForEach(/ keywords matching search term */, id: .self) { suggestion in Text(suggestion) } }
https://developer.apple.com/documentation/swiftui/worldrecenterphase
- SwiftUI
- WorldRecenterPhase Beta
Enumeration
WorldRecenterPhase
A type that represents information associated with a phase of a system recenter event. Values of this type are passed to the closure specified in View.onWorldRecenter(action:).
enum WorldRecenterPhase
Topics
Enumeration Cases
case began
The app has begun to fade out. It is not re-positioned yet.
case ended
The app has begun to fade in after it has been re-positioned.
Relationships
Conforms To
CopyableEquatableHashableSendableSendableMetatype
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/uiapplicationdelegateadaptor).
https://developer.apple.com/documentation/swiftui/backyard-birds-sample)
https://developer.apple.com/documentation/swiftui/food_truck_building_a_swiftui_multiplatform_app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/migrating-to-the-swiftui-life-cycle)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/uiapplicationdelegateadaptor)
https://developer.apple.com/documentation/swiftui/nsapplicationdelegateadaptor)
https://developer.apple.com/documentation/swiftui/wkapplicationdelegateadaptor)
https://developer.apple.com/documentation/swiftui/wkextensiondelegateadaptor)
https://developer.apple.com/documentation/swiftui/creating-a-tvos-media-catalog-app-in-swiftui)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/worldrecenterphase)
https://developer.apple.com/documentation/swiftui/scene/immersionstyle(selection:in:)
#app-main)
- SwiftUI
- Scene
- immersionStyle(selection:in:)
Instance Method
immersionStyle(selection:in:)
Sets the style for an immersive space.
nonisolated func immersionStyle(
in styles: any ImmersionStyle...
Parameters
selection
A Binding to the style that the space uses. You can change this value to change the scene’s style even after you present the immersive space. Even though you provide a binding, the value changes only if you change it.
styles
The list of styles that the selection input can have. Include any styles that you plan to use during the lifetime of the scene.
Return Value
A scene that uses one of the specified styles.
Discussion
Use this modifier to configure the appearance and behavior of an ImmersiveSpace. Specify a style that conforms to the ImmersionStyle protocol, like mixed or full. For example, the following app defines a solar system scene that uses full immersion:
@main struct SolarSystemApp: App { @State private var style: ImmersionStyle = .full
var body: some Scene { ImmersiveSpace { SolarSystem() } .immersionStyle(selection: $style, in: .full) } }
See Also
Creating an immersive space
struct ImmersiveSpace
A scene that presents its content in an unbounded space.
struct ImmersiveSpaceContentBuilder
A result builder for composing a collection of immersive space elements.
protocol ImmersionStyle
The styles that an immersive space can have.
var immersiveSpaceDisplacement: Pose3D
The displacement that the system applies to the immersive space when moving the space away from its default position, in meters.
struct ImmersiveEnvironmentBehavior
The behavior of the system-provided immersive environments when a scene is opened by your app.
Beta
struct ProgressiveImmersionAspectRatio Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/immersionstyle/mixed
- SwiftUI
- ImmersionStyle
- mixed
Type Property
mixed
An immersion style that displays unbounded content intermixed with other app content, along with passthrough video.
static var mixed: MixedImmersionStyle { get }
Available when Self is MixedImmersionStyle.
Discussion
When this immersion style is selected, the immersion amount reported by the closure of onImmersionChange(initial:_:) is 0.0.
Use the immersionStyle(selection:in:) scene modifier to specify this style for an ImmersiveSpace. However, this is the default immersion style if you don’t specify one.
The immersion style affects how windows interact with virtual objects in the environment. In mixed immersion, a virtual object obscures part or all of a window that’s behind the object. Similarly, a window obscures a virtual object that’s behind the window.
See Also
Getting built-in styles
static var automatic: AutomaticImmersionStyle
The default immersion style.
static var full: FullImmersionStyle
An immersion style that displays unbounded content that completely replaces passthrough video.
static var progressive: ProgressiveImmersionStyle
An immersion style that displays unbounded content that partially replaces passthrough video.
https://developer.apple.com/documentation/swiftui/immersionstyle/full
https://developer.apple.com/documentation/swiftui/immersionstyle/progressive
- SwiftUI
- ImmersionStyle
- progressive
Type Property
progressive
An immersion style that displays unbounded content that partially replaces passthrough video.
static var progressive: ProgressiveImmersionStyle { get }
Available when Self is ProgressiveImmersionStyle.
Discussion
The system initially uses a radial portal effect that replaces passthrough in a portion of the field of view. People can interactively adjust the size of the portal by turning the Digital Crown, including down to a minimum amount of immersion defined by the system and up to the point where the portal fully covers passthrough. If someone tries to reduce the portal size below the minimum value, the portal smoothly bounces immersion style, including the configurable visibility of the viewer’s upper limbs.
When this immersion style is selected, the immersion amount reported by the closure of onImmersionChange(initial:_:) is within the range of the immersion that this style uses.
Use the immersionStyle(selection:in:) scene modifier to specify this style for an ImmersiveSpace:
@main struct ImmersiveApp: App { @State private var immersionStyle: ImmersionStyle = .progressive var body: some Scene { ImmersiveSpace { ... } .immersionStyle(selection: $immersionStyle, in: .progressive)) } }
The immersion style affects how windows interact with virtual objects in the environment. In progressive immersion, windows always render in front of virtual content, no matter how someone positions the window or the content. This helps people avoid losing track of windows behind virtual content when passthrough is off.
See Also
Getting built-in styles
static var automatic: AutomaticImmersionStyle
The default immersion style.
static var full: FullImmersionStyle
An immersion style that displays unbounded content that completely replaces passthrough video.
static var mixed: MixedImmersionStyle
An immersion style that displays unbounded content intermixed with other app content, along with passthrough video.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/immersivespace
- SwiftUI
- ImmersiveSpace
Structure
ImmersiveSpace
A scene that presents its content in an unbounded space.
Overview
Use an immersive space as a container for a view hierarchy that your app presents. The hierarchy that you declare as the immersive space’s content serves as a template for it:
@main struct SolarSystemApp: App { var body: some Scene { ImmersiveSpace { SolarSystem() } } }
If you want to create a bounded scene instead, use one of the types that creates a window or a volume, like WindowGroup or DocumentGroup.
Style the immersive space
By default, immersive spaces use the mixed style which places virtual content in a person’s surroundings. You can select a different style for the immersive space by adding the immersionStyle(selection:in:) scene modifier to the scene. For example, you can completely control the visual experience using the full immersion style:
@main struct SolarSystemApp: App { @State private var style: ImmersionStyle = .full
var body: some Scene { ImmersiveSpace { SolarSystem() } .immersionStyle(selection: $style, in: .full) } }
You can change the immersion style after presenting the immersive space by changing the modifier’s selection input, although you can only use one of the values that you specify in the modifier’s second parameter. For any style of immersion, the other parts of your app’s interface — namely its windows — remain visible. However, the immersion style affects how windows interact with virtual objects in the environment:
-
For the
mixedstyle, a virtual object obscures part or all of a window that’s behind the object. Similarly, a window obscures a virtual object that’s behind the window. -
For other styles, windows always render in front of virtual content, no matter how someone positions the window or the content. This helps people to avoid losing track of windows behind virtual content when passthrough is partially or completely off.
Open an immersive space
You can programmatically open an immersive space by giving it an identifier. For example, you can label the solar system view from the previous example:
ImmersiveSpace(id: "solarSystem") { SolarSystem() }
Elsewhere in your code, you use the openImmersiveSpace environment value to get the instance of the OpenImmersiveSpaceAction structure for a given Environment. You call the instance directly — for example, from a button’s closure, like in the following code — using the identifier:
struct NewSolarSystemImmersiveSpace: View { var solarSystem: SolarSystem @Environment(.openImmersiveSpace) private var openImmersiveSpace
var body: some View { Button("Present Solar System") { Task { await openImmersiveSpace(id: "solarSystem") } } } }
Mark the call to the action with await because it executes asynchronously. When your app opens an immersive space, the system hides all other visible apps. The system allows only one immersive space to be open at a time. Be sure to close the open immersive space before opening another one.
Dismiss an immersive space
You can dismiss an immersive space by calling the dismissImmersiveSpace action from the environment. For example, you can define a button that dismisses an immersive space:
struct DismissImmersiveSpaceButton: View { @Environment(.dismissImmersiveSpace) private var dismissImmersiveSpace
var body: some View { Button("Close Solar System") { Task { await dismissImmersiveSpace() } } } }
The dismiss action runs asynchronously, like the open action. You don’t need to specify an identifier when dismissing an immersive space because there can only be one immersive space open at a time.
Present an immersive space at launch
When an app launches, it opens an instance of the first scene that’s listed in the app’s body. However, to open an immersive space at launch, you need to provide additional configuration information in your app’s Info.plist file. In particular, set the UIApplicationPreferredDefaultSceneSessionRole key in the scene manifest to the value UISceneSessionRoleImmersiveSpaceApplication.
To configure the style of the immersive space that opens at launch, add a scene configuration to the scene session role. Use the UISceneInitialImmersionStyle key together with a value that indicates one of the mixed, full, or progressive styles. See the initial immersion style key for more information.
Topics
Creating an immersive space
init(content:)
Creates an immersive space.
Identifying an immersive space
init(id:content:)
Creates the immersive space associated with the specified identifier.
Deprecated
Creating a data-driven immersive space
init(for:content:)
Creates the immersive space for a specified type of presented data.
init(id:for:content:)
Creates the immersive space associated with an identifier for a specified type of presented data.
Providing default data to an immersive space
init(for:content:defaultValue:)
init(id:for:content:defaultValue:)
Creates the immersive space associated with an identifier for a specified type of presented data, and a default value, if the data is not set.
Supporting types
struct ImmersiveSpaceViewContent
Immersive space content that uses a SwiftUI view hierarchy as the content.
protocol ImmersiveSpaceContent
A type that you can use as the content of an immersive space.
Initializers
init(id:makeContent:)
Relationships
Conforms To
Scene
See Also
Creating an immersive space
struct ImmersiveSpaceContentBuilder
A result builder for composing a collection of immersive space elements.
Sets the style for an immersive space.
protocol ImmersionStyle
The styles that an immersive space can have.
var immersiveSpaceDisplacement: Pose3D
The displacement that the system applies to the immersive space when moving the space away from its default position, in meters.
struct ImmersiveEnvironmentBehavior
The behavior of the system-provided immersive environments when a scene is opened by your app.
Beta
struct ProgressiveImmersionAspectRatio Beta
https://developer.apple.com/documentation/swiftui/immersivespacecontentbuilder
- SwiftUI
- ImmersiveSpaceContentBuilder
Structure
ImmersiveSpaceContentBuilder
A result builder for composing a collection of immersive space elements.
@resultBuilder struct ImmersiveSpaceContentBuilder
Topics
See Also
Creating an immersive space
struct ImmersiveSpace
A scene that presents its content in an unbounded space.
Sets the style for an immersive space.
protocol ImmersionStyle
The styles that an immersive space can have.
var immersiveSpaceDisplacement: Pose3D
The displacement that the system applies to the immersive space when moving the space away from its default position, in meters.
struct ImmersiveEnvironmentBehavior
The behavior of the system-provided immersive environments when a scene is opened by your app.
Beta
struct ProgressiveImmersionAspectRatio Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/immersionstyle
- SwiftUI
- ImmersionStyle
Protocol
ImmersionStyle
The styles that an immersive space can have.
protocol ImmersionStyle
Overview
Configure the appearance and behavior of an ImmersiveSpace by adding the immersionStyle(selection:in:) scene modifier to the space and specifying a style that conforms to this protocol, like mixed or full. For example, the following app defines a solar system scene that uses full immersion:
@main struct SolarSystemApp: App { @State private var style: ImmersionStyle = .full
var body: some Scene { ImmersiveSpace { SolarSystem() } .immersionStyle(selection: $style, in: .full) } }
Topics
Getting built-in styles
static var automatic: AutomaticImmersionStyle
The default immersion style.
static var full: FullImmersionStyle
An immersion style that displays unbounded content that completely replaces passthrough video.
static var mixed: MixedImmersionStyle
An immersion style that displays unbounded content intermixed with other app content, along with passthrough video.
static var progressive: ProgressiveImmersionStyle
An immersion style that displays unbounded content that partially replaces passthrough video.
Supporting types
struct AutomaticImmersionStyle
The default style of immersive spaces.
struct FullImmersionStyle
struct MixedImmersionStyle
struct ProgressiveImmersionStyle
Type Methods
static progressive(_:initialAmount:)
static progressive(_:initialAmount:aspectRatio:)
Beta
Relationships
Conforming Types
AutomaticImmersionStyleFullImmersionStyleMixedImmersionStyleProgressiveImmersionStyle
See Also
Creating an immersive space
struct ImmersiveSpace
A scene that presents its content in an unbounded space.
struct ImmersiveSpaceContentBuilder
A result builder for composing a collection of immersive space elements.
Sets the style for an immersive space.
var immersiveSpaceDisplacement: Pose3D
The displacement that the system applies to the immersive space when moving the space away from its default position, in meters.
struct ImmersiveEnvironmentBehavior
The behavior of the system-provided immersive environments when a scene is opened by your app.
struct ProgressiveImmersionAspectRatio Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/environmentvalues/immersivespacedisplacement
- SwiftUI
- EnvironmentValues
- immersiveSpaceDisplacement
Instance Property
immersiveSpaceDisplacement
The displacement that the system applies to the immersive space when moving the space away from its default position, in meters.
var immersiveSpaceDisplacement: Pose3D { get }
Discussion
By default, the system places the origin of the immersive space at floor level, at the person’s feet. When joining a shared activity, the system moves the immersive space to an appropriate location for all participants. As participants join and leave the activity, the location of participants and the immersive space can update. Read this property to get the current offset of the immersive space relative to its default position.
If you access this property outside of an open immersive space, it contains the value identity.
If you display participant-specific views or entities in your shared activity, use the inverse of this displacement value to position those views and entities in the immersive space. Applying the inverse value positions them as if they were in a single-participant immersive space.
In the following example, this value is applied to position a game HUD entity at the person’s location, rather than the shared activity’s location:
@main struct GameApp: App { var body: some Scene { ImmersiveSpace { ImmersiveGameView() } } }
struct ImmersiveGameView: View { @Environment(.immersiveSpaceDisplacement) private var immersiveSpaceDisplacement
let gameHUDEntity = makeGameHUDEntity()
var body: some View { RealityView { content in // ... } update: { content in let inverseDisplacement = float4x4(immersiveSpaceDisplacement.inverse) gameHUDEntity.setTransformMatrix(inverseDisplacement, relativeTo: nil) } } }
See Also
Creating an immersive space
struct ImmersiveSpace
A scene that presents its content in an unbounded space.
struct ImmersiveSpaceContentBuilder
A result builder for composing a collection of immersive space elements.
Sets the style for an immersive space.
protocol ImmersionStyle
The styles that an immersive space can have.
struct ImmersiveEnvironmentBehavior
The behavior of the system-provided immersive environments when a scene is opened by your app.
Beta
struct ProgressiveImmersionAspectRatio Beta
https://developer.apple.com/documentation/swiftui/immersiveenvironmentbehavior
- SwiftUI
- ImmersiveEnvironmentBehavior Beta
Structure
ImmersiveEnvironmentBehavior
The behavior of the system-provided immersive environments when a scene is opened by your app.
struct ImmersiveEnvironmentBehavior
Overview
Use one of these values with the immersiveEnvironmentBehavior(_:) scene modifier to indicate how the immersive environment should behave when your app opens a scene.
Topics
Type Properties
static var automatic: ImmersiveEnvironmentBehavior
A behavior that matches the system default behavior.
static var coexist: ImmersiveEnvironmentBehavior
A behavior that keeps the system’s immersive environment as is when opening a scene.
static var replace: ImmersiveEnvironmentBehavior
A behavior that replaces any currently opened immersive environment with the new scene.
Relationships
Conforms To
EquatableSendableSendableMetatype
See Also
Creating an immersive space
struct ImmersiveSpace
A scene that presents its content in an unbounded space.
struct ImmersiveSpaceContentBuilder
A result builder for composing a collection of immersive space elements.
Sets the style for an immersive space.
protocol ImmersionStyle
The styles that an immersive space can have.
var immersiveSpaceDisplacement: Pose3D
The displacement that the system applies to the immersive space when moving the space away from its default position, in meters.
struct ProgressiveImmersionAspectRatio Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/progressiveimmersionaspectratio
- SwiftUI
- ProgressiveImmersionAspectRatio Beta
Structure
ProgressiveImmersionAspectRatio
struct ProgressiveImmersionAspectRatio
Topics
Type Properties
static var automatic: ProgressiveImmersionAspectRatio
The system will choose a default portal aspect ratio.
static var landscape: ProgressiveImmersionAspectRatio
The portal will be wide.
static var portrait: ProgressiveImmersionAspectRatio
The portal will be tall.
Relationships
Conforms To
EquatableSendableSendableMetatype
See Also
Creating an immersive space
struct ImmersiveSpace
A scene that presents its content in an unbounded space.
struct ImmersiveSpaceContentBuilder
A result builder for composing a collection of immersive space elements.
Sets the style for an immersive space.
protocol ImmersionStyle
The styles that an immersive space can have.
var immersiveSpaceDisplacement: Pose3D
The displacement that the system applies to the immersive space when moving the space away from its default position, in meters.
struct ImmersiveEnvironmentBehavior
The behavior of the system-provided immersive environments when a scene is opened by your app.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/environmentvalues/openimmersivespace
- SwiftUI
- EnvironmentValues
- openImmersiveSpace
Instance Property
openImmersiveSpace
An action that presents an immersive space.
var openImmersiveSpace: OpenImmersiveSpaceAction { get }
Discussion
Use this environment value to get the instance of the OpenImmersiveSpaceAction structure for a given Environment. Then call the instance to present a space. You call the instance directly because it defines callAsFunction() methods that Swift calls when you call the instance.
On macOS, this may be used to open a remote immersive space declared with RemoteImmersiveSpace. When your app opens a remote immersive space, the system may ask the user for a preferred device with which to display the content.
For example, you can define a button that opens a specified planet in an immersive space:
@main struct SolarSystemApp: App { var body: some Scene { ImmersiveSpace(for: Planet.ID.self) { $planetID in // ... } } }
struct ShowPlanetButton: View { var planet: Planet @Environment(.openImmersiveSpace) private var openImmersiveSpace
var body: some View { Button("Show (planet.name)") { Task { await openImmersiveSpace(value: planet.ID) } } } }
You indicate which immersive space to open by providing one of the following:
-
A string identifier that you pass through the
idparameter. -
A
valueparameter that has a type that matches the type that you specify in the space’s initializer, as in the above example. -
Both an identifier and a value. This enables you to define multiple spaces that take input values of the same type and distinguish them by their string identifiers.
The call is asynchronous and returns after presenting the space or if an error occurs. You can check for errors by inspecting the call’s return value, which is of type OpenImmersiveSpaceAction.Result. For example, the call returns an error if you already have an immersive space open, because the system enables only one space to be open at a time.
If you provide a value when you open the space, the scene’s trailing closure receives a binding to the value that you provide. For best performance, use lightweight data for the presentation value. For structured model values that conform to Identifiable, the value’s identifier makes a good presentation value, like the planet.ID value in the above code.
See Also
Opening an immersive space
struct OpenImmersiveSpaceAction
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/openimmersivespaceaction
- SwiftUI
- OpenImmersiveSpaceAction
Structure
OpenImmersiveSpaceAction
An action that presents an immersive space.
@MainActor struct OpenImmersiveSpaceAction
Overview
Use the openImmersiveSpace environment value to get the instance of this structure for a given Environment. Then call the instance to present a space. You call the instance directly because it defines callAsFunction() methods that Swift calls when you call the instance.
On macOS, this may be used to open a remote immersive space declared with RemoteImmersiveSpace. When your app opens a remote immersive space, the system may ask the user for a preferred device with which to display the content.
For example, you can define a button that opens a specified planet in an immersive space:
@main struct SolarSystemApp: App { var body: some Scene { ImmersiveSpace(for: Planet.ID.self) { $planetID in // ... } } }
struct ShowPlanetButton: View { var planet: Planet @Environment(.openImmersiveSpace) private var openImmersiveSpace
var body: some View { Button("Show (planet.name)") { Task { await openImmersiveSpace(value: planet.ID) } } } }
You indicate which immersive space to open by providing one of the following:
-
A string identifier that you pass through the
idparameter. -
A
valueparameter that has a type that matches the type that you specify in the space’s initializer, as in the above example. -
Both an identifier and a value. This enables you to define multiple spaces that take input values of the same type and distinguish them by their string identifiers.
The call is asynchronous and returns after presenting the space or if an error occurs. You can check for errors by inspecting the call’s return value, which is of type OpenImmersiveSpaceAction.Result. For example, the call returns an error if you already have an immersive space open, because the system enables only one space to be open at a time.
If you provide a value when you open the space, the scene’s trailing closure receives a binding to the value that you provide. For best performance, use lightweight data for the presentation value. For structured model values that conform to Identifiable, the value’s identifier makes a good presentation value, like the planet.ID value in the above code.
Topics
Calling the action
Presents an immersive space for the scene with the specified identifier.
Presents the immersive space that your app defines for the specified identifier and that handles the type of the presented value.
Presents the immersive space that handles the type of the presented value.
Getting the result
enum Result
The outcome of an attempt to open an immersive space.
Relationships
Conforms To
SendableSendableMetatype
See Also
Opening an immersive space
var openImmersiveSpace: OpenImmersiveSpaceAction
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/environmentvalues/dismissimmersivespace
- SwiftUI
- EnvironmentValues
- dismissImmersiveSpace
Instance Property
dismissImmersiveSpace
An immersive space dismissal action stored in a view’s environment.
var dismissImmersiveSpace: DismissImmersiveSpaceAction { get }
Discussion
Use this environment value to get a DismissImmersiveSpaceAction instance for a given Environment. Then call the instance to dismiss a space. You call the instance directly because it defines a callAsFunction() method that Swift calls when you call the instance.
On macOS, this may be used to dismiss a remote immersive space declared with RemoteImmersiveSpace.
For example, you can define a button that dismisses an immersive space:
@main struct MyApp: App { var body: some Scene { WindowGroup { DismissImmersiveSpaceButton() } ImmersiveSpace(id: "solarSystem") { SolarSystemView() } } }
struct DismissImmersiveSpaceButton: View { @Environment(.dismissImmersiveSpace) private var dismissImmersiveSpace
var body: some View { Button("Dismiss") { Task { await dismissImmersiveSpace() } } } }
The asynchronous call returns after the system finishes dismissing the space. Unlike the call to openImmersiveSpace that you use to open the space — which requires an identifier, a value, or both to specify which space to open — the dismiss action requires no parameters because there can be only one immersive space open at a time. The call closes the space that is currently open, if any.
See Also
Closing the immersive space
struct DismissImmersiveSpaceAction
An action that dismisses an immersive space.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/dismissimmersivespaceaction
- SwiftUI
- DismissImmersiveSpaceAction
Structure
DismissImmersiveSpaceAction
An action that dismisses an immersive space.
@MainActor struct DismissImmersiveSpaceAction
Overview
Use the dismissImmersiveSpace environment value to get an instance of this type for a given Environment. Then call the instance to dismiss a space. You call the instance directly because it defines a callAsFunction() method that Swift calls when you call the instance.
On macOS, this may be used to dismiss a remote immersive space declared with RemoteImmersiveSpace.
For example, you can define a button that dismisses an immersive space:
@main struct MyApp: App { var body: some Scene { WindowGroup { DismissImmersiveSpaceButton() } ImmersiveSpace(id: "solarSystem") { SolarSystemView() } } }
struct DismissImmersiveSpaceButton: View { @Environment(.dismissImmersiveSpace) private var dismissImmersiveSpace
var body: some View { Button("Dismiss") { Task { await dismissImmersiveSpace() } } } }
The asynchronous call returns after the system finishes dismissing the space. Unlike the call to openImmersiveSpace that you use to open the space — which requires an identifier, a value, or both to specify which space to open — the dismiss action requires no parameters because there can be only one immersive space open at a time. The call closes the space that is currently open, if any.
Topics
Calling the action
func callAsFunction() async
Dismisses the currently opened immersive space.
Relationships
Conforms To
SendableSendableMetatype
See Also
Closing the immersive space
var dismissImmersiveSpace: DismissImmersiveSpaceAction
An immersive space dismissal action stored in a view’s environment.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/scene/upperlimbvisibility(_:)
#app-main)
- SwiftUI
- Scene
- upperLimbVisibility(_:)
Instance Method
upperLimbVisibility(_:)
Sets the preferred visibility of the user’s upper limbs, while an ImmersiveSpace scene is presented.
nonisolated
Parameters
preferredVisibility
A value indicating if the upper limbs should be visible. Use .automatic for a system-defined standard behavior, .visible to keep the upper limbs visible, and .hidden to hide the upper limbs.
Discussion
The system can show the user’s upper limbs during fully immersive experiences, but you can also hide them, for example, in order to display virtual hands instead.
Note that this modifier only sets a preference and ultimately the system will decide if it will honor it or not. The system may by unable to honor the preference if the immersive space is currently not visible.
See Also
Hiding upper limbs during immersion
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/upperlimbvisibility(_:)
#app-main)
- SwiftUI
- View
- upperLimbVisibility(_:)
Instance Method
upperLimbVisibility(_:)
Sets the preferred visibility of the user’s upper limbs, while an ImmersiveSpace scene is presented.
nonisolated
Parameters
preferredVisibility
A value indicating if the upper limbs should be visible. Use .automatic for a system-defined standard behavior, .visible to keep the upper limbs visible, and .hidden to hide the upper limbs.
Discussion
The system can show the user’s upper limbs during fully immersive experiences, but you can also hide them, for example, in order to display virtual hands instead.
Note that this modifier only sets a preference and ultimately the system will decide if it will honor it or not. The system may by unable to honor the preference if the immersive space is currently not visible.
See Also
Hiding upper limbs during immersion
https://developer.apple.com/documentation/swiftui/scene/immersivecontentbrightness(_:)
#app-main)
- SwiftUI
- Scene
- immersiveContentBrightness(_:)
Instance Method
immersiveContentBrightness(_:)
Sets the content brightness of an immersive space.
nonisolated
Parameters
brightness
The level of content brightness that you prefer.
Return Value
A scene that has the specified content brightness.
Discussion
Pass one of the standard brightness levels defined in ImmersiveContentBrightness or a custom one that you create with the custom(_:) method to this scene modifier to set a preference for the content brightness in an ImmersiveSpace. The system takes the value that you set into account, but might not be able to honor a specific preference.
When you do this to create an environment that’s suitable for video playback, the standard brightness values provide good results for most use cases. To optimize further, you can create a custom brightness using a normalized value that expresses the linear brightness ratio between a standard dynamic range white video frame and the background that surrounds the player window.
See Also
Adjusting content brightness
struct ImmersiveContentBrightness
The content brightness of an immersive space.
https://developer.apple.com/documentation/swiftui/immersivecontentbrightness
- SwiftUI
- ImmersiveContentBrightness
Structure
ImmersiveContentBrightness
The content brightness of an immersive space.
struct ImmersiveContentBrightness
Overview
Use a value of this type as an input to the immersiveContentBrightness(_:) scene modifier to indicate the ambient content brightness of an ImmersiveSpace.
When you do this to create an environment that’s suitable for video playback, use one of the standard brightness values like bright, dim, or dark to provide good results for most use cases. To optimize further, you can create a custom brightness using a normalized value that expresses the linear brightness ratio between a standard dynamic range white video frame and the background that surrounds the player window.
Topics
Type Properties
static let automatic: ImmersiveContentBrightness
The default content brightness.
static let bright: ImmersiveContentBrightness
A bright content brightness.
static let dark: ImmersiveContentBrightness
A dark content brightness.
static let dim: ImmersiveContentBrightness
A dimmed content brightness.
Type Methods
Creates a content brightness with a custom value.
Relationships
Conforms To
Equatable
See Also
Adjusting content brightness
Sets the content brightness of an immersive space.
https://developer.apple.com/documentation/swiftui/view/onimmersionchange(initial:_:)
#app-main)
- SwiftUI
- View
- onImmersionChange(initial:_:)
Instance Method
onImmersionChange(initial:_:)
Performs an action when the immersion state of your app changes.
nonisolated func onImmersionChange( initial: Bool = true,
Parameters
initial
Whether the action should be run when this view initially appears.
action
A closure to run when the immersion changes.
Discussion
Depending on the immersion style used for the Immersive Space in your app, the amount of immersion can be controlled by actions such as turning the Digital Crown. Use this modifier to define a closure that is run when the immersion state changes. The following example sets the value of a binding depending on the current amount of immersion:
struct ImmersiveView: View { @Binding var enableSoundEffects: Bool
var body: some View { MyView() .onImmersionChange { _, newImmersion in guard let amount = newImmersion.amount else { enableSoundEffects = false return } // Enable some effects based on the updated // amount of immersion
} } }
See Also
Responding to immersion changes
struct ImmersionChangeContext
A structure that represents a state of immersion of your app.
https://developer.apple.com/documentation/swiftui/immersionchangecontext
- SwiftUI
- ImmersionChangeContext
Structure
ImmersionChangeContext
A structure that represents a state of immersion of your app.
struct ImmersionChangeContext
Overview
You don’t use this structure directly. Instead, SwiftUI provides instances of this structure via the onImmersionChange modifier’s closure.
Topics
Instance Properties
let amount: Double?
The current amount of immersion.
Relationships
Conforms To
SendableSendableMetatype
See Also
Responding to immersion changes
Performs an action when the immersion state of your app changes.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/immersiveenvironmentpicker(content:)
#app-main)
- SwiftUI
- View
- immersiveEnvironmentPicker(content:)
Instance Method
immersiveEnvironmentPicker(content:)
Add menu items to open immersive spaces from a media player’s environment picker.
nonisolated
Discussion
These items are added alongside recently used system environments.
SystemPlayerView(player: player) .immersiveEnvironmentPicker { Button("Chalet", systemImage: "fireplace") { Task { await openImmersiveSpace(id: "Chalet") } } }
Use a UIViewControllerRepresentable instance to display a AVPlayerViewController class in your SwiftUI interface.
struct SystemPlayerView: UIViewControllerRepresentable { let player: AVPlayer
return AVPlayerViewController() }
func updateUIViewController(_ avPlayerViewController: AVPlayerViewController, context: Context) { viewController.player = player } }
Items will be donated to media players (like AVPlayerViewController) downstream in the hierarchy.
https://developer.apple.com/documentation/swiftui/remoteimmersivespace
https://developer.apple.com/documentation/swiftui/remotedeviceidentifier
- SwiftUI
- RemoteDeviceIdentifier Beta
Structure
RemoteDeviceIdentifier
An opaque type that identifies a remote device displaying scene content in a RemoteImmersiveSpace.
struct RemoteDeviceIdentifier
Overview
Access this from the remoteDeviceIdentifier environment property in a remote scene to get the identifier for that scene’s device.
When accessed in a context that is being presented on the local device, this value will be nil.
This identifier can also be used to initialize an ARKitSession associated with the remote device.
struct SolarSystem: CompositorContent { @Environment(.remoteDeviceIdentifier) private var deviceID
var body: some CompositorContent { RemoteImmersiveSpace { CompositorLayer { layerRenderer in // Create an ARSession for the device let arSession = ARKitSession(deviceID)
// Set up and run the Metal render loop. let renderThread = Thread { let engine = solar_engine_create( layerRenderer, arSession) solar_engine_render_loop(engine) } renderThread.name = "Render Thread" renderThread.start() } } } }
Topics
Instance Properties
var cDevice: ar_device_t
Returns the ar_device associated with this device.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Handling remote immersive spaces
struct RemoteImmersiveSpace
A scene that presents its content in an unbounded space on a remote device.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/scene/immersionstyle(selection:in:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/immersionstyle/mixed)
https://developer.apple.com/documentation/swiftui/immersionstyle/full)
https://developer.apple.com/documentation/swiftui/immersionstyle/progressive)
https://developer.apple.com/documentation/swiftui/immersivespace)
https://developer.apple.com/documentation/swiftui/immersivespacecontentbuilder)
https://developer.apple.com/documentation/swiftui/immersionstyle)
https://developer.apple.com/documentation/swiftui/environmentvalues/immersivespacedisplacement)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/immersiveenvironmentbehavior)
https://developer.apple.com/documentation/swiftui/progressiveimmersionaspectratio)
https://developer.apple.com/documentation/swiftui/environmentvalues/openimmersivespace)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/openimmersivespaceaction)
https://developer.apple.com/documentation/swiftui/environmentvalues/dismissimmersivespace)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/dismissimmersivespaceaction)
https://developer.apple.com/documentation/swiftui/scene/upperlimbvisibility(_:))
https://developer.apple.com/documentation/swiftui/view/upperlimbvisibility(_:))
https://developer.apple.com/documentation/swiftui/scene/immersivecontentbrightness(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/immersivecontentbrightness)
https://developer.apple.com/documentation/swiftui/view/onimmersionchange(initial:_:))
https://developer.apple.com/documentation/swiftui/immersionchangecontext)
https://developer.apple.com/documentation/swiftui/view/immersiveenvironmentpicker(content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/remoteimmersivespace)
https://developer.apple.com/documentation/swiftui/remotedeviceidentifier)
https://developer.apple.com/documentation/swiftui/remoteimmersivespace).
https://developer.apple.com/documentation/swiftui/scene
- SwiftUI
- Scene
Protocol
Scene
A part of an app’s user interface with a life cycle managed by the system.
@MainActor @preconcurrency protocol Scene
Mentioned in
Building and customizing the menu bar with SwiftUI
Migrating to the SwiftUI life cycle
Overview
You create an App by combining one or more instances that conform to the Scene protocol in the app’s body. You can use the built-in scenes that SwiftUI provides, like WindowGroup, along with custom scenes that you compose from other scenes. To create a custom scene, declare a type that conforms to the Scene protocol. Implement the required body computed property and provide the content for your custom scene:
struct MyScene: Scene { var body: some Scene { WindowGroup { MyRootView() } } }
A scene acts as a container for a view hierarchy that you want to display to the user. The system decides when and how to present the view hierarchy in the user interface in a way that’s platform-appropriate and dependent on the current state of the app. For example, for the window group shown above, the system lets the user create or remove windows that contain MyRootView on platforms like macOS and iPadOS. On other platforms, the same view hierarchy might consume the entire display when active.
Read the scenePhase environment value from within a scene or one of its views to check whether a scene is active or in some other state. You can create a property that contains the scene phase, which is one of the values in the ScenePhase enumeration, using the Environment attribute:
struct MyScene: Scene { @Environment(.scenePhase) private var scenePhase
// ... }
The Scene protocol provides scene modifiers, defined as protocol methods with default implementations, that you use to configure a scene. For example, you can use the onChange(of:perform:) modifier to trigger an action when a value changes. The following code empties a cache when all of the scenes in the window group have moved to the background:
struct MyScene: Scene { @Environment(.scenePhase) private var scenePhase @StateObject private var cache = DataCache()
var body: some Scene { WindowGroup { MyRootView() } .onChange(of: scenePhase) { newScenePhase in if newScenePhase == .background { cache.empty() } } } }
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is included in the type’s base declaration:
struct MyCustomType: Transition {
// @preconcurrency @MainActor isolation by default
}
Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt out of main actor isolation:
extension MyCustomType: Transition {
// nonisolated by default
}
Topics
Creating a scene
var body: Self.Body
The content and behavior of the scene.
Required
associatedtype Body : Scene
The type of scene that represents the body of this scene.
Watching for changes
func onChange(of:initial:_:)
Adds an action to perform when the given value changes.
Specifies the external events for which SwiftUI opens a new instance of the modified scene.
Creating background tasks
Runs the specified action when the system provides a background task.
Managing app storage
The default store used by AppStorage contained within the scene and its view content.
Setting commands
Adds commands to the scene.
Removes all commands defined by the modified scene.
Replaces all commands defined by the modified scene with the commands from the builder.
Defines a keyboard shortcut for opening new scene windows.
Sizing and positioning the scene
Sets a default position for a window.
func defaultSize(_:)
Sets a default size for a window.
Sets a default width and height for a window.
Sets a default size for a volumetric window.
Defines a function used for determining the default placement of windows.
Sets the kind of resizability to use for a window.
Specifies how windows derived form this scene should determine their size when zooming.
Provides a function which determines a placement to use when windows of a scene zoom.
Configures the role for windows derived from self when participating in a managed window context, such as full screen or Stage Manager.
Interacting with volumes
Specifies how a volume should be aligned when moved in the world.
Specify the world scaling behavior for the window.
Configuring scene visibility
Sets the default launch behavior for this scene.
Sets the restoration behavior for this scene.
Sets the preferred visibility of the non-transient system views overlaying the app.
Styling the scene
Sets the style for an immersive space.
Sets the preferred visibility of the user’s upper limbs, while an ImmersiveSpace scene is presented.
Sets the style for windows created by this scene.
Sets the window level of this scene.
Sets the style for the toolbar defined within this scene.
Sets the label style of items in a toolbar and enables user customization.
Sets the label style of items in a toolbar.
Configuring a data model
Sets the model context in this scene’s environment.
Sets the model container and associated model context in this scene’s environment.
func modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)
Sets the model container in this scene for storing the provided model type, creating a new container if necessary, and also sets a model context for that container in this scene’s environment.
Managing the environment
Places an observable object in the scene’s environment.
Sets the environment value of the specified key path to the given value.
Supplies an ObservableObject to a view subhierarchy.
Transforms the environment value of the specified key path with the given function.
Interacting with dialogs
Configures the icon used by alerts.
Sets the severity for alerts.
Enables user suppression of an alert with a custom suppression message.
func dialogSuppressionToggle(_:isSuppressed:)
Supporting drag behavior
Configures the behavior of dragging a window by its background.
Deprecated symbols
Deprecated
Instance Methods
Adds to a DocumentGroupLaunchScene actions that accept a list of selected files as their parameter.
Sets the content brightness of an immersive space.
Sets the immersive environment behavior that should apply when this scene opens.
Beta
Sets the style for menu bar extra created by this scene.
Relationships
Conforming Types
-
AlertScene -
AssistiveAccess -
DocumentGroup -
DocumentGroupLaunchScene -
GroupConforms whenContentconforms toScene. -
ImmersiveSpace -
MenuBarExtra -
ModifiedContentConforms whenContentconforms toSceneandModifierconforms to_SceneModifier. -
RemoteImmersiveSpace -
Settings -
UtilityWindow -
WKNotificationScene -
Window -
WindowGroup
See Also
Creating scenes
struct SceneBuilder
A result builder for composing a collection of scenes into a single composite scene.
https://developer.apple.com/documentation/swiftui/scene/commands(content:)
#app-main)
- SwiftUI
- Scene
- commands(content:)
Instance Method
commands(content:)
Adds commands to the scene.
nonisolated
Mentioned in
Building and customizing the menu bar with SwiftUI
Discussion
Commands are realized in different ways on different platforms. On macOS, the main menu uses the available command menus and groups to organize its main menu items. Each menu is represented as a top-level menu bar menu, and each command group has a corresponding set of menu items in one of the top-level menus, delimited by separator menu items.
On iPadOS, commands with keyboard shortcuts are exposed in the shortcut discoverability HUD that users see when they hold down the Command (⌘) key.
See Also
Defining commands
Removes all commands defined by the modified scene.
Replaces all commands defined by the modified scene with the commands from the builder.
protocol Commands
Conforming types represent a group of related commands that can be exposed to the user via the main menu on macOS and key commands on iOS.
struct CommandMenu
Command menus are stand-alone, top-level containers for controls that perform related, app-specific commands.
struct CommandGroup
Groups of controls that you can add to existing command menus.
struct CommandsBuilder
Constructs command sets from multi-expression closures. Like ViewBuilder, it supports up to ten expressions in the closure body.
struct CommandGroupPlacement
The standard locations that you can place new command groups relative to.
https://developer.apple.com/documentation/swiftui/scenebuilder
- SwiftUI
- SceneBuilder
Structure
SceneBuilder
A result builder for composing a collection of scenes into a single composite scene.
@resultBuilder struct SceneBuilder
Topics
Building content
static buildBlock(_:)
Passes a single scene written as a child scene through unmodified.
Builds an expression within the builder.
static buildLimitedAvailability(_:)
Processes scene content for a conditional compiler-control statement that performs an availability check.
Produces an optional scene for conditional statements in multi-statement closures that’s only visible when the condition evaluates to true.
See Also
Creating scenes
protocol Scene
A part of an app’s user interface with a life cycle managed by the system.
https://developer.apple.com/documentation/swiftui/environmentvalues/scenephase
- SwiftUI
- EnvironmentValues
- scenePhase
Instance Property
scenePhase
The current phase of the scene.
var scenePhase: ScenePhase { get set }
Discussion
The system sets this value to provide an indication of the operational state of a scene or collection of scenes. The exact meaning depends on where you access the value. For more information, see ScenePhase.
See Also
Monitoring scene life cycle
enum ScenePhase
An indication of a scene’s operational state.
https://developer.apple.com/documentation/swiftui/scenephase
- SwiftUI
- ScenePhase
Enumeration
ScenePhase
An indication of a scene’s operational state.
enum ScenePhase
Mentioned in
Migrating to the SwiftUI life cycle
Overview
The system moves your app’s Scene instances through phases that reflect a scene’s operational state. You can trigger actions when the phase changes. Read the current phase by observing the scenePhase value in the Environment:
@Environment(.scenePhase) private var scenePhase
How you interpret the value depends on where it’s read from. If you read the phase from inside a View instance, you obtain a value that reflects the phase of the scene that contains the view. The following example uses the onChange(of:initial:_:) method to enable a timer whenever the enclosing scene enters the ScenePhase.active phase and disable the timer when entering any other phase:
struct MyView: View { @ObservedObject var model: DataModel @Environment(.scenePhase) private var scenePhase
var body: some View { TimerView() .onChange(of: scenePhase) { model.isTimerRunning = (scenePhase == .active) } } }
If you read the phase from within an App instance, you obtain an aggregate value that reflects the phases of all the scenes in your app. The app reports a value of ScenePhase.active if any scene is active, or a value of ScenePhase.inactive when no scenes are active. This includes multiple scene instances created from a single scene declaration; for example, from a WindowGroup. When an app enters the ScenePhase.background phase, expect the app to terminate soon after. You can use that opportunity to free any resources:
@main struct MyApp: App { @Environment(.scenePhase) private var scenePhase
var body: some Scene { WindowGroup { MyRootView() } .onChange(of: scenePhase) { if scenePhase == .background { // Perform cleanup when all scenes within // MyApp go to the background. } } } }
Topics
Getting scene phases
case active
The scene is in the foreground and interactive.
case inactive
The scene is in the foreground but should pause its work.
case background
The scene isn’t currently visible in the UI.
Relationships
Conforms To
ComparableCopyableEquatableHashableSendableSendableMetatype
See Also
Monitoring scene life cycle
var scenePhase: ScenePhase
The current phase of the scene.
https://developer.apple.com/documentation/swiftui/settings
- SwiftUI
- Settings
Structure
Settings
A scene that presents an interface for viewing and modifying an app’s settings.
Mentioned in
Declaring a custom view
Building and customizing the menu bar with SwiftUI
Overview
Use a settings scene to have SwiftUI manage views with controls for your app’s settings when you declare your app using the App protocol. When you use an App declaration for multiple platforms, compile the settings scene only in macOS:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } #if os(macOS) Settings { SettingsView() } #endif } }
Passing a view as the argument to a settings scene in the App declaration causes SwiftUI to enable the app’s Settings menu item. SwiftUI manages displaying and removing the settings view when the user selects the Settings item from the application menu or the equivalent keyboard shortcut:
The contents of your settings view are controls that modify bindings to UserDefaults values that SwiftUI manages using the AppStorage property wrapper:
struct GeneralSettingsView: View { @AppStorage("showPreview") private var showPreview = true @AppStorage("fontSize") private var fontSize = 12.0
var body: some View { Form { Toggle("Show Previews", isOn: $showPreview) Slider(value: $fontSize, in: 9...96) { Text("Font Size ((fontSize, specifier: "%.0f") pts)") } } } }
You can define your settings in a single view, or you can use a TabView to group settings into different collections:
struct SettingsView: View { var body: some View { TabView { Tab("General", systemImage: "gear") { GeneralSettingsView() } Tab("Advanced", systemImage: "star") { AdvancedSettingsView() } } .scenePadding() .frame(maxWidth: 350, minHeight: 100) } }
Topics
Creating a settings scene
Creates a scene that presents an interface for viewing and modifying an app’s preferences.
Relationships
Conforms To
Scene
See Also
Managing a settings window
struct SettingsLink
A view that opens the Settings scene defined by an app.
struct OpenSettingsAction
An action that presents the settings scene for an app.
var openSettings: OpenSettingsAction
A Settings presentation action stored in a view’s environment.
https://developer.apple.com/documentation/swiftui/settingslink
- SwiftUI
- SettingsLink
Structure
SettingsLink
A view that opens the Settings scene defined by an app.
Overview
On macOS, clicking on the link opens the window for the scene or orders it to the front if it is already open.
Topics
Creating a settings link
init()
Creates a settings link with the default system label.
Creates a settings link with a custom label.
Supporting types
struct DefaultSettingsLinkLabel
The default label to use for a settings link.
Relationships
Conforms To
View
See Also
Managing a settings window
struct Settings
A scene that presents an interface for viewing and modifying an app’s settings.
struct OpenSettingsAction
An action that presents the settings scene for an app.
var openSettings: OpenSettingsAction
A Settings presentation action stored in a view’s environment.
https://developer.apple.com/documentation/swiftui/opensettingsaction
- SwiftUI
- OpenSettingsAction
Structure
OpenSettingsAction
An action that presents the settings scene for an app.
@MainActor @preconcurrency struct OpenSettingsAction
Overview
Use the openSettings environment value to get the instance of this structure for a given Environment. Then call the instance to open a window. You call the instance directly because it defines a callAsFunction() method that Swift calls when you call the instance.
For example, you can define a button that opens the settings window to a particular tab:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } #if os(macOS) Settings { SettingsView() } #endif } }
struct SettingsView: View { @AppStorage("selectedSettingsTab") private var selectedSettingsTab = SettingsTab.general
var body: some View { TabView(selection: $selectedSettingsTab) { GeneralSettings() AdvancedSettings() } } }
struct AdvancedSettingsButton: View { @AppStorage("selectedSettingsTab") private var selectedSettingsTab = SettingsTab.general
@Environment(.openSettings) private var openSettings
var body: some View { Button("Open Advanced Settings…") { selectedSettingsTab = .advanced openSettings() } } }
enum SettingsTab: Int { case general case advanced }
Topics
Instance Methods
func callAsFunction()
Opens the window associated to the Settings scene defined by this app, if one exists.
Relationships
Conforms To
SendableSendableMetatype
See Also
Managing a settings window
struct Settings
A scene that presents an interface for viewing and modifying an app’s settings.
struct SettingsLink
A view that opens the Settings scene defined by an app.
var openSettings: OpenSettingsAction
A Settings presentation action stored in a view’s environment.
https://developer.apple.com/documentation/swiftui/environmentvalues/opensettings
- SwiftUI
- EnvironmentValues
- openSettings
Instance Property
openSettings
A Settings presentation action stored in a view’s environment.
var openSettings: OpenSettingsAction { get }
Discussion
Use the openSettings environment value to get an OpenSettingsAction instance for a given Environment. Then call the instance to open a window. You call the instance directly because it defines a callAsFunction() method that Swift calls when you call the instance.
For example, you can define a button that opens the settings window to a particular tab:
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } #if os(macOS) Settings { SettingsView() } #endif } }
struct SettingsView: View { @AppStorage("selectedSettingsTab") private var selectedSettingsTab = SettingsTab.general
var body: some View { TabView(selection: $selectedSettingsTab) { GeneralSettings() AdvancedSettings() } } }
struct AdvancedSettingsButton: View { @AppStorage("selectedSettingsTab") private var selectedSettingsTab = SettingsTab.general
@Environment(.openSettings) private var openSettings
var body: some View { Button("Open Advanced Settings…") { selectedSettingsTab = .advanced openSettings() } } }
enum SettingsTab: Int { case general case advanced }
See Also
Managing a settings window
struct Settings
A scene that presents an interface for viewing and modifying an app’s settings.
struct SettingsLink
A view that opens the Settings scene defined by an app.
struct OpenSettingsAction
An action that presents the settings scene for an app.
https://developer.apple.com/documentation/swiftui/building-and-customizing-the-menu-bar-with-swiftui
- SwiftUI
- Menus and commands
- Building and customizing the menu bar with SwiftUI
Article
Building and customizing the menu bar with SwiftUI
Provide a seamless, cross-platform user experience by building a native menu bar for iPadOS and macOS.
Overview
On iPadOS and macOS, the menu bar provides access to crucial system-provided actions, such as Cut, Copy, Paste, and window management. The system groups these actions by function into menus and submenus through the menu bar. Apps can add contextual actions, like showing and hiding a sidebar, and can also create custom menus and menu items to allow people to perform app-specific actions from the menu bar. You can also bind menu bar to keyboard shortcuts to make your app quicker and easier to use.
Apps include instances of Scene which display the main views of the app. Each scene provides different default menu sets and actions in the menu bar. Contextually relevant menus and actions, and even custom menus and actions, are specified with the commands(content:) modifier.
The order of system-provided menus and menu items is consistent across all apps, but some menus and menu items are added depending on context. For example, document-based apps include options in the File menu for creating and opening documents. Similarly, not all apps include text-formatting capabilities, but those that include text editing views get a Format menu with options for choosing fonts and styling text by including TextFormattingCommands in the scene’s commands. The system will then add the appropriate menu groups and items that people expect in this context.
Populate the menu bar
When your app launches, the menu bar populates with menus and menu items based on the implemented scenes and commands. Menu items for conditional or context-dependent commands are made active or inactive dynamically, using information from the active scene and its view hierarchy in focus.
Each scene includes a set of default menus and menu items, which you can supplement with your own app-specific needs using the commands(content:) modifier.
A scene’s default menus and menu items are dependent on the functionality the scene type supports. For example, WindowGroup includes commands for quitting and hiding the app, as well as Copy and Paste support and window management.
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
@main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() }
#if os(macOS) Settings { SettingsView() } #endif } }
The DocumentGroup scene includes actions that WindowGroup includes, as well as a number of actions that support document management capabilities, like Save and Duplicate.
Using scenes together creates a menu bar that includes menu items for all of the core functionality of an app that creates and edits documents, manages multiple windows, and exposes user-configurable settings.
@main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: MyAppDocument()) { file in // ... }
#if os(macOS) Settings { // ... } #endif
Add contextual system-provided menu items
Some common menu items are optional, but are helpful if the app contains certain capabilities. For example, not every scene includes a navigation sidebar, but for those that do, people expect to find a menu item that controls the navigation sidebar’s visibility. If your scene includes a navigation sidebar, include this menu item using the commands(content:) modifier and implementing SidebarCommands:
@main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: MyAppDocument()) { file in ContentView(document: file.$document) } .commands { SidebarCommands() } } }
For more information on system-provided command groups, such as text formatting, toolbars, and inspectors, see Commands.
Create custom menus and menu items
Organize and group your app’s custom menu items in custom menus using CommandMenu. The system inserts custom menus into the menu bar after the View menu.
Custom menu items are created with standard SwiftUI views, for example Button and Toggle. Menu creates a submenu. For more information about menu item creation, see Populating SwiftUI menus with adaptive controls.
WindowGroup { ContentView() } .commands { CommandMenu("Actions") { Button("Run", systemImage: "play.fill") { ... } .keyboardShortcut("R")
Button("Stop", systemImage: "stop.fill") { ... } .keyboardShortcut(".") } }
Modify standard menus
Modify system-provided menus using CommandGroup. These groups either extend menus with additional menu items or they replace existing menu items in the indicated command group. When you add menu items in this way, you can specify the location of the menu item based on system-provided menu items.
WindowGroup { ContentView() } .commands { CommandGroup(before: .systemServices) { Button("Check for Updates") { ... } }
CommandGroup(after: .newItem) { Button("New from Clipboard") { ... } }
CommandGroup(replacing: .help) { Button("User Manual") { ... } } }
Update menus and menu items dynamically
Many menu items update their appearance or action depending on whether the scene is active, if the scene has focus, or what is currently selected. For example, the system grays out the Close Window command in the File menu when the app’s last window closes. Similarly, the Cut and Copy menu items are only available in the active window if the person selects copyable data. This behavior also applies to custom menus and menu items your app provides.
Use FocusedValue to create contextual dependencies with your menus and menu items. For example, a menu item’s title can change if the current focus is on a photo or a photo album. A focused value is state data that requires an active scene with its view hierarchy in focus. Use a dynamic property to react to changes in the views of the scene.
In the following, an app with a WindowGroup scene has an Observable() data model for each window that supplies that window’s contents. The active window’s data model is made available as a focused value using the focusedSceneValue(_:) modifier in the window view hierarchy.
@Observable final class DataModel { var messages: [Message] ... }
struct ContentView: View { @State private var model = DataModel()
var body: some View { VStack { ForEach(model.messages) { ... } } .focusedSceneValue(model) } }
Use the FocusedValue property wrapper to represent the active scene’s data model in the menu bar. The data model changes whether the “New Message” button is active or inactive:
struct MessageCommands: Commands { @FocusedValue(DataModel.self) private var dataModel: DataModel?
var body: some Commands { CommandGroup(after: .newItem) { Button("New Message") { dataModel?.messages.append(...) } .disabled(dataModel == nil) } } }
@main struct MessagesApp: App { var body: some Scene { WindowGroup { ContentView() } .commands { MessageCommands() } } }
Similar to the Environment dynamic property, FocusedValue uses a key you provide to find the current value. When the focused value is an Observable object, that key can simply be the object’s type.
To share value-typed values, extend FocusedValues with a custom entry using the Entry() macro, and pass the resulting key path when declaring the FocusedValue property. Custom entry values must always be optional.
struct ContentView: View { @State private var items: [Item] = ... @State private var selection: UUID?
var body: some View { List(items, selection: $selection) { item in ... } // When active, views in the same scene or in the menu bar // can read the selected item ID. .focusedSceneValue(.selectedItemID, selection) } }
struct ItemCommands: Commands { @FocusedValue(.selectedItemID) var selectedItemID: UUID?
var body: some Commands { ... } }
extension FocusedValues { @Entry var selectedItemID: UUID? }
Use focusedValue(_:) when a menu item depends on the current placement of focus within the active scene’s view hierarchy. This creates a focused value that’s’ only visible to other views when focus is on the modified view or one of its subviews. When focus is elsewhere, the value of corresponding FocusedValue property is nil.
var body: some View { NavigationSplitView { SidebarContent() } detail: { List(items, selection: $selection) { item in ... }
// The selected item ID is visible when focus is on the
// navigation detail list. If focus is on the sidebar, the value of
// @FocusedValue(\.selectedItemID) is nil.
.focusedValue(.selectedItemID, selection)
}
}
}
https://developer.apple.com/documentation/swiftui/menubarextra
- SwiftUI
- MenuBarExtra
Structure
MenuBarExtra
A scene that renders itself as a persistent control in the system menu bar.
Overview
Use a MenuBarExtra when you want to provide access to commonly used functionality, even when your app is not active.
@main struct AppWithMenuBarExtra: App { @AppStorage("showMenuBarExtra") private var showMenuBarExtra = true
var body: some Scene { WindowGroup { ContentView() } MenuBarExtra( "App Menu Bar Extra", systemImage: "star", isInserted: $showMenuBarExtra) { StatusMenu() } } }
Or alternatively, to create a utility app that only shows in the menu bar.
@main struct UtilityApp: App { var body: some Scene { MenuBarExtra("Utility App", systemImage: "hammer") { AppMenu() } } }
An app that only shows in the menu bar will be automatically terminated if the user removes the extra from the menu bar.
For apps that only show in the menu bar, a common behavior is for the app to not display its icon in either the Dock or the application switcher. To enable this behavior, set the LSUIElement flag in your app’s Information Property List file to true.
For more complex or data rich menu bar extras, you can use the window style, which displays a popover-like window from the menu bar icon that contains standard controls. You define the layout and contents of those controls with the content that you provide:
MenuBarExtra("Utility App", systemImage: "hammer") { ScrollView { LazyVGrid(...) } } .menuBarExtraStyle(.window)
Topics
Creating a menu bar extra
init(_:content:)
Creates a menu bar extra with a key for a localized string to use as the label. The extra defines the primary scene of an App.
Creates a menu bar extra that will be displayed in the system menu bar, and defines the primary scene of an App.
init(_:isInserted:content:)
Creates a menu bar extra with a key for a localized string to use as the label. The item will be displayed in the system menu bar when the specified binding is set to true. If the user removes the item from the menu bar, the binding will be set to false.
Creates a menu bar extra. The item will be displayed in the system menu bar when the specified binding is set to true. If the user removes the item from the menu bar, the binding will be set to false.
Creating a menu bar extra with an image
init(_:image:content:)
Creates a menu bar extra with an image to use as the items label. The provided title will be used by the accessibility system.
init(_:image:isInserted:content:)
init(_:systemImage:content:)
Creates a menu bar extra with a system image to use as the items label. The provided title will be used by the accessibility system.
init(_:systemImage:isInserted:content:)
Relationships
Conforms To
Scene
See Also
Creating a menu bar extra
Sets the style for menu bar extra created by this scene.
protocol MenuBarExtraStyle
A specification for the appearance and behavior of a menu bar extra scene.
https://developer.apple.com/documentation/swiftui/scene/menubarextrastyle(_:)
#app-main)
- SwiftUI
- Scene
- menuBarExtraStyle(_:)
Instance Method
menuBarExtraStyle(_:)
Sets the style for menu bar extra created by this scene.
nonisolated
See Also
Creating a menu bar extra
struct MenuBarExtra
A scene that renders itself as a persistent control in the system menu bar.
protocol MenuBarExtraStyle
A specification for the appearance and behavior of a menu bar extra scene.
https://developer.apple.com/documentation/swiftui/menubarextrastyle
- SwiftUI
- MenuBarExtraStyle
Protocol
MenuBarExtraStyle
A specification for the appearance and behavior of a menu bar extra scene.
protocol MenuBarExtraStyle
Topics
Getting menu bar extra styles
static var automatic: AutomaticMenuBarExtraStyle
The default menu bar extra style.
static var menu: PullDownMenuBarExtraStyle
A menu bar extra style that renders its contents as a menu that pulls down from the icon in the menu bar.
static var window: WindowMenuBarExtraStyle
A menu bar extra style that renders its contents in a popover-like window.
Supporting types
struct AutomaticMenuBarExtraStyle
The default menu bar extra style. You can also use automatic to construct this style.
struct PullDownMenuBarExtraStyle
struct WindowMenuBarExtraStyle
Relationships
Conforming Types
AutomaticMenuBarExtraStylePullDownMenuBarExtraStyleWindowMenuBarExtraStyle
See Also
Creating a menu bar extra
struct MenuBarExtra
A scene that renders itself as a persistent control in the system menu bar.
Sets the style for menu bar extra created by this scene.
https://developer.apple.com/documentation/swiftui/wknotificationscene
- SwiftUI
- WKNotificationScene
Structure
WKNotificationScene
A scene which appears in response to receiving the specified category of remote or local notifications.
Mentioned in
Declaring a custom view
Topics
Creating a notification scene
init(controller: Controller.Type, category: String)
Creates a scene that appears in response to receiving a specific category of remote or local notifications.
Relationships
Conforms To
Scene
https://developer.apple.com/documentation/swiftui/scene)
https://developer.apple.com/documentation/swiftui/documents).
https://developer.apple.com/documentation/swiftui/scene/commands(content:))
https://developer.apple.com/documentation/swiftui/scenebuilder)
https://developer.apple.com/documentation/swiftui/environmentvalues/scenephase)
https://developer.apple.com/documentation/swiftui/scenephase)
https://developer.apple.com/documentation/swiftui/settings)
https://developer.apple.com/documentation/swiftui/settingslink)
https://developer.apple.com/documentation/swiftui/opensettingsaction)
https://developer.apple.com/documentation/swiftui/environmentvalues/opensettings)
https://developer.apple.com/documentation/swiftui/building-and-customizing-the-menu-bar-with-swiftui)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/menubarextra)
https://developer.apple.com/documentation/swiftui/scene/menubarextrastyle(_:))
https://developer.apple.com/documentation/swiftui/menubarextrastyle)
https://developer.apple.com/documentation/swiftui/wknotificationscene)
https://developer.apple.com/documentation/swiftui/navigationstack
- SwiftUI
- NavigationStack
Structure
NavigationStack
A view that displays a root view and enables you to present additional views over the root view.
@MainActor @preconcurrency
Mentioned in
Migrating to new navigation types
Understanding the navigation stack
Adding a search interface to your app
Overview
Use a navigation stack to present a stack of views over a root view. People can add views to the top of the stack by clicking or tapping a NavigationLink, and remove views using built-in, platform-appropriate controls, like a Back button or a swipe gesture. The stack always displays the most recently added view that hasn’t been removed, and doesn’t allow the root view to be removed.
To create navigation links, associate a view with a data type by adding a navigationDestination(for:destination:) modifier inside the stack’s view hierarchy. Then initialize a NavigationLink that presents an instance of the same kind of data. The following stack displays a ParkDetails view for navigation links that present data of type Park:
NavigationStack { List(parks) { park in NavigationLink(park.name, value: park) } .navigationDestination(for: Park.self) { park in ParkDetails(park: park) } }
In this example, the List acts as the root view and is always present. Selecting a navigation link from the list adds a ParkDetails view to the stack, so that it covers the list. Navigating back removes the detail view and reveals the list again. The system disables backward navigation controls when the stack is empty and the root view, namely the list, is visible.
Manage navigation state
By default, a navigation stack manages state to keep track of the views on the stack. However, your code can share control of the state by initializing the stack with a binding to a collection of data values that you create. The stack adds items to the collection as it adds views to the stack and removes items when it removes views. For example, you can create a State property to manage the navigation for the park detail view:
@State private var presentedParks: [Park] = []
Initializing the state as an empty array indicates a stack with no views. Provide a Binding to this state property using the dollar sign ( $) prefix when you create a stack using the init(path:root:) initializer:
NavigationStack(path: $presentedParks) { List(parks) { park in NavigationLink(park.name, value: park) } .navigationDestination(for: Park.self) { park in ParkDetails(park: park) } }
Like before, when someone taps or clicks the navigation link for a park, the stack displays the ParkDetails view using the associated park data. However, now the stack also puts the park data in the presentedParks array. Your code can observe this array to read the current stack state. It can also modify the array to change the views on the stack. For example, you can create a method that configures the stack with a specific set of parks:
func showParks() { presentedParks = [Park("Yosemite"), Park("Sequoia")] }
The showParks method replaces the stack’s display with a view that shows details for Sequoia, the last item in the new presentedParks array. Navigating back from that view removes Sequoia from the array, which reveals a view that shows details for Yosemite. Use a path to support deep links, state restoration, or other kinds of programmatic navigation.
Navigate to different view types
To create a stack that can present more than one kind of view, you can add multiple navigationDestination(for:destination:) modifiers inside the stack’s view hierarchy, with each modifier presenting a different data type. The stack matches navigation links with navigation destinations based on their respective data types.
To create a path for programmatic navigation that contains more than one kind of data, you can use a NavigationPath instance as the path.
Topics
Creating a navigation stack
Creates a navigation stack that manages its own navigation state.
Creating a navigation stack with a path
init(path:root:)
Creates a navigation stack with homogeneous navigation state that you can control.
Relationships
Conforms To
View
See Also
Stacking views in one column
struct NavigationPath
A type-erased list of data representing the content of a navigation stack.
Associates a destination view with a presented data type for use within a navigation stack.
Associates a destination view with a binding that can be used to push the view onto a NavigationStack.
func navigationDestination<D, C>(item: Binding<Optional<D>>, destination: (D) -> C) -> some View
Associates a destination view with a bound value for use within a navigation stack or navigation split view
https://developer.apple.com/documentation/swiftui/tabview
- SwiftUI
- TabView
Structure
TabView
A view that switches between multiple child views using interactive user interface elements.
Overview
To create a user interface with tabs, place Tab s in a TabView. On iOS, you can also use one of the badge modifiers, like badge(_:), to assign a badge to each of the tabs.
The following example creates a tab view with three tabs, each presenting a custom child view. The first tab has a numeric badge and the third has a string badge.
TabView { Tab("Received", systemImage: "tray.and.arrow.down.fill") { ReceivedView() } .badge(2)
Tab("Sent", systemImage: "tray.and.arrow.up.fill") { SentView() }
Tab("Account", systemImage: "person.crop.circle.fill") { AccountView() } .badge("!") }
To programatically select different tabs, use the init(selection:content:) initializer. You can assign a selection value to each tab using a Tab initializer that takes a value. Each tab should have a unique selection value and all tabs should have the same selection value type. When people select a tab in the tab view, the tab view updates the selection binding to the value of the currently selected tab.
The following example creates a tab view that supports programatic selection and has 3 tabs.
TabView(selection: $selection) { Tab("Received", systemImage: "tray.and.arrow.down.fill", value: 0) { ReceivedView() }
Tab("Sent", systemImage: "tray.and.arrow.up.fill", value: 1) { SentView() }
Tab("Account", systemImage: "person.crop.circle.fill", value: 2) { AccountView() } }
You can use the page style to display a tab view with multiple scrolling pages of content.
The following example uses a ForEach to create a scrolling tab view that shows the temperatures of various cities.
TabView { ForEach(cities) { city in TemperatureView(city) } } .tabViewStyle(.page)
Using tab sections
The sidebarAdaptable style supports declaring a secondary tab hierarchy by grouping tabs with a TabSection.
On iPadOS, tab sections appear in both the sidebar and the tab bar. On iOS and the horizontally compact size class on iPadOS, secondary tabs appear in the tab bar. When secondary tabs appear in the tab bar, the section header doesn’t appear in the tab bar. Consider limiting the number of tabs on iOS and the iPadOS horizontal compact size class so all tabs fit in the tab bar.
The following example has 5 tabs, three of which are grouped within a TabSection.
TabView { Tab("Requests", systemImage: "paperplane") { RequestsView() }
Tab("Account", systemImage: "person.crop.circle.fill") { AccountView() }
TabSection("Messages") { Tab("Received", systemImage: "tray.and.arrow.down.fill") { ReceivedView() }
Tab("Drafts", systemImage: "pencil") { DraftsView() } } } .tabViewStyle(.sidebarAdaptable)
Changing tab structure between horizontal and regular size classes
The following example shows a TabView with 4 tabs in compact and 5 tabs in regular. In compact, one of the tabs is a ‘Browse’ tab that displays a custom list view. This list view allows navigating to the destinations that are contained within the ‘Library’ and ‘Playlists’ sections in the horizontally regular size class. The navigation path and the selection state are updated when the number of tabs changes.
struct BrowseTabExample: View { @Environment(.horizontalSizeClass) var sizeClass
@State var selection: MusicTab = .listenNow @State var browseTabPath: [MusicTab] = [] @State var playlists = [Playlist("All Playlists"), Playlist("Running")]
var body: some View { TabView(selection: $selection) { Tab("Listen Now", systemImage: "play.circle", value: .listenNow) { ListenNowView() }
Tab("Radio", systemImage: "dot.radiowaves.left.and.right", value: .radio) { RadioView() }
Tab("Search", systemImage: "magnifyingglass", value: .search) { SearchDetailView() }
Tab("Browse", systemImage: "list.bullet", value: .browse) { LibraryView(path: $browseTabPath) } .hidden(sizeClass != .compact)
TabSection("Library") { Tab("Recently Added", systemImage: "clock", value: MusicTab.library(.recentlyAdded)) { RecentlyAddedView() }
Tab("Artists", systemImage: "music.mic", value: MusicTab.library(.artists)) { ArtistsView() } } .hidden(sizeClass == .compact)
TabSection("Playlists") { ForEach(playlists) { playlist in Tab(playlist.name, image: playlist.imafe, value: MusicTab.playlists(playlist)) { playlist.detailView() } } } .hidden(sizeClass == .compact) } .tabViewStyle(.sidebarAdaptable) .onChange(of: sizeClass, initial: true) { _, sizeClass in if sizeClass == .compact && selection.showInBrowseTab { browseTabPath = [selection] selection = .browse } else if sizeClass == .regular && selection == .browse { selection = browseTabPath.last ?? .library(.recentlyAdded) } } } } }
struct LibraryView: View { @Binding var path: [MusicTab]
var body: some View { NavigationStack(path: $path) { List { ForEach(MusicLibraryTab.allCases, id: .self) { tab in NavigationLink(tab.rawValue, value: MusicTab.library(tab)) } // Code to add playlists here } .navigationDestination(for: MusicTab.self) { tab in tab.detail() } } } }
Adding support for customization
You can allow people to customize the tabs in a TabView by using sidebarAdaptable style with the tabViewCustomization(_:) modifier. Customization allows people to drag tabs from the sidebar to the tab bar, hide tabs, and rearrange tabs in the sidebar.
All tabs and tab sections that support customization need to have a customization ID. You can mark a tab as being non-customizable by specifying a disabled behavior in all adaptable tab bar placements using customizationBehavior(_:for:).
On macOS, a default interaction is provided for reordering sections but not for controlling the visibility of individual tabs. A custom experience should be provided if desired by setting the visibility of the tab on the customization.
You can use @AppStorage or @SceneStorage to automatically persist any visibility or section order customizations a person makes.
The following example supports customizing all 4 tabs in the tab view and uses @AppStorage to persist the customizations a person makes.
@AppStorage private var customization: TabViewCustomization
TabView { Tab("Home", systemImage: "house") { MyHomeView() } .customizationID("com.myApp.home")
Tab("Reports", systemImage: "chart.bar") { MyReportsView() } .customizationID("com.myApp.reports")
TabSection("Categories") { Tab("Climate", systemImage: "fan") { ClimateView() } .customizationID("com.myApp.climate")
Tab("Lights", systemImage: "lightbulb") { LightsView() } .customizationID("com.myApp.lights") } .customizationID("com.myApp.browse") } .tabViewStyle(.sidebarAdaptable) .tabViewCustomization($customization)
Topics
Creating a tab view
init(content:)
Creates a tab view that uses a builder to create its tabs.
init(selection:content:)
Creates a tab view that uses a builder to create and specify selection values for its tabs.
Relationships
Conforms To
View
See Also
Presenting views in tabs
Enhancing your app’s content with tab navigation
Keep your app content front and center while providing quick access to navigation using the tab bar.
struct Tab
The content for a tab and the tab’s associated tab item in a tab view.
struct TabRole
A value that defines the purpose of the tab.
struct TabSection
A container that you can use to add hierarchy within a tab view.
Sets the style for the tab view within the current environment.
https://developer.apple.com/documentation/swiftui/view/navigationsplitviewstyle(_:)
#app-main)
- SwiftUI
- View
- navigationSplitViewStyle(_:)
Instance Method
navigationSplitViewStyle(_:)
Sets the style for navigation split views within this view.
nonisolated
Parameters
style
The style to set.
Return Value
A view that uses the specified navigation split view style.
Mentioned in
Migrating to new navigation types
See Also
Presenting views in columns
Bringing robust navigation structure to your SwiftUI app
Use navigation links, stacks, destinations, and paths to provide a streamlined experience for all platforms, as well as behaviors such as deep linking and state restoration.
Improve navigation behavior in your app by replacing navigation views with navigation stacks and navigation split views.
struct NavigationSplitView
A view that presents views in two or three columns, where selections in leading columns control presentations in subsequent columns.
Sets a fixed, preferred width for the column containing this view.
Sets a flexible, preferred width for the column containing this view.
struct NavigationSplitViewVisibility
The visibility of the leading columns in a navigation split view.
struct NavigationLink
A view that controls a navigation presentation.
https://developer.apple.com/documentation/swiftui/view/navigationtitle(_:)
https://developer.apple.com/documentation/swiftui/understanding-the-composition-of-navigation-stack
https://developer.apple.com/documentation/swiftui/bringing-robust-navigation-structure-to-your-swiftui-app
https://developer.apple.com/documentation/swiftui/migrating-to-new-navigation-types
https://developer.apple.com/documentation/swiftui/view/navigationsplitviewcolumnwidth(_:)
https://developer.apple.com/documentation/swiftui/view/navigationsplitviewcolumnwidth(min:ideal:max:)
https://developer.apple.com/documentation/swiftui/navigationsplitviewvisibility
https://developer.apple.com/documentation/swiftui/navigationlink
https://developer.apple.com/documentation/swiftui/navigationpath
https://developer.apple.com/documentation/swiftui/view/navigationdestination(for:destination:)
https://developer.apple.com/documentation/swiftui/view/navigationdestination(ispresented:destination:)
https://developer.apple.com/documentation/swiftui/view/navigationdestination(item:destination:)
https://developer.apple.com/documentation/swiftui/navigationsplitviewcolumn
https://developer.apple.com/documentation/swiftui/view/navigationsubtitle(_:)
https://developer.apple.com/documentation/swiftui/view/navigationdocument(_:)
https://developer.apple.com/documentation/swiftui/view/navigationdocument(_:preview:)
https://developer.apple.com/documentation/swiftui/view/navigationbarbackbuttonhidden(_:)
https://developer.apple.com/documentation/swiftui/view/navigationbartitledisplaymode(_:)
https://developer.apple.com/documentation/swiftui/navigationbaritem
https://developer.apple.com/documentation/swiftui/environmentvalues/sidebarrowsize
https://developer.apple.com/documentation/swiftui/sidebarrowsize
- SwiftUI
- SidebarRowSize
Enumeration
SidebarRowSize
The standard sizes of sidebar rows.
enum SidebarRowSize
Overview
On macOS, sidebar rows have three different sizes: small, medium, and large. The size is primarily controlled by the current users’ “Sidebar Icon Size” in Appearance settings, and applies to all applications.
On all other platforms, the only supported sidebar size is .medium.
This size can be read or written in the environment using EnvironmentValues.sidebarRowSize.
Topics
Getting row sizes
case small
The standard “small” row size
case medium
The standard “medium” row size
case large
The standard “large” row size
Relationships
Conforms To
CopyableEquatableHashableSendableSendableMetatype
See Also
Configuring the sidebar
var sidebarRowSize: SidebarRowSize
The current size of sidebar rows.
https://developer.apple.com/documentation/swiftui/enhancing-your-app-content-with-tab-navigation
https://developer.apple.com/documentation/swiftui/tab
- SwiftUI
- Tab
Structure
Tab
The content for a tab and the tab’s associated tab item in a tab view.
Topics
Creating a tab
Creates a new tab that you can use in a tab view, with an empty label.
init(value:content:)
init(value:role:content:)
Creates a new tab with a label inferred from the role.
Creating a tab with label
Creates a new tab with a label that you can use in a tab view.
Creating a tab with system symbol
init(_:systemImage:content:)
Creates a new tab that you can use in a tab view using a system image for the tab item’s image, and a localized string key label.
init(_:systemImage:value:content:)
Creates a tab that the tab view presents when the tab view’s selection matches the tab’s value using a system image for the tab’s tab item image, with a localized string key label.
init(_:systemImage:role:content:)
init(_:systemImage:value:role:content:)
Creating a tab with image
init(_:image:content:)
Creates a new tab that you can use in a tab view, with a localized string key label.
init(_:image:value:content:)
Creates a tab that the tab view presents when the tab view’s selection matches the tab’s value, with a localized string key label.
init(_:image:role:content:)
init(_:image:value:role:content:)
Supporting types
struct DefaultTabLabel
The default label to use for a tab or tab section.
Initializers
init(value:content:label:)
init(value:role:content:label:)
Relationships
Conforms To
CopyableTabContentConforms whenValueconforms toHashable,Contentconforms toView, andLabelconforms toView.
See Also
Presenting views in tabs
Enhancing your app’s content with tab navigation
Keep your app content front and center while providing quick access to navigation using the tab bar.
struct TabView
A view that switches between multiple child views using interactive user interface elements.
struct TabRole
A value that defines the purpose of the tab.
struct TabSection
A container that you can use to add hierarchy within a tab view.
Sets the style for the tab view within the current environment.
https://developer.apple.com/documentation/swiftui/tabrole
- SwiftUI
- TabRole
Structure
TabRole
A value that defines the purpose of the tab.
struct TabRole
Topics
Type Properties
static var search: TabRole
The search role.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Presenting views in tabs
Enhancing your app’s content with tab navigation
Keep your app content front and center while providing quick access to navigation using the tab bar.
struct TabView
A view that switches between multiple child views using interactive user interface elements.
struct Tab
The content for a tab and the tab’s associated tab item in a tab view.
struct TabSection
A container that you can use to add hierarchy within a tab view.
Sets the style for the tab view within the current environment.
https://developer.apple.com/documentation/swiftui/tabsection
- SwiftUI
- TabSection
Structure
TabSection
A container that you can use to add hierarchy within a tab view.
Overview
Use TabSection to organize tab content into separate sections. Each section has custom tab content that you provide on a per-instance basis. You can also provide a header for each section.
Topics
Creating a tab section
init(content:)
Creates a section with the provided section content.
init(_:content:)
Creates a section with the provided content.
init(content:header:)
Creates a section with a header and the provided section content.
Supporting types
struct DefaultTabLabel
The default label to use for a tab or tab section.
Relationships
Conforms To
CopyableTabContentConforms whenHeaderconforms toView,Contentconforms toTabContent,Footerconforms toView, andSelectionValueisContent.TabValue.
See Also
Presenting views in tabs
Enhancing your app’s content with tab navigation
Keep your app content front and center while providing quick access to navigation using the tab bar.
struct TabView
A view that switches between multiple child views using interactive user interface elements.
struct Tab
The content for a tab and the tab’s associated tab item in a tab view.
struct TabRole
A value that defines the purpose of the tab.
Sets the style for the tab view within the current environment.
https://developer.apple.com/documentation/swiftui/view/tabviewstyle(_:)
https://developer.apple.com/documentation/swiftui/view/tabviewsidebarheader(content:)
#app-main)
- SwiftUI
- View
- tabViewSidebarHeader(content:)
Instance Method
tabViewSidebarHeader(content:)
Adds a custom header to the sidebar of a tab view.
nonisolated
Discussion
The header appears at the top of the sidebar before any tab labels and can scroll with the content. The header is only visible when the TabView is displaying the sidebar.
The following example adds a welcome message to the top of the sidebar:
TabView { Tab("Home", systemImage: "house") { HomeView() }
Tab("Alerts", systemImage: "bell") { AlertsView() }
Tab("Browse", systemImage: "list.bullet") { MyBrowseView() } } .tabViewStyle(.sidebarAdaptable) .tabViewSidebarHeader { WelcomeHeaderView() }
See Also
Configuring a tab bar
Adds a custom footer to the sidebar of a tab view.
Adds a custom bottom bar to the sidebar of a tab view.
struct AdaptableTabBarPlacement
A placement for tabs in a tab view using the adaptable sidebar style.
var tabBarPlacement: TabBarPlacement?
The current placement of the tab bar.
struct TabBarPlacement
A placement for tabs in a tab view.
var isTabBarShowingSections: Bool
A Boolean value that determines whether a tab view shows the expanded contents of a tab section.
struct TabBarMinimizeBehavior Beta
enum TabViewBottomAccessoryPlacement
A placement of the bottom accessory in a tab view. You can use this to adjust the content of the accessory view based on the placement.
Beta
https://developer.apple.com/documentation/swiftui/view/tabviewsidebarfooter(content:)
https://developer.apple.com/documentation/swiftui/view/tabviewsidebarbottombar(content:)
#app-main)
- SwiftUI
- View
- tabViewSidebarBottomBar(content:)
Instance Method
tabViewSidebarBottomBar(content:)
Adds a custom bottom bar to the sidebar of a tab view.
nonisolated
Discussion
The content is pinned at the bottom of the sidebar, so it’s always visible when the sidebar is visible and doesn’t scroll with the content.
The following example adds an account button to the bottom of the sidebar:
TabView { Tab("Home", systemImage: "house") { HomeView() }
Tab("Alerts", systemImage: "bell") { AlertsView() }
Tab("Browse", systemImage: "list.bullet") { MyBrowseView() } } .tabViewStyle(.sidebarAdaptable) .tabViewSidebarBottomBar { AccountButton() }
See Also
Configuring a tab bar
Adds a custom header to the sidebar of a tab view.
Adds a custom footer to the sidebar of a tab view.
struct AdaptableTabBarPlacement
A placement for tabs in a tab view using the adaptable sidebar style.
var tabBarPlacement: TabBarPlacement?
The current placement of the tab bar.
struct TabBarPlacement
A placement for tabs in a tab view.
var isTabBarShowingSections: Bool
A Boolean value that determines whether a tab view shows the expanded contents of a tab section.
struct TabBarMinimizeBehavior Beta
enum TabViewBottomAccessoryPlacement
A placement of the bottom accessory in a tab view. You can use this to adjust the content of the accessory view based on the placement.
Beta
https://developer.apple.com/documentation/swiftui/adaptabletabbarplacement
https://developer.apple.com/documentation/swiftui/environmentvalues/tabbarplacement
- SwiftUI
- EnvironmentValues
- tabBarPlacement
Instance Property
tabBarPlacement
The current placement of the tab bar.
var tabBarPlacement: TabBarPlacement? { get }
Discussion
Note that this value is only set within the content views of a TabView.
A nil value corresponds to an undefined placement.
See Also
Configuring a tab bar
Adds a custom header to the sidebar of a tab view.
Adds a custom footer to the sidebar of a tab view.
Adds a custom bottom bar to the sidebar of a tab view.
struct AdaptableTabBarPlacement
A placement for tabs in a tab view using the adaptable sidebar style.
struct TabBarPlacement
A placement for tabs in a tab view.
var isTabBarShowingSections: Bool
A Boolean value that determines whether a tab view shows the expanded contents of a tab section.
struct TabBarMinimizeBehavior Beta
enum TabViewBottomAccessoryPlacement
A placement of the bottom accessory in a tab view. You can use this to adjust the content of the accessory view based on the placement.
Beta
https://developer.apple.com/documentation/swiftui/tabbarplacement
- SwiftUI
- TabBarPlacement
Structure
TabBarPlacement
A placement for tabs in a tab view.
struct TabBarPlacement
Topics
Type Properties
static let bottomBar: TabBarPlacement
Bottom bar of a tab view.
static let ornament: TabBarPlacement
Tab view displaying as an ornament.
static let pageIndicator: TabBarPlacement
Tab view displaying as an indicator that shows the position within the pages.
static let sidebar: TabBarPlacement
The sidebar of a tab view.
static let topBar: TabBarPlacement
Top bar of a tab view.
Relationships
Conforms To
EquatableHashable
See Also
Configuring a tab bar
Adds a custom header to the sidebar of a tab view.
Adds a custom footer to the sidebar of a tab view.
Adds a custom bottom bar to the sidebar of a tab view.
struct AdaptableTabBarPlacement
A placement for tabs in a tab view using the adaptable sidebar style.
var tabBarPlacement: TabBarPlacement?
The current placement of the tab bar.
var isTabBarShowingSections: Bool
A Boolean value that determines whether a tab view shows the expanded contents of a tab section.
struct TabBarMinimizeBehavior Beta
enum TabViewBottomAccessoryPlacement
A placement of the bottom accessory in a tab view. You can use this to adjust the content of the accessory view based on the placement.
Beta
https://developer.apple.com/documentation/swiftui/environmentvalues/istabbarshowingsections
- SwiftUI
- EnvironmentValues
- isTabBarShowingSections
Instance Property
isTabBarShowingSections
A Boolean value that determines whether a tab view shows the expanded contents of a tab section.
var isTabBarShowingSections: Bool { get }
See Also
Configuring a tab bar
Adds a custom header to the sidebar of a tab view.
Adds a custom footer to the sidebar of a tab view.
Adds a custom bottom bar to the sidebar of a tab view.
struct AdaptableTabBarPlacement
A placement for tabs in a tab view using the adaptable sidebar style.
var tabBarPlacement: TabBarPlacement?
The current placement of the tab bar.
struct TabBarPlacement
A placement for tabs in a tab view.
struct TabBarMinimizeBehavior Beta
enum TabViewBottomAccessoryPlacement
A placement of the bottom accessory in a tab view. You can use this to adjust the content of the accessory view based on the placement.
Beta
https://developer.apple.com/documentation/swiftui/tabbarminimizebehavior
- SwiftUI
- TabBarMinimizeBehavior Beta
Structure
TabBarMinimizeBehavior
struct TabBarMinimizeBehavior
Topics
Type Properties
static let automatic: TabBarMinimizeBehavior
Determine the behavior automatically based on the surrounding context.
static let never: TabBarMinimizeBehavior
Never minimize the tab bar.
static let onScrollDown: TabBarMinimizeBehavior
Minimize the tab bar when downwards scrolling starts. Minimizing is supported for tab bars on only iPhone.
static let onScrollUp: TabBarMinimizeBehavior
Minimize the tab bar when upwards scrolling starts. Minimizing is supported for tab bars on only iPhone.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Configuring a tab bar
Adds a custom header to the sidebar of a tab view.
Adds a custom footer to the sidebar of a tab view.
Adds a custom bottom bar to the sidebar of a tab view.
struct AdaptableTabBarPlacement
A placement for tabs in a tab view using the adaptable sidebar style.
var tabBarPlacement: TabBarPlacement?
The current placement of the tab bar.
struct TabBarPlacement
A placement for tabs in a tab view.
var isTabBarShowingSections: Bool
A Boolean value that determines whether a tab view shows the expanded contents of a tab section.
enum TabViewBottomAccessoryPlacement
A placement of the bottom accessory in a tab view. You can use this to adjust the content of the accessory view based on the placement.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/tabviewbottomaccessoryplacement
- SwiftUI
- TabViewBottomAccessoryPlacement Beta
Enumeration
TabViewBottomAccessoryPlacement
A placement of the bottom accessory in a tab view. You can use this to adjust the content of the accessory view based on the placement.
enum TabViewBottomAccessoryPlacement
Overview
The following example shows playback controls when the view is inline, and an expanded slider player view when the view is expanded.
struct MusicPlaybackView: View { @Environment(.tabViewBottomAccessoryPlacement) var placement
var body: some View { switch placement { case .inline: ControlsPlaybackView() case .expanded: SliderPlaybackView() } }
You can set the TabView bottom accessory using tabViewBottomAccessory(content:)
TabView { Tab("Home", systemImage: "house") { HomeView() }
Tab("Alerts", systemImage: "bell") { AlertsView() }
TabSection("Categories") { Tab("Climate", systemImage: "fan") { ClimateView() }
Tab("Lights", systemImage: "lightbulb") { LightsView() } } } .tabViewBottomAccessory { HomeStatusView() }
Topics
Enumeration Cases
case expanded
The bar is expanded on top of the bottom tab bar, if there is a bottom tab bar, or at the bottom of the tab’s content view.
case inline
The view is displayed in line with the bottom tab bar.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Configuring a tab bar
Adds a custom header to the sidebar of a tab view.
Adds a custom footer to the sidebar of a tab view.
Adds a custom bottom bar to the sidebar of a tab view.
struct AdaptableTabBarPlacement
A placement for tabs in a tab view using the adaptable sidebar style.
var tabBarPlacement: TabBarPlacement?
The current placement of the tab bar.
struct TabBarPlacement
A placement for tabs in a tab view.
var isTabBarShowingSections: Bool
A Boolean value that determines whether a tab view shows the expanded contents of a tab section.
struct TabBarMinimizeBehavior Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/sectionactions(content:)
#app-main)
- SwiftUI
- View
- sectionActions(content:)
Instance Method
sectionActions(content:)
Adds custom actions to a section.
nonisolated
Discussion
On iOS, the actions are displayed as items after the content of the section. On macOS, the actions are displayed when a user hovers over the section.
The following example adds an ‘Add’ button to the ‘Categories’ section.
List { Label("Home", systemImage: "house") Label("Alerts", systemImage: "bell")
Section("Categories") { Label("Climate", systemImage: "fan") Label("Lights", systemImage: "lightbulb") } .sectionActions { Button("Add Category", systemImage: "plus") { } } }
See Also
Configuring a tab
struct TabPlacement
A place that a tab can appear.
struct TabContentBuilder
A result builder that constructs tabs for a tab view that supports programmatic selection. This builder requires that all tabs in the tab view have the same selection type.
protocol TabContent
A type that provides content for programmatically selectable tabs in a tab view.
struct AnyTabContent
Type erased tab content.
https://developer.apple.com/documentation/swiftui/tabplacement
- SwiftUI
- TabPlacement
Structure
TabPlacement
A place that a tab can appear.
struct TabPlacement
Overview
Not all TabView styles support all placements.
Topics
Type Properties
static let automatic: TabPlacement
The default tab location.
static let pinned: TabPlacement
The pinned tab placement location.
static let sidebarOnly: TabPlacement
The sidebar tab placement location.
Relationships
Conforms To
EquatableHashable
See Also
Configuring a tab
Adds custom actions to a section.
struct TabContentBuilder
A result builder that constructs tabs for a tab view that supports programmatic selection. This builder requires that all tabs in the tab view have the same selection type.
protocol TabContent
A type that provides content for programmatically selectable tabs in a tab view.
struct AnyTabContent
Type erased tab content.
https://developer.apple.com/documentation/swiftui/tabcontentbuilder
- SwiftUI
- TabContentBuilder
Structure
TabContentBuilder
A result builder that constructs tabs for a tab view that supports programmatic selection. This builder requires that all tabs in the tab view have the same selection type.
@resultBuilder
Topics
Structures
struct Content
A view representation of the content of a builder-based tab view with selection.
Type Methods
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(_:))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(::))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(::_:))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(::::))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(::::_:))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(::::::))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(::::::_:))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(::::::::))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(::::::::_:))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildblock(::::::::::))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildexpression(_:))
`](https://developer.apple.com/documentation/swiftui/tabcontentbuilder/buildif(_:))
See Also
Configuring a tab
Adds custom actions to a section.
struct TabPlacement
A place that a tab can appear.
protocol TabContent
A type that provides content for programmatically selectable tabs in a tab view.
struct AnyTabContent
Type erased tab content.
https://developer.apple.com/documentation/swiftui/tabcontent
https://developer.apple.com/documentation/swiftui/anytabcontent
- SwiftUI
- AnyTabContent
Structure
AnyTabContent
Type erased tab content.
Topics
Initializers
Create an instance that type-erases tabContent.
Relationships
Conforms To
TabContent
See Also
Configuring a tab
Adds custom actions to a section.
struct TabPlacement
A place that a tab can appear.
struct TabContentBuilder
A result builder that constructs tabs for a tab view that supports programmatic selection. This builder requires that all tabs in the tab view have the same selection type.
protocol TabContent
A type that provides content for programmatically selectable tabs in a tab view.
https://developer.apple.com/documentation/swiftui/view/tabviewcustomization(_:)
https://developer.apple.com/documentation/swiftui/tabviewcustomization
- SwiftUI
- TabViewCustomization
Structure
TabViewCustomization
The customizations a person makes to an adaptable sidebar tab view.
struct TabViewCustomization
Overview
By default, if a person hasn’t made customizations, tabs appear according to the default builder visibilities and sections appear in the order you declare in the tab view’s tab builder.
You can change the default visibility by using the defaultVisibility(_:for:) with a sidebar placement.
You can change the default section order by changing the order in the builder. If there’s an existing persisted customization, reset the order by calling resetTabOrder() when you change the order.
All tabs and tab sections that support customization need to have a customization ID. You can mark a tab as being non-customizable by specifying a disabled behavior in all adaptable tab bar placements using customizationBehavior(_:for:).
On macOS, a default interaction is provided for reordering sections but not for controlling the visibility of individual tabs. A custom experience should be provided if desired by setting the visibility of the tab on the customization.
The following code example uses @AppStorage to automatically persist any visibility or section order customizations a person makes.
@AppStorage private var customization: TabViewCustomization
TabView { Tab("Home", systemImage: "house") { MyHomeView() } .customizationID("com.myApp.home")
Tab("Reports", systemImage: "chart.bar") { MyReportsView() } .customizationID("com.myApp.reports")
TabSection("Categories") { Tab("Climate", systemImage: "fan") { ClimateView() } .customizationID("com.myApp.climate")
Tab("Lights", systemImage: "lightbulb") { LightsView() } .customizationID("com.myApp.lights") } .customizationID("com.myApp.browse") } .tabViewStyle(.sidebarAdaptable) .tabViewCustomization($customization)
Topics
Structures
struct SectionCustomization
The customizations a user has made to a TabSection.
struct TabCustomization
The customizations a user has made to a Tab.
Initializers
init()
Creates an empty tab sidebar customization.
Instance Methods
func resetSectionOrder()
Resets ordering )
Resets all tab sidebar visibilities
The customization of the section, identified by its customization identifier.
The customization for a section’s children, identified by the section’s customization identifier.
Deprecated
The visibility of the tab identified by its customization identifier.
The customization of the tab, identified by its customization identifier.
Relationships
Conforms To
DecodableEncodableEquatableSendableSendableMetatype
See Also
Enabling tab customization
Specifies the customizations to apply to the sidebar representation of the tab view.
struct TabCustomizationBehavior
The customization behavior of customizable tab view content.
https://developer.apple.com/documentation/swiftui/tabcustomizationbehavior
https://developer.apple.com/documentation/swiftui/hsplitview
- SwiftUI
- HSplitView
Structure
HSplitView
A layout container that arranges its children in a horizontal line and allows the user to resize them using dividers placed between them.
Topics
Relationships
Conforms To
View
See Also
Displaying views in multiple panes
struct VSplitView
A layout container that arranges its children in a vertical line and allows the user to resize them using dividers placed between them.
https://developer.apple.com/documentation/swiftui/vsplitview
- SwiftUI
- VSplitView
Structure
VSplitView
A layout container that arranges its children in a vertical line and allows the user to resize them using dividers placed between them.
Topics
Relationships
Conforms To
View
See Also
Displaying views in multiple panes
struct HSplitView
A layout container that arranges its children in a horizontal line and allows the user to resize them using dividers placed between them.
https://developer.apple.com/documentation/swiftui/navigationview
- SwiftUI
- NavigationView Deprecated
Structure
NavigationView
A view for presenting a stack of views that represents a visible path in a navigation hierarchy.
iOS 13.0–26.0DeprecatediPadOS 13.0–26.0DeprecatedMac Catalyst 13.0–26.0DeprecatedmacOS 10.15–26.0DeprecatedtvOS 13.0–26.0DeprecatedvisionOS 1.0–26.0DeprecatedwatchOS 7.0–26.0Deprecated
Mentioned in
Migrating to new navigation types
Displaying data in lists
Picking container views for your content
Overview
Use a NavigationView to create a navigation-based app in which the user can traverse a collection of views. Users navigate to a destination view by selecting a NavigationLink that you provide. On iPadOS and macOS, the destination content appears in the next column. Other platforms push a new view onto the stack, and enable removing items from the stack with platform-specific controls, like a Back button or a swipe gesture.
Use the init(content:) initializer to create a navigation view that directly associates navigation links and their destination views:
NavigationView { List(model.notes) { note in NavigationLink(note.title, destination: NoteEditor(id: note.id)) } Text("Select a Note") }
Style a navigation view by modifying it with the navigationViewStyle(_:) view modifier. Use other modifiers, like navigationTitle(_:), on views presented by the navigation view to customize the navigation interface for the presented view.
Topics
Creating a navigation view
Creates a destination-based navigation view.
Styling navigation views
Sets the style for navigation views within this view.
protocol NavigationViewStyle
A specification for the appearance and interaction of a navigation view.
Relationships
Conforms To
View
See Also
Deprecated Types
Sets the tab bar item associated with this view.
Deprecated
https://developer.apple.com/documentation/swiftui/view/tabitem(_:)
#app-main)
- SwiftUI
- View
- tabItem(_:) Deprecated
Instance Method
tabItem(_:)
Sets the tab bar item associated with this view.
iOS 13.0–26.0DeprecatediPadOS 13.0–26.0DeprecatedMac Catalyst 13.0–26.0DeprecatedmacOS 10.15–26.0DeprecatedtvOS 13.0–26.0DeprecatedwatchOS 7.0–26.0Deprecated
nonisolated
Parameters
label
The tab bar item to associate with this view.
Discussion
Use tabItem(_:) to configure a view as a tab bar item in a TabView. The example below adds two views as tabs in a TabView:
struct View1: View { var body: some View { Text("View 1") } }
struct View2: View { var body: some View { Text("View 2") } }
struct TabItem: View { var body: some View { TabView { View1() .tabItem { Label("Menu", systemImage: "list.dash") }
View2() .tabItem { Label("Order", systemImage: "square.and.pencil") } } } }
See Also
Deprecated Types
struct NavigationView
A view for presenting a stack of views that represents a visible path in a navigation hierarchy.
Deprecated
https://developer.apple.com/documentation/swiftui/navigationstack),
https://developer.apple.com/documentation/swiftui/tabview).
https://developer.apple.com/documentation/swiftui/view/navigationsplitviewstyle(_:))
https://developer.apple.com/documentation/swiftui/view/navigationtitle(_:))
https://developer.apple.com/documentation/swiftui/understanding-the-composition-of-navigation-stack)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/bringing-robust-navigation-structure-to-your-swiftui-app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/migrating-to-new-navigation-types)
https://developer.apple.com/documentation/swiftui/view/navigationsplitviewcolumnwidth(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/navigationsplitviewcolumnwidth(min:ideal:max:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/navigationsplitviewvisibility)
https://developer.apple.com/documentation/swiftui/navigationlink)
https://developer.apple.com/documentation/swiftui/navigationstack)
https://developer.apple.com/documentation/swiftui/navigationpath)
https://developer.apple.com/documentation/swiftui/view/navigationdestination(for:destination:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/navigationdestination(ispresented:destination:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/navigationstack).
https://developer.apple.com/documentation/swiftui/view/navigationdestination(item:destination:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/navigationsplitviewcolumn)
https://developer.apple.com/documentation/swiftui/view/navigationsubtitle(_:))
https://developer.apple.com/documentation/swiftui/view/navigationdocument(_:))
https://developer.apple.com/documentation/swiftui/view/navigationdocument(_:preview:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/navigationbarbackbuttonhidden(_:))
https://developer.apple.com/documentation/swiftui/view/navigationbartitledisplaymode(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/navigationbaritem)
https://developer.apple.com/documentation/swiftui/environmentvalues/sidebarrowsize)
https://developer.apple.com/documentation/swiftui/sidebarrowsize)
https://developer.apple.com/documentation/swiftui/enhancing-your-app-content-with-tab-navigation)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/tabview)
https://developer.apple.com/documentation/swiftui/tab)
https://developer.apple.com/documentation/swiftui/tabrole)
https://developer.apple.com/documentation/swiftui/tabsection)
https://developer.apple.com/documentation/swiftui/view/tabviewstyle(_:))
https://developer.apple.com/documentation/swiftui/view/tabviewsidebarheader(content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/tabviewsidebarfooter(content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/tabviewsidebarbottombar(content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/adaptabletabbarplacement)
https://developer.apple.com/documentation/swiftui/environmentvalues/tabbarplacement)
https://developer.apple.com/documentation/swiftui/tabbarplacement)
https://developer.apple.com/documentation/swiftui/environmentvalues/istabbarshowingsections)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/tabbarminimizebehavior)
https://developer.apple.com/documentation/swiftui/tabviewbottomaccessoryplacement)
https://developer.apple.com/documentation/swiftui/view/sectionactions(content:))
https://developer.apple.com/documentation/swiftui/tabplacement)
https://developer.apple.com/documentation/swiftui/tabcontentbuilder)
https://developer.apple.com/documentation/swiftui/tabcontent)
https://developer.apple.com/documentation/swiftui/anytabcontent)
https://developer.apple.com/documentation/swiftui/view/tabviewcustomization(_:))
https://developer.apple.com/documentation/swiftui/tabviewcustomization)
https://developer.apple.com/documentation/swiftui/tabcustomizationbehavior)
https://developer.apple.com/documentation/swiftui/hsplitview)
https://developer.apple.com/documentation/swiftui/vsplitview)
https://developer.apple.com/documentation/swiftui/navigationview)
https://developer.apple.com/documentation/swiftui/view/tabitem(_:))
https://developer.apple.com/documentation/swiftui/app/body-swift.property
- SwiftUI
- App
- body
Instance Property
body
The content and behavior of the app.
@SceneBuilder @MainActor @preconcurrency var body: Self.Body { get }
Required
Discussion
For any app that you create, provide a computed body property that defines your app’s scenes, which are instances that conform to the Scene protocol. For example, you can create a simple app with a single scene containing a single view:
@main struct MyApp: App { var body: some Scene { WindowGroup { Text("Hello, world!") } } }
Swift infers the app’s Body associated type based on the scene provided by the body property.
See Also
Implementing an app
associatedtype Body : Scene
The type of scene representing the content of the app.
https://developer.apple.com/documentation/swiftui/app/main()
#app-main)
- SwiftUI
- App
- main()
Type Method
main()
Initializes and runs the app.
@MainActor @preconcurrency static func main()
Discussion
If you precede your App conformer’s declaration with the @main attribute, the system calls the conformer’s main() method to launch the app. SwiftUI provides a default implementation of the method that manages the launch process in a platform-appropriate way.
See Also
Running an app
init()
Creates an instance of the app using the body that you define for its content.
Required
https://developer.apple.com/documentation/swiftui/stateobject
- SwiftUI
- StateObject
Structure
StateObject
A property wrapper type that instantiates an observable object.
@MainActor @frozen @propertyWrapper @preconcurrency
Overview
Use a state object as the single source of truth for a reference type that you store in a view hierarchy. Create a state object in an App, Scene, or View by applying the @StateObject attribute to a property declaration and providing an initial value that conforms to the ObservableObject protocol. Declare state objects as private to prevent setting them from a memberwise initializer, which can conflict with the storage management that SwiftUI provides:
class DataModel: ObservableObject { @Published var name = "Some Name" @Published var isEnabled = false }
struct MyView: View { @StateObject private var model = DataModel() // Create the state object.
var body: some View { Text(model.name) // Updates when the data model changes. MySubView() .environmentObject(model) } }
SwiftUI creates a new instance of the model object only once during the lifetime of the container that declares the state object. For example, SwiftUI doesn’t create a new instance if a view’s inputs change, but does create a new instance if the identity of a view changes. When published properties of the observable object change, SwiftUI updates any view that depends on those properties, like the Text view in the above example.
Share state objects with subviews
You can pass a state object into a subview through a property that has the ObservedObject attribute. Alternatively, add the object to the environment of a view hierarchy by applying the environmentObject(_:) modifier to a view, like MySubView in the above code. You can then read the object inside MySubView or any of its descendants using the EnvironmentObject attribute:
struct MySubView: View { @EnvironmentObject var model: DataModel
var body: some View { Toggle("Enabled", isOn: $model.isEnabled) } }
Get a Binding to the state object’s properties using the dollar sign ( $) operator. Use a binding when you want to create a two-way connection. In the above code, the Toggle controls the model’s isEnabled value through a binding.
Initialize state objects using external data
When a state object’s initial state depends on data that comes from outside its container, you can call the object’s initializer explicitly from within its container’s initializer. For example, suppose the data model from the previous example takes a name input during initialization and you want to use a value for that name that comes from outside the view. You can do this with a call to the state object’s initializer inside an explicit initializer that you create for the view:
struct MyInitializableView: View { @StateObject private var model: DataModel
init(name: String) { // SwiftUI ensures that the following initialization uses the // closure only once during the lifetime of the view, so // later changes to the view's name input have no effect. _model = StateObject(wrappedValue: DataModel(name: name)) }
var body: some View { VStack { Text("Name: (model.name)") } } }
Use caution when doing this. SwiftUI only initializes a state object the first time you call its initializer in a given view. This ensures that the object provides stable storage even as the view’s inputs change. However, it might result in unexpected behavior or unwanted side effects if you explicitly initialize the state object.
In the above example, if the name input to MyInitializableView changes, SwiftUI reruns the view’s initializer with the new value. However, SwiftUI runs the autoclosure that you provide to the state object’s initializer only the first time you call the state object’s initializer, so the model’s stored name value doesn’t change.
Explicit state object initialization works well when the external data that the object depends on doesn’t change for a given instance of the object’s container. For example, you can create two views with different constant names:
var body: some View { VStack { MyInitializableView(name: "Ravi") MyInitializableView(name: "Maria") } }
Force reinitialization by changing view identity
If you want SwiftUI to reinitialize a state object when a view input changes, make sure that the view’s identity changes at the same time. One way to do this is to bind the view’s identity to the value that changes using the id(_:) modifier. For example, you can ensure that the identity of an instance of MyInitializableView changes when its name input changes:
MyInitializableView(name: name) .id(name) // Binds the identity of the view to the name property.
If you need the view to reinitialize state based on changes in more than one value, you can combine the values into a single identifier using a Hasher. For example, if you want to update the data model in MyInitializableView when the values of either name or isEnabled change, you can combine both variables into a single hash:
var hash: Int { var hasher = Hasher() hasher.combine(name) hasher.combine(isEnabled) return hasher.finalize() }
Then apply the combined hash to the view as an identifier:
MyInitializableView(name: name, isEnabled: isEnabled) .id(hash)
Be mindful of the performance cost of reinitializing the state object every time the input changes. Also, changing view identity can have side effects. For example, SwiftUI doesn’t automatically animate changes inside the view if the view’s identity changes at the same time. Also, changing the identity resets all state held by the view, including values that you manage as State, FocusState, GestureState, and so on.
Topics
Creating a state object
Creates a new state object with an initial wrapped value.
Getting the value
var wrappedValue: ObjectType
The underlying value referenced by the state object.
A projection of the state object that creates bindings to its properties.
Relationships
Conforms To
DynamicPropertySendableSendableMetatype
See Also
Creating model data
Managing model data in your app
Create connections between your app’s data model and views.
Migrating from the Observable Object protocol to the Observable macro
Update your existing app to leverage the benefits of Observation in Swift.
@attached(member, names: named(_$observationRegistrar), named(access), named(withMutation), named(shouldNotifyObservers)) @attached(memberAttribute) @attached(extension, conformances: Observable) macro Observable()
Defines and implements conformance of the Observable protocol.
Monitoring data changes in your app
Show changes to data in your app’s user interface by using observable objects.
struct ObservedObject
A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.
protocol ObservableObject : AnyObject
A type of object with a publisher that emits before the object has changed.
https://developer.apple.com/documentation/swiftui/observedobject
- SwiftUI
- ObservedObject
Structure
ObservedObject
A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.
@MainActor @propertyWrapper @preconcurrency @frozen
Overview
Add the @ObservedObject attribute to a parameter of a SwiftUI View when the input is an ObservableObject and you want the view to update when the object’s published properties change. You typically do this to pass a StateObject into a subview.
The following example defines a data model as an observable object, instantiates the model in a view as a state object, and then passes the instance to a subview as an observed object:
class DataModel: ObservableObject { @Published var name = "Some Name" @Published var isEnabled = false }
struct MyView: View { @StateObject private var model = DataModel()
var body: some View { Text(model.name) MySubView(model: model) } }
struct MySubView: View { @ObservedObject var model: DataModel
var body: some View { Toggle("Enabled", isOn: $model.isEnabled) } }
When any published property of the observable object changes, SwiftUI updates any view that depends on the object. Subviews can also make updates to the model properties, like the Toggle in the above example, that propagate to other observers throughout the view hierarchy.
Don’t specify a default or initial value for the observed object. Use the attribute only for a property that acts as an input for a view, as in the above example.
Topics
Creating an observed object
init(wrappedValue: ObjectType)
Creates an observed object with an initial wrapped value.
init(initialValue: ObjectType)
Creates an observed object with an initial value.
Getting the value
var wrappedValue: ObjectType
The underlying value that the observed object references.
A projection of the observed object that creates bindings to its properties.
struct Wrapper
A wrapper of the underlying observable object that can create bindings to its properties.
Relationships
Conforms To
DynamicPropertySendableSendableMetatype
See Also
Creating model data
Managing model data in your app
Create connections between your app’s data model and views.
Migrating from the Observable Object protocol to the Observable macro
Update your existing app to leverage the benefits of Observation in Swift.
@attached(member, names: named(_$observationRegistrar), named(access), named(withMutation), named(shouldNotifyObservers)) @attached(memberAttribute) @attached(extension, conformances: Observable) macro Observable()
Defines and implements conformance of the Observable protocol.
Monitoring data changes in your app
Show changes to data in your app’s user interface by using observable objects.
struct StateObject
A property wrapper type that instantiates an observable object.
protocol ObservableObject : AnyObject
A type of object with a publisher that emits before the object has changed.
https://developer.apple.com/documentation/swiftui/environmentobject
- SwiftUI
- EnvironmentObject
Structure
EnvironmentObject
A property wrapper type for an observable object that a parent or ancestor view supplies.
@MainActor @frozen @propertyWrapper @preconcurrency
Overview
An environment object invalidates the current view whenever the observable object that conforms to ObservableObject changes. If you declare a property as an environment object, be sure to set a corresponding model object on an ancestor view by calling its environmentObject(_:) modifier.
Topics
Creating an environment object
init()
Creates an environment object.
Getting the value
var wrappedValue: ObjectType
The underlying value referenced by the environment object.
A projection of the environment object that creates bindings to its properties using dynamic member lookup.
struct Wrapper
A wrapper of the underlying environment object that can create bindings to its properties using dynamic member lookup.
Relationships
Conforms To
DynamicPropertySendableSendableMetatype
See Also
Distributing model data throughout your app
Supplies an observable object to a view’s hierarchy.
Supplies an ObservableObject to a view subhierarchy.
https://developer.apple.com/documentation/swiftui/app/body-swift.associatedtype
- SwiftUI
- App
- Body
Associated Type
Body
The type of scene representing the content of the app.
associatedtype Body : Scene
Required
Discussion
When you create a custom app, Swift infers this type from your implementation of the required body property.
See Also
Implementing an app
var body: Self.Body
The content and behavior of the app.
https://developer.apple.com/documentation/swiftui/app/init()
#app-main)
- SwiftUI
- App
- init()
Initializer
init()
Creates an instance of the app using the body that you define for its content.
@MainActor @preconcurrency init()
Required
Discussion
Swift synthesizes a default initializer for structures that don’t provide one. You typically rely on the default initializer for your app.
See Also
Running an app
static func main()
Initializes and runs the app.
https://developer.apple.com/documentation/swiftui/app/body-swift.property)
https://developer.apple.com/documentation/swiftui/app/main())
https://developer.apple.com/documentation/swiftui/stateobject)
https://developer.apple.com/documentation/swiftui/observedobject)
https://developer.apple.com/documentation/swiftui/environmentobject)
https://developer.apple.com/documentation/swiftui/app/body-swift.associatedtype)
https://developer.apple.com/documentation/swiftui/app/init())
https://developer.apple.com/documentation/swiftui/declaring-a-custom-view
- SwiftUI
- View fundamentals
- Declaring a custom view
Article
Declaring a custom view
Define views and assemble them into a view hierarchy.
Overview
SwiftUI offers a declarative approach to user interface design. With a traditional imperative approach, the burden is on your controller code not only to instantiate, lay out, and configure views, but also to continually make updates as conditions change. In contrast, with a declarative approach, you create a lightweight description of your user interface by declaring views in a hierarchy that mirrors the desired layout of your interface. SwiftUI then manages drawing and updating these views in response to events like user input or state changes.
SwiftUI provides tools for defining and configuring the views in your user interface. You compose custom views out of built-in views that SwiftUI provides, plus other composite views that you’ve already defined. You configure these views with view modifiers and connect them to your data model. You then place your custom views within your app’s view hierarchy.
Conform to the view protocol
Declare a custom view type by defining a structure that conforms to the View protocol:
struct MyView: View { }
Like other Swift protocols, the View protocol provides a blueprint for functionality — in this case, the behavior of an element that SwiftUI draws onscreen. Conformance to the protocol comes with both requirements that a view must fulfill, and functionality that the protocol provides. After you fulfill the requirements, you can insert your custom view into a view hierarchy so that it becomes part of your app’s user interface.
Declare a body
The View protocol’s main requirement is that conforming types must define a body computed property:
struct MyView: View { var body: some View { } }
SwiftUI reads the value of this property any time it needs to update the view, which can happen repeatedly during the life of the view, typically in response to user input or system events. The value that the view returns is an element that SwiftUI draws onscreen.
The View protocol’s secondary requirement is that conforming types must indicate an associated type for the body property. However, you don’t make an explicit declaration. Instead, you declare the body property as an opaque type, using the some View syntax, to indicate only that the body’s type conforms to View. The exact type depends on the body’s content, which varies as you edit the body during development. Swift infers the exact type automatically.
Assemble the view’s content
Describe your view’s appearance by adding content to the view’s body property. You can compose the body from built-in views that SwiftUI provides, as well as custom views that you’ve defined elsewhere. For example, you can create a body that draws the string “Hello, World!” using a built-in Text view:
struct MyView: View { var body: some View { Text("Hello, World!") } }
In addition to views for specific kinds of content, controls, and indicators, like Text, Toggle, and ProgressView, SwiftUI also provides built-in views that you can use to arrange other views. For example, you can vertically stack two Text views using a VStack:
struct MyView: View { var body: some View { VStack { Text("Hello, World!") Text("Glad to meet you.") } } }
Views that take multiple input child views, like the stack in the example above, typically do so using a closure marked with the ViewBuilder attribute. This enables a multiple-statement closure that doesn’t require additional syntax at the call site. You only need to list the input views in succession.
For examples of views that contain other views, see Layout fundamentals.
Configure views with modifiers
To configure the views in your view’s body, you apply view modifiers. A modifier is nothing more than a method called on a particular view. The method returns a new, altered view that effectively takes the place of the original in the view hierarchy.
SwiftUI extends the View protocol with a large set of methods for this purpose. All View protocol conformers — both built-in and custom views — have access to these methods that alter the behavior of a view in some way. For example, you can change the font of a text view by applying the font(_:) modifier:
struct MyView: View { var body: some View { VStack { Text("Hello, World!") .font(.title) Text("Glad to meet you.") } } }
For more information about how view modifiers work, and how to use them on your views, see Configuring views.
Manage data
To supply inputs to your views, add properties. For example, you can make the font of the “Hello, World!” string configurable:
struct MyView: View { let helloFont: Font
var body: some View { VStack { Text("Hello, World!") .font(helloFont) Text("Glad to meet you.") } } }
If an input value changes, SwiftUI notices the change and redraws only the affected parts of your interface. This might involve reinitializing your entire view, but SwiftUI manages that for you.
Because the system may reinitialize a view at any time, it’s important to avoid doing any significant work in your view’s initialization code. It’s often best to omit an explicit initializer, as in the example above, allowing Swift to synthesize a member-wise initializer instead.
SwiftUI provides many tools to help you manage your app’s data under these constraints, as described in Model data. For information about Swift initializers, see Initialization in The Swift Programming Language.
Add your view to the view hierarchy
After you define a view, you can incorporate it in other views, just like you do with built-in views. You add your view by declaring it at the point in the hierarchy at which you want it to appear. For example, you could put MyView in your app’s ContentView, which Xcode creates automatically as the root view of a new app:
struct ContentView: View { var body: some View { MyView(helloFont: .title) } }
Alternatively, you could add your view as the root view of a new scene in your app, like the Settings scene that declares content for a macOS preferences window, or a WKNotificationScene scene that declares the content for a watchOS notification. For more information about defining your app structure with SwiftUI, see App organization.
See Also
Creating a view
protocol View
A type that represents part of your app’s user interface and provides modifiers that you use to configure views.
struct ViewBuilder
A custom parameter attribute that constructs views from closures.
https://developer.apple.com/documentation/swiftui/configuring-views
- SwiftUI
- View fundamentals
- Configuring views
Article
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Overview
In SwiftUI, you assemble views into a hierarchy that describes your app’s user interface. To help you customize the appearance and behavior of your app’s views, you use view modifiers. For example, you can use modifiers to:
-
Add accessibility features to a view.
-
Adjust a view’s styling, layout, and other appearance characteristics.
-
Respond to events, like copy and paste.
-
Conditionally present modal views, like popovers.
-
Configure supporting views, like toolbars.
Because view modifiers are Swift methods with behavior provided by the View protocol, you can apply them to any type that conforms to the View protocol. That includes built-in views like Text, Image, and Button, as well as views that you define.
Configure a view with a modifier
Like other Swift methods, a modifier operates on an instance — a view of some kind in this case — and can optionally take input parameters. For example, you can apply the foregroundColor(_:) modifier to set the color of a Text view:
Text("Hello, World!") .foregroundColor(.red) // Display red text.
Modifiers return a view that wraps the original view and replaces it in the view hierarchy. You can think of the two lines in the example above as resolving to a single view that displays red text.
While the code above follows the rules of Swift, the code’s structure might be unfamiliar for developers new to SwiftUI. SwiftUI uses a declarative approach, where you declare and configure a view at the point in your code that corresponds to the view’s position in the view hierarchy. For more information, see Declaring a custom view.
Chain modifiers to achieve complex effects
You commonly chain modifiers, each wrapping the result of the previous one, by calling them one after the other. For example, you can wrap a text view in an invisible box with a given width using the frame(width:height:alignment:) modifier to influence its layout, and then use the border(_:width:) modifier to draw an outline around that:
Text("Title") .frame(width: 100) .border(Color.gray)
The order in which you apply modifiers matters. For example, the border that results from the code above outlines the full width of the frame.
By specifying the frame modifier after the border modifier, SwiftUI applies the border only to the text view, which never takes more space than it needs to render its contents.
Text("Title") .border(Color.gray) // Apply the border first this time. .frame(width: 100)
Wrapping that view in an invisible one with a fixed 100 point width affects the layout of the composite view, but has no effect on the border.
Configure child views
You can apply any view modifier defined by the View protocol to any concrete view, even when the modifier doesn’t have an immediate effect on its target view. The effects of a modifier propagate to child views that don’t explicitly override the modifier.
For example, a VStack instance on its own acts only to vertically stack other views — it doesn’t have any text to display. Therefore, applying a font(_:) modifier to the stack has no effect on the stack. Yet the font modifier does apply to any of the stack’s child views, some of which might display text. You can, however, locally override the stack’s modifier by adding another to a specific child view:
VStack { Text("Title") .font(.title) // Override the font of this view. Text("First body line.") Text("Second body line.") } .font(.body) // Set a default font for text in the stack.
Use view-specific modifiers
While many view types rely on standard view modifiers for customization and control, some views do define modifiers that are specific to that view type. You can’t use such a modifier on anything but the appropriate kind of view. For example, Text defines the bold() modifier as a convenience for adding a bold effect to the view’s text. While you can use font(_:) on any view because it’s part of the View protocol, you can use bold() only on Text views. As a result, you can’t use it on a container view:
VStack { Text("Hello, world!") } .bold() // Fails because 'VStack' doesn't have a 'bold' modifier.
You also can’t use it on a Text view after applying another general modifier because general modifiers return an opaque type. For example, the return value from the padding modifier isn’t Text, but rather an opaque result type that can’t take a bold modifier:
Text("Hello, world!") .padding() .bold() // Fails because 'some View' doesn't have a 'bold' modifier.
Instead, apply the bold modifier directly to the Text view and then add the padding:
Text("Hello, world!") .bold() // Succeeds. .padding()
See Also
Modifying a view
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
https://developer.apple.com/documentation/swiftui/reducing-view-modifier-maintenance
- SwiftUI
- View fundamentals
- Reducing view modifier maintenance
Article
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Overview
To create consistent views, you might reuse the same view modifier or group of modifiers repeatedly across your views. For example, you might apply the same font and foreground color to many text instances throughout your app, so they all match. Unfortunately, this can lead to maintenance challenges, because even a small change in format, like a different font size, requires changes in many different parts of your code.
To avoid this overhead, collect a set of modifiers into a single location using an instance of the ViewModifier protocol. Then, extend the View protocol with a method that uses your modifier, making it easy to use and understand. Collecting the modifiers together provides a single location to update when you want to change them.
Create a custom view modifier
When you create your custom modifier, name it to reflect the purpose of the collection. For example, if you repeatedly apply the caption font style and a secondary color scheme to views to represent a secondary styling, collect them together as CaptionTextFormat:
struct CaptionTextFormat: ViewModifier {
content .font(.caption) .foregroundColor(.secondary) } }
Apply your modifier using the modifier(_:) method. The following code applies the above example to a Text instance:
Text("Some additional information...") .modifier(CaptionTextFormat())
Extend the view protocol to provide fluent modifier access
To make your custom view modifier conveniently accessible, extend the View protocol with a function that applies your modifier:
extension View {
modifier(CaptionTextFormat()) } }
Apply the modifier to a text view by including this extension:
Text("Some additional information...") .captionTextFormat()
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
https://developer.apple.com/documentation/swiftui/displaying-data-in-lists
- SwiftUI
- Lists
- Displaying data in lists
Article
Displaying data in lists
Visualize collections of data with platform-appropriate appearance.
Overview
Displaying a collection of data in a vertical list is a common requirement in many apps. Whether it’s a list of contacts, a schedule of events, an index of categories, or a shopping list, you’ll often find a use for a List.
List views display collections of items vertically, load rows as needed, and add scrolling when the rows don’t fit on the screen, making them suitable for displaying large collections of data.
By default, list views also apply platform-appropriate styling to their elements. For example, on iOS, the default configuration of a list displays a separator line between each row, and adds disclosure indicators next to items that initiate navigation actions.
The code in this article shows the use of list views to display a company’s staff directory. Each section enhances the usefulness of the list, by adding custom cells, splitting the list into sections, and using the list selection to navigate to a detail view.
Prepare your data for iteration
The most common use of List is for representing collections of information in your data model. The following example defines a Person as an Identifiable type with the properties name and phoneNumber. An array called staff contains two instances of this type.
struct Person: Identifiable { let id = UUID() var name: String var phoneNumber: String }
var staff = [
Person(name: "Juan Chavez", phoneNumber: "(408) 555-4301"),
Person(name: "Mei Chen", phoneNumber: "(919) 555-2481")
]
To present the contents of the array as a list, the example creates a List instance. The list’s content builder uses a ForEach to iterate over the staff array. For each member of the array, the listing creates a row view by instantiating a new Text that contains the name of the Person.
struct StaffList: View { var body: some View { List { ForEach(staff) { person in Text(person.name) } } } }
Members of a list must be uniquely identifiable from one another. Unique identifiers allow SwiftUI to automatically generate animations for changes in the underlying data, like inserts, deletions, and moves. Identify list members either by using a type that conforms to Identifiable, as Person does, or by providing an id parameter with the key path to a unique property of the type. The ForEach that populates the list above depends on this behavior, as do the List initializers that take a RandomAccessCollection of members to iterate over.
Display data inside a row
Each row inside a List must be a SwiftUI View. You may be able to represent your data with a single view such as an Image or Text view, or you may need to define a custom view to compose several views into something more complex.
As your row views get more sophisticated, refactor the views into separate view structures, passing in the data that the row needs to render. The following example defines a PersonRowView to create a two-line view for a Person, using fonts, colors, and the system “phone” icon image to visually style the data.
struct PersonRowView: View { var person: Person
var body: some View { VStack(alignment: .leading, spacing: 3) { Text(person.name) .foregroundColor(.primary) .font(.headline) HStack(spacing: 3) { Label(person.phoneNumber, systemImage: "phone") } .foregroundColor(.secondary) .font(.subheadline) } } }
struct StaffList: View { var body: some View { List { ForEach(staff) { person in PersonRowView(person: person) } } } }
For more information on composing the types of views commonly used inside list rows, see Building layouts with stack views.
Represent data hierarchy with sections
List views can also display data with a level of hierarchy, grouping associated data into sections.
Consider an expanded data model that represents an entire company, including multiple departments. Each Department has a name and an array of Person instances, and the company has an array of the Department type.
struct Department: Identifiable { let id = UUID() var name: String var staff: [Person] }
struct Company { var departments: [Department] }
var company = Company(departments: [
Department(name: "Sales", staff: [
Person(name: "Juan Chavez", phoneNumber: "(408) 555-4301"),
Person(name: "Mei Chen", phoneNumber: "(919) 555-2481"),
// ...
]),
Department(name: "Engineering", staff: [
Person(name: "Bill James", phoneNumber: "(408) 555-4450"),
Person(name: "Anne Johnson", phoneNumber: "(417) 555-9311"),
// ...
]),
// ...
])
Use Section views to give the data inside a List a level of hierarchy. Start by creating the List, using a ForEach to iterate over the company.departments array, and then create Section views for each department. Within the section’s view builder, use a ForEach to iterate over the department’s staff, and return a customized view for each Person.
List { ForEach(company.departments) { department in Section(header: Text(department.name)) { ForEach(department.staff) { person in PersonRowView(person: person) } } } }
Use Lists for Navigation
Using a NavigationLink within a List contained inside a NavigationView adds platform-appropriate visual styling, and in some cases, additional container views that provide the structure for navigation. SwiftUI uses one of two visual presentations, based on the runtime environment:
-
A list with disclosure indicators, which performs an animated navigation to a destination scene when the user chooses a list item. SwiftUI uses this presentation on watchOS, tvOS, and on most iOS devices except as described below.
-
A two-panel split view, with the top-level data as a list on the left side and the detail on the right. To get this presentation, you also need to provide a placeholder view after the list; this placeholder fills the detail pane until the user makes a selection. SwiftUI uses this two-panel approach on macOS, iPadOS, and on iOS devices with sufficient horizontal space, as indicated by the
horizontalSizeClassenvironment value.
The following example sets up a navigation-based UI by wrapping the list with a navigation view. Instances of NavigationLink wrap the list’s rows to provide a destination view to navigate to when the user taps the row. If a split view navigation is appropriate for the platform, the right panel initially contains the “No Selection” placeholder view, which the navigation view replaces with the destination view when the user makes a selection.
NavigationView { List { ForEach(company.departments) { department in Section(header: Text(department.name)) { ForEach(department.staff) { person in NavigationLink(destination: PersonDetailView(person: person)) { PersonRowView(person: person) } } } } } .navigationTitle("Staff Directory")
// Placeholder Text("No Selection") .font(.headline) }
In this example, the view passed in as the destination is a PersonDetailView, which repeats the information from the list. In a more complex app, this detail view could show more information about a Person than would fit inside the list row.
struct PersonDetailView: View { var person: Person
var body: some View { VStack { Text(person.name) .foregroundColor(.primary) .font(.title) .padding() HStack { Label(person.phoneNumber, systemImage: "phone") } .foregroundColor(.secondary) } } }
On most iOS devices (those with a compact horizontal size class), the list appears as a view by itself, and tapping a row performs an animated transition to the destination view. The following figure shows both the list view and the destination view that appears when the user makes a selection:
On the other hand, iPadOS and macOS show the list and the detail view together as a multi-column view. The following figure shows what this example looks like on macOS prior to making a selection, which means the “No selection” placeholder view is still in the detail column.
You can use the navigationViewStyle(_:) view modifier to change the default behavior of a NavigationView. For example, on iOS, the StackNavigationViewStyle forces single-column mode, even on an iPad in landscape orientation.
See Also
Creating a list
struct List
A container that presents rows of data arranged in a single column, optionally providing the ability to select one or more members.
Sets the style for lists within this view.
https://developer.apple.com/documentation/swiftui/view/body-8kl5o
- SwiftUI
- View
- body
Instance Property
body
The content and behavior of the view.
@ViewBuilder @MainActor @preconcurrency var body: Self.Body { get }
Required Default implementations provided.
Mentioned in
Declaring a custom view
Discussion
When you implement a custom view, you must implement a computed body property to provide the content for your view. Return a view that’s composed of built-in views that SwiftUI provides, plus other composite views that you’ve already defined:
struct MyView: View { var body: some View { Text("Hello, World!") } }
For more information about composing views and a view hierarchy, see Declaring a custom view.
Default Implementations
NSViewControllerRepresentable Implementations
var body: Never
Declares the content and behavior of this view.
NSViewRepresentable Implementations
UIViewControllerRepresentable Implementations
UIViewRepresentable Implementations
WKInterfaceObjectRepresentable Implementations
See Also
Implementing a custom view
associatedtype Body : View
The type of view representing the body of this view.
Required
Applies a modifier to a view and returns a new view.
Generate dynamic, interactive previews of your custom views.
https://developer.apple.com/documentation/swiftui/text
- SwiftUI
- Text
Structure
Text
A view that displays one or more lines of read-only text.
@frozen struct Text
Mentioned in
Configuring views
Declaring a custom view
Laying out a simple view
Building layouts with stack views
Performing a search operation
Overview
A text view draws a string in your app’s user interface using a body font that’s appropriate for the current platform. You can choose a different standard font, like title or caption, using the font(_:) view modifier.
Text("Hamlet") .font(.title)
If you need finer control over the styling of the text, you can use the same modifier to configure a system font or choose a custom font. You can also apply view modifiers like bold() or italic() to further adjust the formatting.
Text("by William Shakespeare") .font(.system(size: 12, weight: .light, design: .serif)) .italic()
To apply styling within specific portions of the text, you can create the text view from an AttributedString, which in turn allows you to use Markdown to style runs of text. You can mix string attributes and SwiftUI modifiers, with the string attributes taking priority.
let attributedString = try! AttributedString( markdown: "Hamlet by William Shakespeare")
var body: some View { Text(attributedString) .font(.system(size: 12, weight: .light, design: .serif)) }
A text view always uses exactly the amount of space it needs to display its rendered contents, but you can affect the view’s layout. For example, you can use the frame(width:height:alignment:) modifier to propose specific dimensions to the view. If the view accepts the proposal but the text doesn’t fit into the available space, the view uses a combination of wrapping, tightening, scaling, and truncation to make it fit. With a width of 100 points but no constraint on the height, a text view might wrap a long string:
Text("To be, or not to be, that is the question:") .frame(width: 100)
Use modifiers like lineLimit(_:), allowsTightening(_:), minimumScaleFactor(_:), and truncationMode(_:) to configure how the view handles space constraints. For example, combining a fixed width and a line limit of 1 results in truncation for text that doesn’t fit in that space:
Text("Brevity is the soul of wit.") .frame(width: 100) .lineLimit(1)
Localizing strings
If you initialize a text view with a string literal, the view uses the init(_:tableName:bundle:comment:) initializer, which interprets the string as a localization key and searches for the key in the table you specify, or in the default table if you don’t specify one.
Text("pencil") // Searches the default table in the main bundle.
For an app localized in both English and Spanish, the above view displays “pencil” and “lápiz” for English and Spanish users, respectively. If the view can’t perform localization, it displays the key instead. For example, if the same app lacks Danish localization, the view displays “pencil” for users in that locale. Similarly, an app that lacks any localization information displays “pencil” in any locale.
To explicitly bypass localization for a string literal, use the init(verbatim:) initializer.
Text(verbatim: "pencil") // Displays the string "pencil" in any locale.
If you initialize a text view with a variable value, the view uses the init(_:) initializer, which doesn’t localize the string. However, you can request localization by creating a LocalizedStringKey instance first, which triggers the init(_:tableName:bundle:comment:) initializer instead:
// Don't localize a string variable... Text(writingImplement)
// ...unless you explicitly convert it to a localized string key. Text(LocalizedStringKey(writingImplement))
When localizing a string variable, you can use the default table by omitting the optional initialization parameters — as in the above example — just like you might for a string literal.
When composing a complex string, where there is a need to assemble multiple pieces of text, use string interpolation:
let name: String = //… Text("Hello, (name)")
This would look up the "Hello, %@" localization key in the localized string file and replace the format specifier %@ with the value of name before rendering the text on screen.
Using string interpolation ensures that the text in your app can be localized correctly in all locales, especially in right-to-left languages.
If you desire to style only parts of interpolated text while ensuring that the content can still be localized correctly, interpolate Text or AttributedString:
let name = Text(person.name).bold() Text("Hello, (name)")
The example above uses appendInterpolation(_:) and will look up the "Hello, %@" in the localized string file and interpolate a bold text rendering the value of name.
Using appendInterpolation(_:) you can interpolate Image in text.
Topics
Creating a text view
init(LocalizedStringKey, tableName: String?, bundle: Bundle?, comment: StaticString?)
Creates a text view that displays localized content identified by a key.
init(_:)
Creates a text view that displays styled attributed content.
init(verbatim: String)
Creates a text view that displays a string literal without localization.
init(Date, style: Text.DateStyle)
Creates an instance that displays localized dates and times using a specific style.
init(_:format:)
Creates a text view that displays the formatted representation of a nonstring type supported by a corresponding format style.
init(_:formatter:)
Creates a text view that displays the formatted representation of a Foundation object.
Creates an instance that displays a timer counting within the provided interval.
Choosing a font
Sets the default font for text in the view.
Sets the font weight of the text.
Sets the font design of the text.
Sets the font width of the text.
Styling the view’s text
Sets the style of the text displayed by this view.
Applies a bold or emphasized treatment to the fonts of the text.
Applies a bold font weight to the text.
Applies italics to the text.
Applies a strikethrough to the text.
Applies an underline to the text.
Modifies the font of the text to use the fixed-width variant of the current font, if possible.
Modifies the text view’s font to use fixed-width digits, while leaving other characters proportionally spaced.
Sets the spacing, or kerning, between characters.
Sets the tracking for the text.
Sets the vertical offset for the text relative to its baseline.
enum Case
A scheme for transforming the capitalization of characters within text.
struct DateStyle
A predefined style used to display a Date.
struct LineStyle
Description of the style used to draw the line for StrikethroughStyleAttribute and UnderlineStyleAttribute.
Fitting text into available space
Applies a text scale to the text.
struct Scale
Defines text scales
enum TruncationMode
The type of truncation to apply to a line of text when it’s too long to fit in the available space.
Localizing text
func typesettingLanguage(_:isEnabled:)
Specifies the language for typesetting.
Configuring voiceover
Raises or lowers the pitch of spoken text.
Sets whether VoiceOver should always speak all punctuation in the text view.
Controls whether to queue pending announcements behind existing speech rather than interrupting speech in progress.
Sets whether VoiceOver should speak the contents of the text view character by character.
Providing accessibility information
Sets the accessibility level of this heading.
func accessibilityLabel(_:)
Adds a label to the view that describes its contents.
Sets an accessibility text content type.
Combining text views
Concatenates the text in two text views in a new text view.
Deprecated
Deprecated symbols
Sets the color of the text displayed by this view.
Structures
struct AlignmentStrategy
The way SwiftUI infers the appropriate text alignment if no value is explicitly provided.
Beta
struct Layout
A value describing the layout and custom attributes of a tree of Text views.
struct LayoutKey
A preference key that provides the Text.Layout values for all text views in the queried subtree.
struct WritingDirectionStrategy
The way SwiftUI infers the appropriate writing direction if no value is explicitly provided.
Instance Methods
Adds a custom attribute to the text view.
Controls the way text size variants are chosen.
Relationships
Conforms To
CopyableEquatableSendableSendableMetatypeView
See Also
Displaying text
struct Label
A standard label for user interface items, consisting of an icon with a title.
Sets the style for labels within this view.
https://developer.apple.com/documentation/swiftui/view/opacity(_:)
#app-main)
- SwiftUI
- View
- opacity(_:)
Instance Method
opacity(_:)
Sets the transparency of this view.
nonisolated
Parameters
opacity
A value between 0 (fully transparent) and 1 (fully opaque).
Return Value
A view that sets the transparency of this view.
Discussion
Apply opacity to reveal views that are behind another view or to de-emphasize a view.
When applying the opacity(_:) modifier to a view that has already had its opacity transformed, the modifier multiplies the effect of the underlying opacity transformation.
The example below shows yellow and red rectangles configured to overlap. The top yellow rectangle has its opacity set to 50%, allowing the occluded portion of the bottom rectangle to be visible:
struct Opacity: View { var body: some View { VStack { Color.yellow.frame(width: 100, height: 100, alignment: .center) .zIndex(1) .opacity(0.5)
Color.red.frame(width: 100, height: 100, alignment: .center) .padding(-40) } } }
See Also
Hiding views
Hides this view unconditionally.
https://developer.apple.com/documentation/swiftui/view-layout
https://developer.apple.com/documentation/swiftui/view-accessibility
https://developer.apple.com/documentation/swiftui/view-input-and-events
Collection
- SwiftUI
- View fundamentals
- View
- Input and event modifiers
API Collection
Input and event modifiers
Supply actions for a view to perform in response to user input and system events.
Overview
Use input and event modifiers to configure and provide handlers for a wide variety of user inputs or system events. For example, you can detect and control focus, respond to life cycle events like view appearance and disappearance, manage keyboard shortcuts, and much more.
Topics
Interactivity
Adds a condition that controls whether users can interact with this view.
Sets a tag that you use for tracking interactivity.
List controls
Adds custom swipe actions to a row in a list.
Marks this view as refreshable.
Adds a condition that controls whether users can select this view.
Scroll controls
Associates a binding to a scroll position with a scroll view within this view.
Associates a binding to be updated when a scroll view within this view scrolls.
Associates an anchor to control which part of the scroll view’s content should be rendered by default.
Associates an anchor to control the position of a scroll view in a particular circumstance.
Sets the scroll behavior of views scrollable in the provided axes.
Configures the outermost layout as a scroll target layout.
Applies the given transition, animating between the phases of the transition as this view appears and disappears within the visible region of the containing scroll view.
Adds an action to be performed when a value, created from a scroll geometry, changes.
Adds an action to be called with information about what views would be considered visible.
Adds an action to be called when the view crosses the threshold to be considered on/off screen.
func onScrollPhaseChange(_:)
Adds an action to perform when the scroll phase of the first scroll view in the hierarchy changes.
Geometry
func onGeometryChange(for:of:action:)
Adds an action to be performed when a value, created from a geometry proxy, changes.
Taps and gestures
For more information, see Gestures.
Adds an action to perform when this view recognizes a tap gesture.
func onTapGesture(count:coordinateSpace:perform:)
Adds an action to perform when this view recognizes a tap gesture, and provides the action with the location of the interaction.
Adds an action to perform when this view recognizes a long press gesture.
Adds an action to perform when this view recognizes a remote long touch gesture. A long touch gesture is when the finger is on the remote touch surface without actually pressing.
func gesture(_:)
Attaches an NSGestureRecognizerRepresentable to the view.
Beta
Attaches a gesture to the view with a lower precedence than gestures defined by the view.
Attaches a gesture to the view with a higher precedence than gestures defined by the view.
Attaches a gesture to the view to process simultaneously with gestures defined by the view.
Sets the screen edge from which you want your gesture to take precedence over the system gesture.
Adds an action to perform after the user double-taps their Apple Pencil.
Adds an action to perform when the user squeezes their Apple Pencil.
Configures whether gestures in this view hierarchy can handle events that activate the containing window.
Keyboard input
Performs an action if the user presses a key on a hardware keyboard while the view has focus.
Performs an action if the user presses any key on a hardware keyboard while the view has focus.
Performs an action if the user presses one or more keys on a hardware keyboard while the view has focus.
Performs an action whenever the user presses or releases a hardware modifier key.
Keyboard shortcuts
func keyboardShortcut(_:)
Assigns a keyboard shortcut to the modified control.
Defines a keyboard shortcut and assigns it to the modified control.
Builds a view to use in place of the modified view when the user presses the modifier key(s) indicated by the given set.
Hover
Adds an action to perform when the user moves the pointer over or away from the view’s frame.
func onContinuousHover(coordinateSpace:perform:)
Adds an action to perform when the pointer enters, moves within, and exits the view’s bounds.
Applies a hover effect to this view.
func hoverEffect(_:isEnabled:)
Applies a hover effect to this view, optionally adding it to a HoverEffectGroup.
Applies a hover effect to this view described by the given closure.
Adds an implicit HoverEffectGroup to all effects defined on descendant views, so that all effects added to subviews activate as a group whenever this view or any descendant views are hovered.
Adds a HoverEffectGroup to all effects defined on descendant views, and activates the group whenever this view or any descendant views are hovered.
Adds a condition that controls whether this view can display hover effects.
func defaultHoverEffect(_:)
Sets the default hover effect to use for views within this view.
Requests that the containing list row use the provided hover effect.
Requests that the containing list row have its hover effect disabled.
Pointer
Sets the visibility of the pointer when it’s over the view.
Sets the pointer style to display when the pointer is over the view.
Focus
For more information, see Focus.
Modifies this view by binding its focus state to the given state value.
Modifies this view by binding its focus state to the given Boolean state value.
Sets the focused value for the given object type.
func focusedValue(_:_:)
Modifies this view by injecting a value that you provide for use by other views whose state depends on the focused view hierarchy.
Sets the focused value for the given object type at a scene-wide scope.
func focusedSceneValue(_:_:)
Modifies this view by injecting a value that you provide for use by other views whose state depends on the focused scene.
func focusedObject(_:)
Creates a new view that exposes the provided object to other views whose whose state depends on the focused view hierarchy.
func focusedSceneObject(_:)
Creates a new view that exposes the provided object to other views whose whose state depends on the active scene.
Indicates that the view should receive focus by default for a given namespace.
Creates a focus scope that SwiftUI uses to limit default focus preferences.
Indicates that the view’s frame and cohort of focusable descendants should be used to guide focus movement.
Specifies if the view is focusable.
Specifies if the view is focusable, and if so, what focus-driven interactions it supports.
Adds a condition that controls whether this view can display focus effects, such as a default focus ring or hover effect.
Defines a region of the window in which default focus is evaluated by assigning a value to a given focus state binding.
Modifies this view by binding the focus state of the search field associated with the nearest searchable modifier to the given Boolean value.
Modifies this view by binding the focus state of the search field associated with the nearest searchable modifier to the given value.
Copy and paste
For more information, see Clipboard.
Specifies a list of items to copy in response to the system’s Copy command.
Specifies an action that moves items to the Clipboard in response to the system’s Cut command.
Specifies an action that adds validated items to a view in response to the system’s Paste command.
Adds an action to perform in response to the system’s Copy command.
Adds an action to perform in response to the system’s Cut command.
func onPasteCommand(of:perform:)
Adds an action to perform in response to the system’s Paste command.
func onPasteCommand(of:validator:perform:)
Adds an action to perform in response to the system’s Paste command with items that you validate.
Drag and drop
For more information, see Drag and drop.
Activates this view as the source of a drag and drop operation.
Provides a closure that vends the drag representation to be used for a particular data element.
func onDrop(of:isTargeted:perform:)
Defines the destination of a drag-and-drop operation that handles the dropped content with a closure that you specify.
func onDrop(of:delegate:)
Defines the destination of a drag and drop operation using behavior controlled by the delegate that you provide.
Defines the destination of a drag and drop operation that handles the dropped content with a closure that you specify.
Sets the spring loading behavior this view.
Submission
Adds an action to perform when the user submits a value to this view.
Prevents submission triggers originating from this view to invoke a submission action configured by a submission modifier higher up in the view hierarchy.
Sets the submit label for this view.
Movement
Adds an action to perform in response to a move command, like when the user presses an arrow key on a Mac keyboard, or taps the edge of the Siri Remote when controlling an Apple TV.
Adds a condition for whether the view’s view hierarchy is movable.
Deletion
Adds an action to perform in response to the system’s Delete command, or pressing either the ⌫ (backspace) or ⌦ (forward delete) keys while the view has focus.
Adds a condition for whether the view’s view hierarchy is deletable.
Commands
Steps a value through a range in response to page up or page down commands.
Sets up an action that triggers in response to receiving the exit command while the view has focus.
Adds an action to perform in response to the system’s Play/Pause command.
Adds an action to perform in response to the given selector.
Digital crown
Specifies the visibility of Digital Crown accessory Views on Apple Watch.
Places an accessory View next to the Digital Crown on Apple Watch.
Tracks Digital Crown rotations by updating the specified binding.
func digitalCrownRotation(detent:from:through:by:sensitivity:isContinuous:isHapticFeedbackEnabled:onChange:onIdle:)
Immersive Spaces
For more information, see Immersive spaces.
Performs an action when the immersion state of your app changes.
Volumes
Adds an action to perform when the viewpoint of the volume changes.
Specifies which viewpoints are supported for the window bar and ornaments in a volume.
User activities
Advertises a user activity type.
Registers a handler to invoke in response to a user activity that your app receives.
Specifies the external events that the view’s scene handles if the scene is already open.
View life cycle
Adds an action to perform before this view appears.
Adds an action to perform after this view disappears.
func onChange(of:initial:_:)
Adds a modifier for this view that fires an action when a specific value changes.
Adds an asynchronous task to perform before this view appears.
Adds a task to perform before this view appears or when a specified value changes.
File renaming
func renameAction(_:)
Sets a closure to run for the rename action.
URLs
Registers a handler to invoke in response to a URL that your app receives.
Sets the URL to open in the containing app when the user clicks the widget.
Publisher events
Adds an action to perform when this view detects data emitted by the given publisher.
Hit testing
Configures whether this view participates in hit test operations.
Content shape
Defines the content shape for hit testing.
Sets the content shape for this view.
Import and export
Exports a read-only item provider for consumption by shortcuts, quick actions, and services.
Exports a read-write item provider for consumption by shortcuts, quick actions, and services.
Enables importing item providers from services, such as Continuity Camera on macOS.
Exports items for consumption by shortcuts, quick actions, and services.
Exports read-write items for consumption by shortcuts, quick actions, and services.
Enables importing items from services, such as Continuity Camera on macOS.
App intents
Sets the given style for ShortcutsLinks within the view hierarchy
Sets the given style for SiriTipView within the view hierarchy
Camera
Used to register an action triggered by system capture events.
Used to register actions triggered by system capture events.
Specifies the view that should act as the virtual camera for Apple Vision Pro 2D Persona stream.
See Also
Providing interactivity
Enable people to search for content in your app.
Define additional views for the view to present under specified conditions.
Access storage and provide child views with configuration data.
https://developer.apple.com/documentation/swiftui/view/body-swift.associatedtype
- SwiftUI
- View
- Body
Associated Type
Body
The type of view representing the body of this view.
associatedtype Body : View
Required
Discussion
When you create a custom view, Swift infers this type from your implementation of the required body property.
See Also
Implementing a custom view
var body: Self.Body
The content and behavior of the view.
Required Default implementations provided.
Applies a modifier to a view and returns a new view.
Generate dynamic, interactive previews of your custom views.
https://developer.apple.com/documentation/swiftui/view/modifier(_:)
#app-main)
- SwiftUI
- View
- modifier(_:)
Instance Method
modifier(_:)
Applies a modifier to a view and returns a new view.
nonisolated
Parameters
modifier
The modifier to apply to this view.
Mentioned in
Reducing view modifier maintenance
Discussion
Use this modifier to combine a View and a ViewModifier, to create a new view. For example, if you create a view modifier for a new kind of caption with blue text surrounded by a rounded rectangle:
struct BorderedCaption: ViewModifier {
content .font(.caption2) .padding(10) .overlay( RoundedRectangle(cornerRadius: 15) .stroke(lineWidth: 1) ) .foregroundColor(Color.blue) } }
You can use modifier(_:) to extend View to create new modifier for applying the BorderedCaption defined above:
extension View {
modifier(BorderedCaption()) } }
Then you can apply the bordered caption to any view:
Image(systemName: "bus") .resizable() .frame(width:50, height:50) Text("Downtown Bus") .borderedCaption()
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Bundle view modifiers that you regularly reuse into a custom view modifier.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
https://developer.apple.com/documentation/swiftui/view-appearance
Collection
- SwiftUI
- View fundamentals
- View
- Appearance modifiers
API Collection
Appearance modifiers
Configure a view’s foreground and background styles, controls, and visibility.
Overview
Use these modifiers to configure the appearance of a view, including the use of color and tint, and the application of overlays and background elements. Control the visibility of a view and specific elements within a view. Manage the shape and size of various controls.
For information about configuring views, see View configuration.
Topics
Colors and patterns
Sets the specified style to render backgrounds within the view.
Sets a view’s foreground elements to use a given style.
Sets the primary and secondary levels of the foreground style in the child view.
Sets the primary, secondary, and tertiary levels of the foreground style.
Returns a new view configured with the specified allowed dynamic range.
Tint
func tint(_:)
Sets the tint color within this view.
Sets the tint color associated with a row.
Sets the tint color associated with a section.
func listItemTint(_:)
Sets a fixed tint color for content in a list.
Light and dark appearance
Sets the preferred color scheme for this presentation.
Applies an effect to passthrough video.
Foreground elements
Adds a border to this view with the specified style and width.
Layers the views that you specify in front of this view.
Layers the specified style in front of this view.
Layers a shape that you specify in front of this view.
Background elements
Layers the views that you specify behind this view.
Sets the view’s background to a style.
Sets the view’s background to the default background style.
func background(_:in:fillStyle:)
Sets the view’s background to an insettable shape filled with a style.
func background(in:fillStyle:)
Sets the view’s background to an insettable shape filled with the default background style.
Overrides whether lists and tables in this view have alternating row backgrounds.
Places a custom background view behind a list row item.
Specifies the visibility of the background for scrollable views within this view.
Sets the container background of the enclosing container using a view.
Fills the view’s background with an automatic glass background effect and container-relative rounded rectangle shape.
Fills the view’s background with an automatic glass background effect and a shape that you specify.
Control configuration
Sets the default wheel-style picker item height.
Sets the style for radio group style pickers within this view to be horizontally positioned with the radio buttons inside the layout.
func controlSize(_:)
Sets the size for controls within this view.
Sets the border shape for buttons in this view.
Sets whether buttons in this view should repeatedly trigger their actions on prolonged interactions.
Sets the header prominence for this view.
Disables or enables scrolling in scrollable views.
Configures the bounce behavior of scrollable views along the specified axis.
Flashes the scroll indicators of a scrollable view when it appears.
Flashes the scroll indicators of scrollable views when a value changes.
Sets the preferred order of items for menus presented from this view.
Tells a menu whether to dismiss after performing an action.
Specifies the selection effect to apply to a palette item.
func typeSelectEquivalent(_:)
Sets an explicit type select equivalent text in a collection, such as a list or table.
Symbol effects
Returns a new view with a symbol effect added to it.
Returns a new view with its inherited symbol image effects either removed or left unchanged.
Privacy and redaction
Marks the view as containing sensitive, private user data.
Adds a reason to apply a redaction to this view hierarchy.
Removes any reason to apply a redaction to this view hierarchy.
Mark the receiver as their content might be invalidated.
Visibility
Hides this view unconditionally.
Hides the labels of any controls contained within this view.
Sets the menu indicator visibility for controls within this view.
Sets the display mode for the separator associated with this specific row.
Sets whether to hide the separator associated with a list section.
Sets the preferred visibility of the non-transient system views overlaying the app.
Sets the visibility of scroll indicators within this view.
Sets whether a scroll view clips its content to its bounds.
Controls the visibility of a Table’s column header views.
Sets the preferred visibility of the user’s upper limbs, while an ImmersiveSpace scene is presented.
Sets the visibility of the baseplate of a volume, which appears when a user looks towards the ‘floor’ of a volume and during resize. Both automatic and visible will show the baseplate. hidden will never show it.
Sensory feedback
Plays the specified feedback when the provided trigger value changes.
func sensoryFeedback(trigger:_:)
Plays feedback when returned from the feedback closure after the provided trigger value changes.
Plays the specified feedback when the provided trigger value changes and the condition closure returns true.
Widget configuration
Adds the view and all of its subviews to the accented group.
Displays the widget’s content along a curve if the context allows it.
func widgetLabel(_:)
Returns a localized text label that displays additional content outside the accessory family widget’s main SwiftUI view.
Creates a label for displaying additional content outside an accessory family widget’s main SwiftUI view.
Specifies the vertical placement for a view of an expanded Live Activity that appears in the Dynamic Island.
Window behaviors
Configures the dismiss functionality for the window enclosing self.
Configures the full screen functionality for the window enclosing self.
Configures the minimize functionality for the window enclosing self.
Configures the resize functionality for the window enclosing self.
See Also
Configuring view elements
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Manage the rendering, selection, and entry of text in your view.
Add and configure supporting views, like toolbars and context menus.
Configure charts that you declare with Swift Charts.
https://developer.apple.com/documentation/swiftui/view-text-and-symbols
Collection
- SwiftUI
- View fundamentals
- View
- Text and symbol modifiers
API Collection
Text and symbol modifiers
Manage the rendering, selection, and entry of text in your view.
Overview
SwiftUI provides built-in views that display text to the user, like Text and Label, or that collect text from the user, like TextField and TextEditor. Use text and symbol modifiers to control how SwiftUI displays and manages that text. For example, you can set a font, specify text layout parameters, and indicate what kind of input to expect.
To learn more about the kinds of views that you use to display text and the ways in which you can configure those views, see Text input and output.
Topics
Fonts
Sets the default font for text in this view.
Dynamic type
func dynamicTypeSize(_:)
Sets the Dynamic Type size within the view to the given value.
Text style
Applies a bold font weight to the text in this view.
Sets the font design of the text in this view.
Sets the font weight of the text in this view.
Sets the font width of the text in this view.
Applies italics to the text in this view.
Modifies the fonts of all child views to use the fixed-width variant of the current font, if possible.
Modifies the fonts of all child views to use fixed-width digits, if possible, while leaving other characters proportionally spaced.
Applies a strikethrough to the text in this view.
Sets a transform for the case of the text contained in this view when displayed.
Applies a text scale to text in the view.
Applies an underline to the text in this view.
Text layout
Sets whether text in this view can compress the space between characters when necessary to fit text in a line.
Sets the vertical offset for the text relative to its baseline in this view.
Sets whether this view mirrors its contents horizontally when the layout direction is right-to-left.
Sets the spacing, or kerning, between characters for the text in this view.
Sets the minimum amount that text in this view scales down to fit in the available space.
Sets the tracking for the text in this view.
Sets the truncation mode for lines of text that are too long to fit in the available space.
func typesettingLanguage(_:isEnabled:)
Specifies the language for typesetting.
Multiline text
func lineLimit(_:)
Sets to a closed range the number of lines that text can occupy in this view.
Sets a limit for the number of lines text can occupy in this view.
Sets the amount of space between lines of text in this view.
Sets the alignment of a text view that contains multiple lines of text.
Text selection
Controls whether people can select text within this view.
Text entry
Sets whether to disable autocorrection for this view.
Sets the keyboard type for this view.
Configures the behavior in which scrollable content interacts with the software keyboard.
Sets how often the shift key in the keyboard is automatically enabled.
Associates a fully formed string with the value of this view when used as a text input suggestion
Configures the text input suggestions for this view.
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on a watchOS device.
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on macOS.
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on an iOS or tvOS device.
Find and replace
Programmatically presents the find and replace interface for text editor views.
Prevents find and replace operations in a text editor.
Prevents replace operations in a text editor.
Symbol appearance
Sets the rendering mode for symbol images within this view.
Makes symbols within the view show a particular variant.
See Also
Configuring view elements
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Configure a view’s foreground and background styles, controls, and visibility.
Add and configure supporting views, like toolbars and context menus.
Configure charts that you declare with Swift Charts.
https://developer.apple.com/documentation/swiftui/view-auxiliary-views
Collection
- SwiftUI
- View fundamentals
- View
- Auxiliary view modifiers
API Collection
Auxiliary view modifiers
Add and configure supporting views, like toolbars and context menus.
Overview
Use these modifiers to manage supplemental views that present context-specific controls and information. For example, you can add titles and buttons to navigation bars, manage the status bar, create context menus, and add badges many different kinds of views.
Topics
Navigation titles
Configure your apps navigation titles
Use a navigation title to display the current navigation state of an interface.
func navigationTitle(_:)
Configures the view’s title for purposes of navigation, using a string binding.
func navigationSubtitle(_:)
Configures the view’s subtitle for purposes of navigation.
Navigation title configuration
func navigationDocument(_:)
Configures the view’s document for purposes of navigation.
func navigationDocument(_:preview:)
Navigation bars
Hides the navigation bar back button for the view.
Configures the title display mode for this view.
Navigation stacks and columns
Associates a destination view with a presented data type for use within a navigation stack.
Associates a destination view with a binding that can be used to push the view onto a NavigationStack.
func navigationDestination<D, C>(item: Binding<Optional<D>>, destination: (D) -> C) -> some View
Associates a destination view with a bound value for use within a navigation stack or navigation split view
Sets a fixed, preferred width for the column containing this view.
Sets a flexible, preferred width for the column containing this view.
Tab views
Specifies the customizations to apply to the sidebar representation of the tab view.
Specifies the default placement for the tabs in a tab view using the adaptable sidebar style.
Adds a custom header to the sidebar of a tab view.
Adds a custom footer to the sidebar of a tab view.
Adds a custom bottom bar to the sidebar of a tab view.
Adds custom actions to a section.
Toolbars
For information about toolbars, see Toolbars.
func toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
Populates the toolbar or navigation bar with the specified items, allowing for user customization.
Specifies the visibility of a bar managed by SwiftUI.
Remove a toolbar item present by default
func toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
Specifies the preferred visibility of backgrounds on a bar managed by SwiftUI.
Specifies the preferred foreground style of bars managed by SwiftUI.
Specifies the preferred color scheme of a bar managed by SwiftUI.
Configures the semantic role for the content populating the toolbar.
Configure the title menu of a toolbar.
Configures the toolbar title display mode for this view.
func ornament(visibility:attachmentAnchor:contentAlignment:ornament:)
Presents an ornament.
Context menus
For information about menus in your app, see Menus and commands.
Adds a context menu to a view.
Adds a context menu with a custom preview to a view.
Adds an item-based context menu to a view.
Badges
func badge(_:)
Generates a badge for the view from an integer value.
Specifies the prominence of badges created by this view.
Help text
func help(_:)
Adds help text to a view using a text view that you provide.
Status bar
Sets the visibility of the status bar.
Touch Bar
Sets the content that the Touch Bar displays.
Sets the Touch Bar content to be shown in the Touch Bar when applicable.
Sets principal views that have special significance to this Touch Bar.
Sets a user-visible string that identifies the view’s functionality.
Sets the behavior of the user-customized view.
See Also
Configuring view elements
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Configure a view’s foreground and background styles, controls, and visibility.
Manage the rendering, selection, and entry of text in your view.
Configure charts that you declare with Swift Charts.
https://developer.apple.com/documentation/swiftui/view-chart-view
Collection
- SwiftUI
- View fundamentals
- View
- Chart view modifiers
API Collection
Chart view modifiers
Configure charts that you declare with Swift Charts.
Overview
Use these modifiers to configure a Chart view that you add to your SwiftUI app.
Topics
Styles
Adds a background to a view that contains a chart.
Configures the foreground style scale for charts.
Configures the plot area of charts.
Legends
Configures the legend for charts.
Overlays
Adds an overlay to a view that contains a chart.
Axes
Sets the visibility of the x axis.
Configures the x-axis for charts in the view.
Configures the x axis content of charts.
Sets the visibility of the y axis.
Configures the y-axis for charts in the view.
Configures the y axis content of charts.
Axis Labels
func chartXAxisLabel(_:position:alignment:spacing:)
Adds x axis label for charts in the view.
func chartYAxisLabel(_:position:alignment:spacing:)
Adds y axis label for charts in the view.
Axis scales
Configures the x scale for charts.
Configures the y scale for charts.
Symbol scales
func chartSymbolScale(_:)
Configures the symbol scale for charts.
Configures the symbol style scale for charts.
func chartSymbolScale(domain:range:)
func chartSymbolScale(range:)
Symbol size scales
Configures the symbol size scale for charts.
Line style scales
Configures the line style scale for charts.
Scrolling
Sets the initial scroll position along the x-axis. Once the user scrolls the scroll view, the value provided to this modifier will have no effect.
Sets the initial scroll position along the y-axis. Once the user scrolls the scroll view, the value provided to this modifier will have no effect.
Associates a binding to be updated when the chart scrolls along the x-axis.
Associates a binding to be updated when the chart scrolls along the y-axis.
Sets the scroll behavior of the scrollable chart.
Configures the scrollable behavior of charts in this view.
Visible domain
Sets the length of the visible domain in the X dimension.
Sets the length of the visible domain in the Y dimension.
See Also
Configuring view elements
Make your SwiftUI apps accessible to everyone, including people with disabilities.
Configure a view’s foreground and background styles, controls, and visibility.
Manage the rendering, selection, and entry of text in your view.
Add and configure supporting views, like toolbars and context menus.
https://developer.apple.com/documentation/swiftui/view-style-modifiers
Collection
- SwiftUI
- View fundamentals
- View
- Style modifiers
API Collection
Style modifiers
Apply built-in styles to different types of views.
Overview
SwiftUI defines built-in styles for certain kinds of views, and chooses the appropriate style for a particular presentation context. For example, a Label might appear as an icon, a string title, or both, depending on factors like the platform, whether the view appears in a toolbar, and so on.
You can override the automatic style by using one of the style modifiers. These modifiers typically propagate through container views, so you can wrap an entire view hierarchy in a style modifier to affect all the views of the given type within the hierarchy. Some view types enable you to create custom styles, which you also apply using style modifiers.
For more information about styling views, see View styles.
Topics
Controls
func buttonStyle(_:)
Sets the style for buttons within this view to a button style with a custom appearance and standard interaction behavior.
Sets the style for date pickers within this view.
Sets the style for menus within this view.
Sets the style for pickers within this view.
Sets the style for toggles in a view hierarchy.
Indicators
Sets the style for gauges within this view.
Sets the style for progress views in this view.
Text
Sets the style for labels within this view.
Sets the style for text fields within this view.
Sets the style for text editors within this view.
Collections
Sets the style for lists within this view.
Sets the style for tables within this view.
Sets the style for disclosure groups within this view.
Presentation
Sets the style for navigation split views within this view.
Sets the style for the tab view within the current environment.
Sets the style for windows created by interacting with this view.
Sets the style for the toolbar in windows created by interacting with this view.
Groups
Sets the style for control groups within this view.
Sets the style for group boxes within this view.
Sets the style for the index view within the current environment.
See Also
Drawing views
Tell a view how to arrange itself within a view hierarchy by adjusting its size, position, alignment, padding, and so on.
Affect the way the system draws a view, for example by scaling or masking a view, or by applying graphical effects.
https://developer.apple.com/documentation/swiftui/view-graphics-and-rendering
Collection
- SwiftUI
- View fundamentals
- View
- Graphics and rendering modifiers
API Collection
Graphics and rendering modifiers
Affect the way the system draws a view, for example by scaling or masking a view, or by applying graphical effects.
Overview
Use these view modifiers to apply many of the rendering effects typically associated with a graphics context, like adding masks and creating composites. You can apply these effects to graphical views, like Shapes, as well as any other SwiftUI view.
When you do need the flexibility of immediate mode drawing in a graphics context, use a Canvas view instead. This can be particularly helpful when you want to draw an extremely large number of dynamic shapes — for example, to create particle effects.
For more information about using these effects in your app, see Drawing and graphics.
Topics
Masks and clipping
Masks this view using the alpha channel of the given view.
Clips this view to its bounding rectangular frame.
Sets a clipping shape for this view.
Sets the container shape to use for any container relative shape within this view.
Scale
Scales this view to fill its parent.
Scales this view to fit its parent.
func scaleEffect(_:anchor:)
Scales this view’s rendered output by the given amount in both the horizontal and vertical directions, relative to an anchor point.
Scales this view’s rendered output by the given horizontal and vertical amounts, relative to an anchor point.
Scales this view by the specified horizontal, vertical, and depth factors, relative to an anchor point.
Scales images within the view according to one of the relative sizes available including small, medium, and large images sizes.
func aspectRatio(_:contentMode:)
Constrains this view’s dimensions to the specified aspect ratio.
Rotation and transformation
Rotates a view’s rendered output in two dimensions around the specified point.
Rotates the view’s content by the specified 3D rotation value.
Renders a view’s content as if it’s rotated in three dimensions around the specified axis.
func rotation3DEffect(_:axis:anchor:)
Rotates the view’s content by an angle about an axis that you specify as a tuple of elements.
Applies a projection transformation to this view’s rendered output.
Applies an affine transformation to this view’s rendered output.
Applies a 3D transformation to this view’s rendered output.
Graphical effects
Applies a Gaussian blur to this view.
Sets the transparency of this view.
Brightens this view by the specified amount.
Sets the contrast and separation between similar colors in this view.
Inverts the colors in this view.
Adds a color multiplication effect to this view.
Adjusts the color saturation of this view.
Adds a grayscale effect to this view.
Applies a hue rotation effect to this view.
Adds a luminance to alpha effect to this view.
Adds a shadow to this view.
Applies effects to this view, while providing access to layout information through a geometry proxy.
Applies effects to this view, while providing access to layout information through a 3D geometry proxy.
Shaders
Returns a new view that applies shader to self as a filter effect on the color of each pixel.
Returns a new view that applies shader to self as a geometric distortion effect on the location of each pixel.
Returns a new view that applies shader to self as a filter on the raster layer created from self.
Composites
Sets the blend mode for compositing this view with overlapping views.
Wraps this view in a compositing group.
Composites this view’s contents into an offscreen image before final display.
Animations
func animation(_:)
Applies the given animation to this view when this view changes.
Applies the given animation to this view when the specified value changes.
Applies the given animation to all animatable values within the body closure.
Loops the given keyframes continuously, updating the view using the modifiers you apply in body.
Plays the given keyframes when the given trigger value changes, updating the view using the modifiers you apply in body.
Animates effects that you apply to a view over a sequence of phases that change continuously.
Animates effects that you apply to a view over a sequence of phases that change based on a trigger.
Modifies the view to use a given transition as its method of animating changes to the contents of its views.
func transition(_:)
Associates a transition with the view.
Applies the given transaction mutation function to all animations used within the view.
Applies the given transaction mutation function to all animations used within the body closure.
Defines a group of views with synchronized geometry using an identifier and namespace that you provide.
Isolates the geometry (e.g. position and size) of the view from its parent view.
See Also
Drawing views
Apply built-in styles to different types of views.
Tell a view how to arrange itself within a view hierarchy by adjusting its size, position, alignment, padding, and so on.
https://developer.apple.com/documentation/swiftui/view-search
https://developer.apple.com/documentation/swiftui/view-presentation
Collection
- SwiftUI
- View fundamentals
- View
- Presentation modifiers
API Collection
Presentation modifiers
Define additional views for the view to present under specified conditions.
Overview
Use presentation modifiers to show different kinds of modal presentations, like alerts, popovers, sheets, and confirmation dialogs.
Because SwiftUI is a declarative framework, you don’t call a method at the moment you want to present the modal. Rather, you define how the presentation looks and the condition under which SwiftUI should present it. SwiftUI detects when the condition changes and makes the presentation for you. Because you provide a Binding to the condition that initiates the presentation, SwiftUI can reset the underlying value when the user dismisses the presentation.
For more information about how to use these modifiers, see Modal presentations.
Topics
Alerts
func alert(_:isPresented:actions:)
Presents an alert when a given condition is true, using a text view for the title.
func alert(_:isPresented:presenting:actions:)
Presents an alert using the given data to produce the alert’s content and a text view as a title.
Presents an alert when an error is present.
Alerts with a message
func alert(_:isPresented:actions:message:)
Presents an alert with a message when a given condition is true using a text view as a title.
func alert(_:isPresented:presenting:actions:message:)
Presents an alert with a message using the given data to produce the alert’s content and a text view for a title.
Presents an alert with a message when an error is present.
Confirmation dialogs
func confirmationDialog(_:isPresented:titleVisibility:actions:)
Presents a confirmation dialog when a given condition is true, using a text view for the title.
func confirmationDialog(_:isPresented:titleVisibility:presenting:actions:)
Presents a confirmation dialog using data to produce the dialog’s content and a text view for the title.
func dismissalConfirmationDialog(_:shouldPresent:actions:)
Presents a confirmation dialog when a dismiss action has been triggered.
Confirmation dialogs with a message
func confirmationDialog(_:isPresented:titleVisibility:actions:message:)
Presents a confirmation dialog with a message when a given condition is true, using a text view for the title.
func confirmationDialog(_:isPresented:titleVisibility:presenting:actions:message:)
Presents a confirmation dialog with a message using data to produce the dialog’s content and a text view for the message.
func dismissalConfirmationDialog(_:shouldPresent:actions:message:)
Dialog configuration
Configures the icon used by dialogs within this view.
Enables user suppression of dialogs and alerts presented within self, with a default suppression message on macOS. Unused on other platforms.
func dialogSuppressionToggle(_:isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a custom suppression message on macOS. Unused on other platforms.
Sheets
Presents a sheet when a binding to a Boolean value that you provide is true.
Presents a sheet using the given item as a data source for the sheet’s content.
Presents a modal view that covers as much of the screen as possible when binding to a Boolean value you provide is true.
Presents a modal view that covers as much of the screen as possible using the binding you provide as a data source for the sheet’s content.
Popovers
Presents a popover using the given item as a data source for the popover’s content.
Presents a popover when a given condition is true.
Sheet and popover configuration
Conditionally prevents interactive dismissal of presentations like popovers, sheets, and inspectors.
Sets the available detents for the enclosing sheet.
Sets the available detents for the enclosing sheet, giving you programmatic control of the currently selected detent.
Sets the visibility of the drag indicator on top of a sheet.
Sets the presentation background of the enclosing sheet using a shape style.
Sets the presentation background of the enclosing sheet to a custom view.
Controls whether people can interact with the view behind a presentation.
Specifies how to adapt a presentation to horizontally and vertically compact size classes.
Specifies how to adapt a presentation to compact size classes.
Configures the behavior of swipe gestures on a presentation.
Requests that the presentation have a specific corner radius.
Sets the sizing of the containing presentation.
File exporter
func fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)
Presents a system interface for exporting a document that’s stored in a value type, like a structure, to a file on disk.
func fileExporter(isPresented:documents:contentType:onCompletion:)
Presents a system interface for exporting a collection of value type documents to files on disk.
func fileExporter(isPresented:document:contentTypes:defaultFilename:onCompletion:onCancellation:)
Presents a system interface for allowing the user to export a FileDocument to a file on disk.
func fileExporter(isPresented:documents:contentTypes:onCompletion:onCancellation:)
Presents a system dialog for allowing the user to export a collection of documents that conform to FileDocument to files on disk.
Presents a system interface allowing the user to export a Transferable item to file on disk.
Presents a system interface allowing the user to export a collection of items to files on disk.
func fileExporterFilenameLabel(_:)
On macOS, configures the fileExporter with a label for the file name field.
File importer
Presents a system interface for allowing the user to import multiple files.
Presents a system interface for allowing the user to import an existing file.
Presents a system dialog for allowing the user to import multiple files.
File mover
Presents a system interface for allowing the user to move an existing file to a new location.
Presents a system interface for allowing the user to move a collection of existing files to a new location.
Presents a system dialog for allowing the user to move an existing file to a new location.
Presents a system dialog for allowing the user to move a collection of existing files to a new location.
File dialog configuration
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
func fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
func fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
Inspectors
Inserts an inspector at the applied position in the view hierarchy.
Sets a fixed, preferred width for the inspector containing this view when presented as a trailing column.
Sets a flexible, preferred width for the inspector in a trailing-column presentation.
Quick look previews
Presents a Quick Look preview of the contents of a single URL.
Presents a Quick Look preview of the URLs you provide.
Family Sharing
Presents an activity picker view as a sheet.
Live Activities
The text color for the auxiliary action button that the system shows next to a Live Activity on the Lock Screen.
Sets the tint color for the background of a Live Activity that appears on the Lock Screen.
Apple Music
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
StoreKit
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
PhotoKit
Presents a Photos picker that selects a PhotosPickerItem.
Presents a Photos picker that selects a PhotosPickerItem from a given photo library.
Presents a Photos picker that selects a collection of PhotosPickerItem.
Presents a Photos picker that selects a collection of PhotosPickerItem from a given photo library.
Sets the accessory visibility of the Photos picker. Accessories include anything between the content and the edge, like the navigation bar or the sidebar.
Disables capabilities of the Photos picker.
Sets the mode of the Photos picker.
See Also
Providing interactivity
Supply actions for a view to perform in response to user input and system events.
Enable people to search for content in your app.
Access storage and provide child views with configuration data.
https://developer.apple.com/documentation/swiftui/view-state
Collection
- SwiftUI
- View fundamentals
- View
- State modifiers
API Collection
State modifiers
Access storage and provide child views with configuration data.
Overview
SwiftUI provides tools for managing data in your app. For example, you can store values and objects in an environment that’s shared among the views in a view hierarchy. Any view that shares the environment — typically all the descendant views of the view that stores the item — can then access the stored item.
For more information about the types that SwiftUI provides to help manage data in your app, see Model data.
Topics
Identity
Sets the unique tag value of this view.
Binds a view’s identity to the given proxy value.
Prevents the view from updating its child view when its new value is the same as its old value.
Environment values
Places an observable object in the view’s environment.
Sets the environment value of the specified key path to the given value.
Supplies an observable object to a view’s hierarchy.
Transforms the environment value of the specified key path with the given function.
Preferences
Sets a value for the given preference.
Applies a transformation to a preference value.
Sets a value for the specified preference key, the value is a function of a geometry value tied to the current coordinate space, allowing readers of the value to convert the geometry to their local coordinates.
Sets a value for the specified preference key, the value is a function of the key’s current value and a geometry value tied to the current coordinate space, allowing readers of the value to convert the geometry to their local coordinates.
Adds an action to perform when the specified preference key’s value changes.
Reads the specified preference value from the view, using it to produce a second view that is applied as the background of the original view.
Reads the specified preference value from the view, using it to produce a second view that is applied as an overlay to the original view.
Default storage
The default store used by AppStorage contained within the view.
Configuring a model
Sets the model context in this view’s environment.
Sets the model container and associated model context in this view’s environment.
func modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)
Sets the model container in this view for storing the provided model type, creating a new container if necessary, and also sets a model context for that container in this view’s environment.
See Also
Providing interactivity
Supply actions for a view to perform in response to user input and system events.
Enable people to search for content in your app.
Define additional views for the view to present under specified conditions.
https://developer.apple.com/documentation/swiftui/view-deprecated
Collection
- SwiftUI
- View fundamentals
- View
- Deprecated modifiers
API Collection
Deprecated modifiers
Review unsupported modifiers and their replacements.
Overview
Avoid using deprecated modifiers in your app. Select a modifier to see the replacement that you should use instead.
Topics
Accessibility modifiers
Adds a label to the view that describes its contents.
Deprecated
Adds a textual description of the value that the view contains.
Specifies whether to hide this view from system accessibility features.
Uses the specified string to identify the view.
Sets a selection identifier for this view’s accessibility element.
Communicates to the user what happens after performing the view’s action.
func accessibility(activationPoint:)
Specifies the point where activations occur in the view.
Sets alternate input labels with which users identify a view.
Adds the given traits to the view.
Removes the given traits from this view.
Sets the sort priority order for this view’s accessibility element, relative to other elements at the same level.
Appearance modifiers
Sets this view’s color scheme.
Sets the color that the system applies to the row background when this view is placed in a list.
Layers the given view behind this view.
Layers a secondary view in front of this view.
Sets the color of the foreground elements displayed by this view.
Promotes this view to the foreground in a complication.
Text modifiers
Sets whether to apply auto-capitalization to this view.
Sets whether to disable autocorrection for this view.
Auxiliary view modifiers
func navigationBarTitle(_:)
Sets the title in the navigation bar for this view.
func navigationBarTitle(_:displayMode:)
Sets the title and display mode in the navigation bar for this view.
Sets the navigation bar items for this view.
Configures the navigation bar items for this view.
Hides the navigation bar for this view.
Sets the visibility of the status bar.
Adds a context menu to the view.
Style modifiers
Sets the style for menu buttons within this view.
Sets the style for navigation views within this view.
Layout modifiers
Positions this view within an invisible frame.
Changes the view’s proposed area to extend outside the screen’s safe areas.
Assigns a name to the view’s coordinate space, so other code can operate on dimensions like points and sizes relative to the named space.
Graphics and rendering modifiers
Sets the accent color for this view and the views it contains.
Masks this view using the alpha channel of the given view.
Applies the given animation to all animatable values within this view.
Clips this view to its bounding frame, with the specified corner radius.
Input and events modifiers
Adds an action to perform when the given value changes.
Adds an action to perform when this view recognizes a tap gesture, and provides the action with the location of the interaction.
Adds an action to perform when this view recognizes a long press gesture.
Adds an action to perform in response to the system’s Paste command.
Adds an action to perform in response to the system’s Paste command with items that you validate.
Defines the destination for a drag and drop operation with the same size and position as this view, with behavior controlled by the given delegate.
func onDrop(of:isTargeted:perform:)
Defines the destination of a drag-and-drop operation that handles the dropped content with a closure that you specify.
Specifies if the view is focusable and, if so, adds an action to perform when the view comes into focus.
Adds an action to perform when the pointer enters, moves within, and exits the view’s bounds.
View presentation modifiers
Presents an action sheet when a given condition is true.
Presents an action sheet using the given item as a data source for the sheet’s content.
Presents an alert to the user.
Search modifiers
func searchable(text:placement:prompt:suggestions:)
Marks this view as searchable, which configures the display of a search field.
Tab modifiers
Sets the tab bar item associated with this view.
https://developer.apple.com/documentation/swiftui/view/accessibilityactions(category:_:)
#app-main)
- SwiftUI
- View
- accessibilityActions(category:_:)
Instance Method
accessibilityActions(category:_:)
Adds multiple accessibility actions to the view with a specific category. Actions allow assistive technologies, such as VoiceOver, to interact with the view by invoking the action and are grouped by their category. When multiple action modifiers with an equal category are applied to the view, the actions are combined together.
nonisolated
category: AccessibilityActionCategory,
Parameters
category
The category the accessibility actions are grouped by.
content
The accessibility actions added to the view.
Discussion
Var body: some View { EditorView() .accessibilityActions(category: .edit) { ForEach(editActions) { action in Button(action.title) { action() } } if hasTextSuggestions { Button(“Show Text Suggestions”) { presentTextSuggestions() } } } }
See Also
Adding actions to views
Adds an accessibility action to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action.
Adds multiple accessibility actions to the view.
func accessibilityAction(named:_:)
Adds an accessibility action labeled by the contents of label to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action. When the action is performed, the intent will be invoked.
Adds an accessibility action representing actionKind to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action. When the action is performed, the intent will be invoked.
func accessibilityAction(named:intent:)
Adds an accessibility action labeled name to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action. When the action is performed, the intent will be invoked.
Adds an accessibility adjustable action to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action.
Adds an accessibility scroll action to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action.
struct AccessibilityActionKind
The structure that defines the kinds of available accessibility actions.
enum AccessibilityAdjustmentDirection
A directional indicator you use when making an accessibility adjustment.
struct AccessibilityActionCategory
Designates an accessibility action category that is provided and named by the system.
https://developer.apple.com/documentation/swiftui/view/accessibilitydefaultfocus(::)
#app-main)
- SwiftUI
- View
- accessibilityDefaultFocus(_:_:) Beta
Instance Method
accessibilityDefaultFocus(_:_:)
Defines a region in which default accessibility focus is evaluated by assigning a value to a given accessibility focus state binding.
nonisolated
_ value: Value
Parameters
binding
An accessibility focus state binding to update when evaluating default accessibility focus.
value
The value to set the binding to during evaluation.
Discussion
Accessibility default focus is evaluated when a scene appears and an accessibility technology like VoiceOver focuses on its content, when an accessibility focus state binding update moves focus automatically, and when the layout of a scene changes and the accessibility technology must refocus on new content.
In the following example, an accessibility technology, like VoiceOver, automatically lands on the title of the playlist as the most important view to initially have focus on, rather than navigating through all controls to understand what the primary content of the view is.
var body: some View { VStack { PlayerControls(currentSong: $currentSong) Text(playlist.title) .font(.title) .accessibilityFocused($focusedField, equals: .title) PlaylistEntries(entries: playlist.entries) } .accessibilityDefaultFocus($focusedField, .title) }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/accessibilityscrollstatus(_:isenabled:)
#app-main)
- SwiftUI
- View
- accessibilityScrollStatus(_:isEnabled:) Beta
Instance Method
accessibilityScrollStatus(_:isEnabled:)
Changes the announcement provided by accessibility technologies when a user scrolls a scroll view within this view.
nonisolated func accessibilityScrollStatus( _ status: LocalizedStringResource, isEnabled: Bool = true
Show all declarations
Parameters
status
The current status of the scroll view.
isEnabled
If true the accessibility scroll status is applied; otherwise the accessibility scroll status is unchanged.
Discussion
Use this modifier to provide a description of the content at the current position in the scroll view. For example, you could use this modifier to announce the current month being scrolled to in a view that contains a calendar.
ScrollView { LazyVStack { ForEach(months) { months in MonthView(month: months) } } .scrollTargetLayout() } .scrollPosition($position) .accessibilityScrollStatus(”(months.name(position.viewID)) (year)”)
By default, VoiceOver announces “Page X of Y” while scrolling.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/accessorywidgetgroupstyle(_:)
#app-main)
- SwiftUI
- View
- accessoryWidgetGroupStyle(_:)
Instance Method
accessoryWidgetGroupStyle(_:)
The view modifier that can be applied to AccessoryWidgetGroup to specify the shape the three content views will be masked with. The value of style is set to .automatic, which is .circular by default.
@MainActor @preconcurrency
Parameters
style
The shape with which the content views are masked. The available shapes are circle and rounded square.
https://developer.apple.com/documentation/swiftui/view/addordertowalletbuttonstyle(_:)
https://developer.apple.com/documentation/swiftui/view/addpasstowalletbuttonstyle(_:)
#app-main)
- SwiftUI
- View
- addPassToWalletButtonStyle(_:)
Instance Method
addPassToWalletButtonStyle(_:)
Sets the style to be used by the button. (see PKAddPassButtonStyle).
PassKitSwiftUI
nonisolated
See Also
Accessing Apple Pay and Wallet
A view that displays a button for identity verification.
Sets the button’s style.
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
Sets the action on the PayLaterView. See PKPayLaterAction.
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Sets the style to be used by the button. (see PKIdentityButtonStyle).
Provides a task to perform before this view appears
https://developer.apple.com/documentation/swiftui/view/allowswindowactivationevents()
#app-main)
- SwiftUI
- View
- allowsWindowActivationEvents()
Instance Method
allowsWindowActivationEvents()
Configures gestures in this view hierarchy to handle events that activate the containing window.
nonisolated
Discussion
Views higher in the hierarchy can override the value you set on this view. In the following example, the tap gesture on the Rectangle won’t handle events that activate the containing window because the outer allowsWindowActivationEvents(_:) view modifier overrides the inner one:
HStack { Rectangle() .onTapGesture { ... } .allowsWindowActivationEvents() } .allowsWindowActivationEvents(false)
https://developer.apple.com/documentation/swiftui/view/appstoreoffer(ispresented:kind:ondismiss:)
#app-main)
- SwiftUI
- View
- appStoreOffer(isPresented:kind:onDismiss:) Beta
Instance Method
appStoreOffer(isPresented:kind:onDismiss:)
StoreKitSwiftUI
nonisolated func appStoreOffer(
kind: AppStoreOfferKind,
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/aspectratio3d(_:contentmode:)
#app-main)
- SwiftUI
- View
- aspectRatio3D(_:contentMode:) Beta
Instance Method
aspectRatio3D(_:contentMode:)
Constrains this view’s dimensions to the specified 3D aspect ratio.
nonisolated func aspectRatio3D( _ aspectRatio: Size3D? = nil, contentMode: ContentMode
Parameters
aspectRatio
The ratio of width to height to depth to use for the resulting view. If aspectRatio is nil, the resulting view maintains this view’s aspect ratio.
contentMode
A flag indicating whether this view should fit or fill the parent context.
Return Value
A view that constrains this view’s dimensions to aspectRatio, using contentMode as its scaling algorithm.
Discussion
If this view is resizable, the resulting view will have aspectRatio as its aspect ratio. In this example, the Model3D has a 2 : 3 : 1 width to height to depth ratio, and scales to fit its frame:
Model3D(named: "Sphere") { resolved in let ratio3D = Size3D(width: 2, height: 3, depth: 1) resolved .resizable() .aspectRatio3D(ratio3D, contentMode: .fit) } placeholder: { ProgressView() } .frame(width: 200, height: 200) .frame(depth: 200) .border(Color(white: 0.75))
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/assistiveaccessnavigationicon(_:)
#app-main)
- SwiftUI
- View
- assistiveAccessNavigationIcon(_:) Beta
Instance Method
assistiveAccessNavigationIcon(_:)
Configures the view’s icon for purposes of navigation.
nonisolated
Parameters
icon
The icon image to display.
Discussion
In an Assistive Access scene on iOS and iPadOS, the icon is displayed adjacent to the navigation title. Otherwise, the icon is unused.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/assistiveaccessnavigationicon(systemimage:)
#app-main)
- SwiftUI
- View
- assistiveAccessNavigationIcon(systemImage:) Beta
Instance Method
assistiveAccessNavigationIcon(systemImage:)
Configures the view’s icon for purposes of navigation.
nonisolated
Parameters
systemImage
The system symbol to display.
Discussion
In an Assistive Access scene on iOS and iPadOS, the icon is displayed adjacent to the navigation title. Otherwise, the icon is unused.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/attributedtextformattingdefinition(_:)
#app-main)
- SwiftUI
- View
- attributedTextFormattingDefinition(_:) Beta
Instance Method
attributedTextFormattingDefinition(_:)
Apply a text formatting definition to all nested editor views.
@MainActor @preconcurrency
Show all declarations
Discussion
Applying a text formatting definition to a view makes sure that any content observable to the user adheres to the constraints of the formatting definition.
You can compose your own definition from an attribute scope and a series of AttributedTextValueConstraint s:
// MyTextFormattingDefinition.swift
struct MyTextFormattingDefinition: AttributedTextFormattingDefinition { var body: some AttributedTextFormattingDefinition<
ValueConstraint( for: .underlineStyle, values: [nil, .single], default: .single) MyAttributedTextValueConstraint() } }
// MyEditorView.swift
TextEditor(text: $text) .attributedTextFormattingDefinition(MyTextFormattingDefinition())
To manually enforce constraints, e.g. before serializing text contents, use the AttributedTextValueConstraint/constrain(_:)-6cp64 method.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/automateddeviceenrollmentaddition(ispresented:)
#app-main)
- SwiftUI
- View
- automatedDeviceEnrollmentAddition(isPresented:)
Instance Method
automatedDeviceEnrollmentAddition(isPresented:)
Presents a modal view that enables users to add devices to their organization.
@MainActor @preconcurrency
Parameters
isPresented
A binding to a Boolean value that determines whether to present the view.
Return Value
The modal view that the system presents to the user.
Discussion
Use this view modifier to present UI in your app for device administrators to add devices purchased outside of the official channel to their organization — Apple School Manager, Apple Business Manager, or Apple Business Essentials. The system requires sign in with a Managed Apple Account that includes device enrollment privileges.
The following code example shows one way to present this view to your users:
Example Usage:
import SwiftUI import AutomatedDeviceEnrollment
struct ContentView: View { @State private var isAddingDevices: Bool = false
var body: some View { Button("Add Devices to Automated Device Enrollment") { isAddingDevices = true } .automatedDeviceEnrollmentAddition(isPresented: $isAddingDevices) .onChange(of: isAddingDevices) { if !isAddingDevices { // Handle dismiss action } } } }
See Also
Working with managed devices
Applies a managed content style to the view.
https://developer.apple.com/documentation/swiftui/view/breakthrougheffect(_:)
#app-main)
- SwiftUI
- View
- breakthroughEffect(_:) Beta
Instance Method
breakthroughEffect(_:)
Ensures that the view is always visible to the user, even when other content is occluding it, like 3D models.
nonisolated
Parameters
effect
The type of effect to apply when the view is occluded by other content.
Discussion
Breakthrough is an effect allowing elements to be visible to the user even when other app content (3D models, UI elements) is positioned in front. The way the element breaks through content in front depends on the chosen BreakthroughEffect.
This modifier can be used in a number of scenarios, including ornaments and RealityView attachments to have them break through in their entirety.
Regular Elements
To have SwiftUI element break through content in front, apply the breakthroughEffect modifier directly to the View:
ResizeHandle() .breakthroughEffect(.subtle)
Ornaments
When applied to the whole content of an ornament, the ornament (including its background) will break through content in front:
Text("A view with an ornament") .ornament(attachmentAnchor: .scene(.bottom)) { OrnamentContent() .glassBackgroundEffect() .breakthroughEffect(.prominent) }
RealityView Attachments
Similarly, a RealityView Attachment can break through other entities in the RealityView, including the entity it is attached to:
Attachment(id: "example") { AttachmentContent() .breakthroughEffect(.subtle) }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/buttonsizing(_:)
#app-main)
- SwiftUI
- View
- buttonSizing(_:) Beta
Instance Method
buttonSizing(_:)
nonisolated
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/certificatesheet(trust:title:message:help:)
#app-main)
- SwiftUI
- View
- certificateSheet(trust:title:message:help:)
Instance Method
certificateSheet(trust:title:message:help:)
Displays a certificate sheet using the provided certificate trust.
@MainActor @preconcurrency func certificateSheet(
title: String? = nil, message: String? = nil, help: URL? = nil
Parameters
trust
title
The title to display. Uses a default title if nil.
message
The message to display. Uses a default message if nil.
help
URL for the “Learn More” button. Uses a default URL if nil.
https://developer.apple.com/documentation/swiftui/view/chart3dcameraprojection(_:)
https://developer.apple.com/documentation/swiftui/view/chart3dpose(_:)
https://developer.apple.com/documentation/swiftui/view/chart3drenderingstyle(_:)
#app-main)
- SwiftUI
- View
- chart3DRenderingStyle(_:) Beta
Instance Method
chart3DRenderingStyle(_:)
@MainActor @preconcurrency
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/chartzaxis(_:)
https://developer.apple.com/documentation/swiftui/view/chartzaxis(content:)
#app-main)
- SwiftUI
- View
- chartZAxis(content:) Beta
Instance Method
chartZAxis(content:)
Configures the z-axis for 3D charts in the view.
nonisolated
Parameters
content
The axis content.
Discussion
Use this modifier to customize the z-axis of a chart. Provide an AxisMarks builder that composes AxisGridLine, AxisTick, and AxisValueLabel structures to form the axis. Omit components from the builder to omit them from the resulting axis. For example, the following code adds grid lines to the z-axis:
.chartZAxis { AxisMarks { AxisGridLine() } }
Use arguments such as position: or values: to control the placement of the axis values it displays.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/chartzaxislabel(_:position:alignment:spacing:)
https://developer.apple.com/documentation/swiftui/view/chartzscale(domain:range:type:)
https://developer.apple.com/documentation/swiftui/view/chartzscale(domain:type:)
#app-main)
- SwiftUI
- View
- chartZScale(domain:type:) Beta
Instance Method
chartZScale(domain:type:)
nonisolated
domain: Domain, type: ScaleType? = nil
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/chartzscale(range:type:)
https://developer.apple.com/documentation/swiftui/view/chartzselection(range:)
#app-main)
- SwiftUI
- View
- chartZSelection(range:) Beta
Instance Method
chartZSelection(range:)
nonisolated
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/chartzselection(value:)
#app-main)
- SwiftUI
- View
- chartZSelection(value:) Beta
Instance Method
chartZSelection(value:)
nonisolated
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/contactaccessbuttoncaption(_:)
#app-main)
- SwiftUI
- View
- contactAccessButtonCaption(_:)
Instance Method
contactAccessButtonCaption(_:)
@MainActor @preconcurrency
See Also
Managing contact access
Modally present UI which allows the user to select which contacts your app has access to.
https://developer.apple.com/documentation/swiftui/view/contactaccessbuttonstyle(_:)
https://developer.apple.com/documentation/swiftui/view/containervalue(::)
https://developer.apple.com/documentation/swiftui/view/contentcaptureprotected(_:)
https://developer.apple.com/documentation/swiftui/view/contenttoolbar(for:content:)
#app-main)
- SwiftUI
- View
- contentToolbar(for:content:)
Instance Method
contentToolbar(for:content:)
Populates the toolbar of the specified content view type with the views you provide.
nonisolated
for placement: ContentToolbarPlacement,
Show all declarations
Parameters
content
The views representing the content of the toolbar.
Discussion
Use this modifier to add toolbar content that remains consistent regardless of the content view. Use a toolbar modifier within the content view if the toolbar content is dependent the content view is showing.
Unlike the toolbar modifier, which configures the toolbar of the modified view’s container, the contentToolbar modifier configures the toolbar within the modified view’s content instead. This means that the contentToolbar modifier should generally be applied directly to a container view, instead of to the content within a container view. For example, to configure the toolbar of tab view’s sidebar, apply the contentToolbar modifier to the TabView itself, not to any of the tabs within the TabView.
The content toolbar modifier expects a collection of toolbar items that you can provide by either supplying a collection of views with each view wrapped in a ToolbarItem, or by providing a collection of views as a ToolbarItemGroup. The example below adds an account summary to the bottom of the tab view sidebar and a button to the tab view sidebar overflow menu.
TabView { Tab("Home", systemImage: "house") { HomeView() }
Tab("Alerts", systemImage: "bell") { AlertsView() }
TabSection("Categories") { Tab("Climate", systemImage: "fan") { ClimateView() }
Tab("Lights", systemImage: "lightbulb") { LightsView() } } } .tabViewStyle(.sidebarAdaptable) .contentToolbar(for: .tabViewSidebar) { ToolbarItem(placement: .automatic) { DisconnectDevicesButton() } ToolbarItem(placement: .bottomBar) { AccountSummaryView() } }
https://developer.apple.com/documentation/swiftui/view/continuitydevicepicker(ispresented:ondidconnect:)
https://developer.apple.com/documentation/swiftui/view/controlwidgetactionhint(_:)
#app-main)
- SwiftUI
- View
- controlWidgetActionHint(_:)
Instance Method
controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
@MainActor @preconcurrency
Show all declarations
Parameters
hint
The localized string resource to display.
Discussion
This text will appear next to the Action Button to describe what your control will do when activated. By default, a control’s action hint is derived from its display name, the type of control, and value text, if any:
// Action Hint: “Hold for ‘Ping My Watch’” struct PingMyWatchButton: Control { static let displayName: LocalizedStringResource = “Ping My Watch” … }
// When this button’s action conforms to OpenIntent: // Action Hint: “Hold to Open Notes” struct NotesLauncher: Control { static let displayName: LocalizedStringResource = “Notes” … }
// Action Hint: “Hold to Turn On ‘Silent Mode’” / “Hold to Turn Off ‘Silent Mode’” struct SilentModeToggle: Control { static let displayName: LocalizedStringResource = “Silent Mode” … }
// Action Hint: “Hold for Silent” / “Hold for Ring” ControlWidgetToggle(…) { isOn in Label( isOn ? “Silent” : “Ring”, systemImage: isOn ? “bell.slash” : “bell” ) }
When the default action hint is insufficiently descriptive, you can customize the hint by applying this modifier to the control’s label. For instance, we can describe what the user will use our NotesLauncher control to do, “Compose a Note”, instead of the default “Hold to Open Notes” hint, like this:
ControlWidgetButton(…) { Image(systemName: “note.text”) .controlWidgetActionHint(“Compose a Note”) }
See Also
Composing control widgets
protocol ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
protocol ControlWidgetConfiguration
A type that describes a control widget’s content.
struct EmptyControlWidgetConfiguration
An empty control widget configuration.
struct ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
protocol ControlWidgetTemplate
struct EmptyControlWidgetTemplate
An empty control widget template.
struct ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/controlwidgetstatus(_:)
#app-main)
- SwiftUI
- View
- controlWidgetStatus(_:)
Instance Method
controlWidgetStatus(_:)
The status of the control described by the modified label.
@MainActor @preconcurrency
Show all declarations
Parameters
status
The localized string resource to display.
Discussion
This text will appear in Control Center when your control’s state changes. You can customize the text by applying this modifier to the control’s value label:
// Status Text: "Do Not Disturb Until This Evening" / "Do Not Disturb Disabled" ControlWidgetToggle("Do Not Disturb", ...) { isOn in Image(systemName: "moon") .controlWidgetStatus(isOn ? "Do Not Disturb Until This Evening" : "Do Not Disturb Disabled") }
See Also
Composing control widgets
protocol ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
protocol ControlWidgetConfiguration
A type that describes a control widget’s content.
struct EmptyControlWidgetConfiguration
An empty control widget configuration.
struct ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
protocol ControlWidgetTemplate
struct EmptyControlWidgetTemplate
An empty control widget template.
struct ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/currententitlementtask(for:priority:action:)
#app-main)
- SwiftUI
- View
- currentEntitlementTask(for:priority:action:)
Instance Method
currentEntitlementTask(for:priority:action:)
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
StoreKitSwiftUI
nonisolated func currentEntitlementTask( for productID: String, priority: TaskPriority = .medium,
Parameters
productID
The product ID to get the entitlement for. The task restarts whenever this parameter changes.
priority
The task priority to use when creating the task.
action
The action to perform when the task’s state changes.
Discussion
Before a view modified with this method appears, a task will start in the background to get the current entitlement. While the view is presented, the task will call action whenever the entitlement changes or the task’s state changes.
Consumable in-app purchases will always pass nil to action. For auto-renewable subscriptions, use subscriptionStatusTask(for:priority:action:) to get the full status information for the subscription.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
Declares the view as dependent on a collection of In-App Purchase products and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/dialogpreventsapptermination(_:)
https://developer.apple.com/documentation/swiftui/view/dragconfiguration(_:)
https://developer.apple.com/documentation/swiftui/view/dragcontainer(for:id:in:_:)
#app-main)
- SwiftUI
- View
- dragContainer(for:id:in:_:) Beta
Instance Method
dragContainer(for:id:in:_:)
A container with draggable views. The drag payload is based on the current selection.
nonisolated
for itemType: Item.Type = Item.self,
in namespace: Namespace.ID? = nil,
Parameters
itemType
A type of the dragged item.
id
A closure that provides the item’s identifier.
namespace
An optional namespace that identifies the drag container.
payload
A closure which is called when a drag operation begins. As an argument, the closure receives the identifier of the dragged view under the finger or cursor. Using the passed identifier, put together the payload to drag, and return from the closure. Return an empty Collection to disable the drag.
Return Value
A view that can be activated as the source of a drag and drop operation, beginning with user gesture input.
Discussion
Below is an example of a container view with three sections. Each section is draggable. Also, each section is selectable, and each view in a section is selectable as well. When a section drag starts, the app wants to use its custom logic to decide what the payload should be. If an unselected section is dragged, it should be the only one on the drag payload. If a selected section is dragged, the payload should contain other selected sections, and also the sections that have at least one fruit selected.
var berries: [Fruit] var citruses: [Fruit] var tropical: [Fruit]
@State var selectedSections: [UUID] @State var selectedFruits: [UUID]
var body: some View { ScrollView { VStack { BerriesSectionView(FruitSection(berries)) .draggable(containerItemID: FruitSection.berries) CitrusSectionView(FruitSection(citruses)) .draggable(containerItemID: FruitSection.citruses) TropicalSectionView(FruitSection(tropical)) .draggable(containerItemID: FruitSection.tropical) } } .dragContainer { draggedSectionID in let identifiers = sectionIDsToDrag(for: draggedSectionID) return sections(identifiers: identifiers) } }
// an unselected section is dragged if !selectedSections.contains(draggedID) { return [draggedID] }
// a selected section is dragged let payloadIDs = selectedSections + sectionIdentifiersOfSelectedFruits() return uniqueSections(from: payloadIDs) }
struct Fruit { let id: UUID }
struct FruitSection: Transferable { static let berries: UUID static let citruses: UUID static let tropical: UUID
let id: UUID var fruits: [Fruit] }
struct BerriesSectionView: View { var section: FruitSection
var body: some View { HStack { ForEach(section.fruit) { berry in BerryView(berry) } } } }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/dragcontainer(for:id:in:selection:_:)
#app-main)
- SwiftUI
- View
- dragContainer(for:id:in:selection:_:) Beta
Instance Method
dragContainer(for:id:in:selection:_:)
A container with single item selection and draggable views. The drag payload is based on the current selection and provided identifiers.
nonisolated
for itemType: Item.Type = Item.self,
in namespace: Namespace.ID? = nil,
Show all declarations
Parameters
itemType
A type of the dragged item.
id
A closure that returns the identifier of a given dragged item.
namespace
An optional namespace that identifies the drag container.
selection
A closure returning the item that is currently selected. Return nil to indicate that the selection is empty.
payload
A closure that returns the item with a given identifier. Return nil to disable drag.
Return Value
A view that can be activated as the source of a drag and drop operation, beginning with user gesture input.
Discussion
In an example below, an app presents a view with Fruit values. Fruit uses the name as its identifier.
@State private var fruits: [Fruit] @State private var selection: Fruit.ID?
var body: some View { VStack { ForEach(fruits) { fruit in FruitView(fruit) .draggable(containerItemID: fruit.name) } } .dragContainer(selection: selection, id: .name) { draggedID in fruit(id: id) } }
struct Fruit: Transferable { var name: String ... }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/dragcontainer(for:in:_:)
https://developer.apple.com/documentation/swiftui/view/dragcontainer(for:in:selection:_:)
#app-main)
- SwiftUI
- View
- dragContainer(for:in:selection:_:) Beta
Instance Method
dragContainer(for:in:selection:_:)
A container with multiple selection and draggable views. The drag payload is identifiable and is based on the current selection.
nonisolated
for itemType: Item.Type = Item.self, in namespace: Namespace.ID? = nil,
Show all declarations
Parameters
itemType
A type of the dragged items.
namespace
An optional namespace that identifies the drag container.
selection
Identifiers of the currently selected items.
payload
A closure which is called when a drag operation begins. As an argument, the closure receives either the identifiers of all the selected items, if the dragged item is a part of selection, or only the identifier of the dragged item, if it is not part of the selection. With the passed identifiers, put together the payload to drag, and return from the closure. The number of returned items can be different from the number of dragged identifiers. Only the views that correspond to returned item identifiers will be dragged. Return an empty Collection to disable the drag.
Return Value
A view that can be activated as the source of a drag and drop operation, beginning with user gesture input.
Discussion
In an example below, an app presents a view with Fruit values. When a user starts drag, SwiftUI uses the selection to put together the list of item identifiers to drag.
var fruits: [Fruit] @State var selection: [Fruit.ID]
var body: some View { VStack { ForEach(fruits) { fruit in FruitView(fruit) .draggable(containerItemID: fruit.id) } } .dragContainer(selection: selection) { ids in fruits(ids: ids) } }
/// Returns the Fruit values with given identifiers.
struct Fruit: Transferable, Identifiable { ... }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/dragpreviewsformation(_:)
#app-main)
- SwiftUI
- View
- dragPreviewsFormation(_:) Beta
Instance Method
dragPreviewsFormation(_:)
Describes the way dragged previews are visually composed.
nonisolated
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/draggable(::)
https://developer.apple.com/documentation/swiftui/view/draggable(containeritemid:)
https://developer.apple.com/documentation/swiftui/view/draggable(for🆔_:)
https://developer.apple.com/documentation/swiftui/view/dropconfiguration(_:)
https://developer.apple.com/documentation/swiftui/view/droppreviewsformation(_:)
https://developer.apple.com/documentation/swiftui/view/formstyle(_:)
https://developer.apple.com/documentation/swiftui/view/gamesynceddirectoryloadingview(directory:finishedloading:)
https://developer.apple.com/documentation/swiftui/view/glassbackgroundeffect(_:displaymode:)
https://developer.apple.com/documentation/swiftui/view/glassbackgroundeffect(_:in:displaymode:)
https://developer.apple.com/documentation/swiftui/view/glasseffecttransition(_:isenabled:)
https://developer.apple.com/documentation/swiftui/view/glasseffectunion(id:namespace:)
https://developer.apple.com/documentation/swiftui/view/groupactivityassociation(_:)
#app-main)
- SwiftUI
- View
- groupActivityAssociation(_:) Beta
Instance Method
groupActivityAssociation(_:)
Specifies how a view should be associated with the current SharePlay group activity.
GroupActivitiesSwiftUI
nonisolated
Parameters
kind
If given, the kind of group activity association.
You can dynamically remove the group activity's association with a view by
setting the given kind to nil instead of .primary(_:).
Discussion
When a group of people join a SharePlay activity with their spatial Personas, the system selects a common, primary scene to arrange their spatial Personas around. This association between the group activity and a primary scene in your app creates a shared space for the spatial Personas to interact in; enabling participants to gesture at the associated scene and understand each other. For more information about spatial Personas and SharePlay on visionOS, see doc:adding-spatial-persona-support-to-an-activity.
By default, the system uses your scene’s activation conditions in concert with your activity’s SceneAssociationBehavior to select a scene to associate with the activity. You can specify a different scene or dynamically change the associated scene by using this modifier to set a view’s group activity association to GroupActivityAssociationKind/primary.
struct MyApp: App { var body: some Scene { ... Window("Game Window") { GameView() .groupActivityAssociation(.primary("game-window")) } } }
If there are multiple scenes that are simultaneously configured with the primary group activity association, the most recently associated scene will be used. For example, if your app defines two windows and both contain views with the primary association kind, the most recently opened one will be used as the primary scene. If that second window is subsequently closed, the original window will be used again.
You can dynamically remove the group activity’s association with a view by setting the given kind to nil instead of .primary.
@State var activityState: ActivityState
var body: some Scene { WindowGroup { TeamSelectionView() .groupActivityAssociation(activityState == .teamSelection ? .primary("team-selection") : nil) }
WindowGroup { CardGameVolume() .groupActivityAssociation(activityState == .inGame ? .primary("in-game") : nil) } .windowStyle(.volumetric) }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/handgestureshortcut(_:isenabled:)
#app-main)
- SwiftUI
- View
- handGestureShortcut(_:isEnabled:)
Instance Method
handGestureShortcut(_:isEnabled:)
Assigns a hand gesture shortcut to the modified control.
nonisolated func handGestureShortcut( _ shortcut: HandGestureShortcut, isEnabled: Bool = true
Parameters
shortcut
The shortcut to associate with this control.
isEnabled
A Boolean value that indicates whether the shortcut is is enabled for this control.
Discussion
Performing the control’s shortcut while the control is anywhere in the frontmost scene is equivalent to direct interaction with the control to perform its primary action.
The following example lets users of a watchOS music app toggle playback by double-tapping their thumb and index finger together:
struct PlaybackControls: View { let model: TrackModel
var body: some View { HStack { Button("Skip Back") { model.skipBack() }
Button("Play/Pause") { model.playPause() } .handGestureShortcut(.primaryAction)
Button("Skip Forward") { model.skipForward() } } } }
The target of a hand gesture shortcut is resolved in a leading-to-trailing traversal of the active scene.
See Also
Defining custom gestures
Attaches a gesture to the view with a higher precedence than gestures defined by the view.
Sets the screen edge from which you want your gesture to take precedence over the system gesture.
protocol Gesture
An instance that matches a sequence of events to a gesture, and returns a stream of values for each of its states.
struct AnyGesture
A type-erased gesture.
struct HandActivationBehavior
An activation behavior specific to hand-driven input.
struct HandGestureShortcut
Hand gesture shortcuts describe finger and wrist movements that the user can perform in order to activate a button or toggle.
https://developer.apple.com/documentation/swiftui/view/handpointerbehavior(_:)
#app-main)
- SwiftUI
- View
- handPointerBehavior(_:)
Instance Method
handPointerBehavior(_:)
Sets the behavior of the hand pointer while the user is interacting with the view.
nonisolated
Parameters
behavior
The behavior to apply to the hand pointer. If nil, the hand pointer behavior will be inherited from the view’s ancestors.
Return Value
A view that applies the given behavior to the hand pointer.
See Also
Changing view appearance for hover events
Applies a hover effect to this view.
struct HoverEffect
An effect applied when the pointer hovers over a view.
Applies a hover effect to this view, optionally adding it to a HoverEffectGroup.
Applies a hover effect to this view described by the given closure.
protocol CustomHoverEffect
A type that represents how a view should change when a pointer hovers over a view, or when someone looks at the view.
struct ContentHoverEffect
A CustomHoverEffect that applies effects to a view on hover using a closure.
Beta
struct HoverEffectGroup
Describes a grouping of effects that activate together.
Adds an implicit HoverEffectGroup to all effects defined on descendant views, so that all effects added to subviews activate as a group whenever this view or any descendant views are hovered.
Adds a HoverEffectGroup to all effects defined on descendant views, and activates the group whenever this view or any descendant views are hovered.
struct GroupHoverEffect
A CustomHoverEffect that activates a named group of effects.
protocol HoverEffectContent
A type that describes the effects of a view for a particular hover effect phase.
struct EmptyHoverEffectContent
An empty base effect that you use to build other effects.
struct HandPointerBehavior
A behavior that can be applied to the hand pointer while the user is interacting with a view.
https://developer.apple.com/documentation/swiftui/view/handlesgamecontrollerevents(matching:)
#app-main)
- SwiftUI
- View
- handlesGameControllerEvents(matching:)
Instance Method
handlesGameControllerEvents(matching:)
Specifies the game controllers events which should be delivered through the GameController framework when the view, or one of its descendants has focus.
GameControllerSwiftUI
nonisolated
Discussion
SpriteView(scene: MyGameScene()) .handlesGameControllerEvents(matching: .gamepad) .focused(true)
https://developer.apple.com/documentation/swiftui/view/handlesgamecontrollerevents(matching:withoptions:)
#app-main)
- SwiftUI
- View
- handlesGameControllerEvents(matching:withOptions:) Beta
Instance Method
handlesGameControllerEvents(matching:withOptions:)
Specifies the game controllers events which should be delivered through the GameController framework when the view or one of its descendants has focus.
GameControllerSwiftUI
nonisolated func handlesGameControllerEvents( matching types: GCUIEventTypes, withOptions options: GameControllerEventHandlingOptions?
Discussion
SpriteView(scene: MyGameScene()) .handlesGameControllerEvents(matching: .gamepad, withOptions: .defaultOptions) .focused(true)
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/healthdataaccessrequest(store:objecttype:predicate:trigger:completion:)
#app-main)
- SwiftUI
- View
- healthDataAccessRequest(store:objectType:predicate:trigger:completion:)
Instance Method
healthDataAccessRequest(store:objectType:predicate:trigger:completion:)
Asynchronously requests permission to read a data type that requires per-object authorization (such as vision prescriptions).
@preconcurrency nonisolated func healthDataAccessRequest( store: HKHealthStore, objectType: HKObjectType, predicate: NSPredicate? = nil, trigger: some Equatable,
Parameters
store
The HealthKit store where you’re requesting authorization.
objectType
The data type you want to read. This type must be a type that requires per-object authorization.
predicate
An optional predicate that further restricts the objects of interest.
trigger
A value used to trigger the request. This value must be a State variable. Any change to the variable triggers a request.
completion
A block that the system calls after the request is complete. The system passes the result parameter.
Discussion
Some samples require per-object authorization. For these samples, people can select which ones your app can read on a sample-by-sample basis. By default, your app can read any of the per-object authorization samples that it has saved to the HealthKit store; however, you may not always have access to those samples. People can update the authorization status for any of these samples at any time.
Your app can begin by setting up the request in SwiftUI.
@State private var trigger = false let store = HKHealthStore()
var body: some Scene { WindowGroup { ContentView(enabled: $authenticated) .healthDataAccessRequest(store: store, objectType: .visionPrescriptionType(), predicate: nil, trigger: trigger) { result in
switch result { case .success(_): authenticated = true case .failure(let error): // Handle the error here. fatalError("*** An error occurred while requesting authentication: (error) ***") }
logger.debug("Authentication Complete.") } } }
Next, query for any samples that it already has permission to read.
// Read the newest prescription from the HealthKit store. let queryDescriptor = HKSampleQueryDescriptor(predicates: [.visionPrescription()], sortDescriptors: [SortDescriptor(.startDate, order: .reverse)], limit: 1)
let prescription: HKVisionPrescription
do { guard let result = try await queryDescriptor.result(for: store).first else { print("*** No prescription found. ***") return }
prescription = result } catch { // Handle the error here. fatalError("*** An error occurred while reading the most recent vision prescriptions: (error.localizedDescription) ***") }
Based on the results, you can then decide whether you need to request authorization for additional samples. Modify the trigger’s value to prompt someone to modify the samples your app has access to read.
// Request authorization for additional samples. trigger.toggle()
When your app calls this method, HealthKit displays an authorization sheet that asks for permission to read the samples that match the predicate and object type. The person using your app can then select individual samples to share with your app. The system always asks for permission, regardless of whether the user previously granted it.
People can individually enable each of the prescriptions. After they respond, the system calls the callback handler on an arbitrary background queue.
See Also
Accessing health data
Requests permission to read the specified HealthKit data types.
Requests permission to save and read the specified HealthKit data types.
Presents a preview of the workout contents as a modal sheet
https://developer.apple.com/documentation/swiftui/view/healthdataaccessrequest(store:readtypes:trigger:completion:)
#app-main)
- SwiftUI
- View
- healthDataAccessRequest(store:readTypes:trigger:completion:)
Instance Method
healthDataAccessRequest(store:readTypes:trigger:completion:)
Requests permission to read the specified HealthKit data types.
@preconcurrency nonisolated func healthDataAccessRequest( store: HKHealthStore,
trigger: some Equatable,
Parameters
store
The HealthKit store where you’re requesting authorization.
readTypes
An optional set containing the data types you want to read. This set can contain any concrete subclass of the HKObjectType class (any of the HKCharacteristicType, HKQuantityType, HKCategoryType, HKWorkoutType, or HKCorrelationType classes ). If the user grants permission, your app can read these data types from the HealthKit store.
trigger
A value used to trigger the request. This value must be a State variable. Any change to the variable triggers a request.
completion
A block that the system calls after the request is complete. The system passes the result parameter.
Discussion
HealthKit performs this request asynchronously when you modify the trigger’s value. If you call this method with a new data type (a type of data that the user hasn’t previously granted or denied permission for in this app), the system automatically displays the authorization sheet when you modify the trigger’s value. The authorization sheet lists all the requested permissions. After the user finishes responding, HealthKit calls the completion block on a background queue. If the user has already chosen to grant or prohibit access to all of the types specified, HealthKit calls the completion when you modify the trigger without prompting the user.
@State private var trigger = false
var body: some Scene { WindowGroup { ContentView(enabled: $authenticated) .healthDataAccessRequest(store: store, readTypes: healthDataTypes, trigger: trigger) { result in switch result {
case .success(_): authenticated = true case .failure(let error): // Handle the error here. fatalError("*** An error occurred while requesting authentication: (error) ***") }
logger.debug("Authentication Complete.") } .onAppear() { trigger.toggle() } } }
import SwiftUI import HealthKit import HealthKitUI import os
let healthDataTypes: Set = [
HKQuantityType.workoutType(),
HKQuantityType(.heartRate),
HKQuantityType(.activeEnergyBurned),
HKQuantityType(.basalEnergyBurned),
HKQuantityType(.distanceWalkingRunning),
HKQuantityType(.stepCount)
]
private let logger = Logger(subsystem: "example.com.MyWorkoutApp", category: "iOS App")
@main struct MyApp: App {
@State private var authenticated = false @State private var trigger = false
let store = HKHealthStore()
logger.debug("Authentication Complete.") } .onAppear() { trigger.toggle() } } } }
Customize the messages displayed on the permissions sheet by setting the following key:
NSHealthShareUsageDescriptioncustomizes the message for reading data.
Set the key in the Target Properties list on the app’s Info tab.
After users set the permissions for your app, they can always change them using either the Settings or the Health app. Your app appears in the Health app’s Sources tab, even if the user didn’t allow permission to read data.
See Also
Accessing health data
Asynchronously requests permission to read a data type that requires per-object authorization (such as vision prescriptions).
Requests permission to save and read the specified HealthKit data types.
Presents a preview of the workout contents as a modal sheet
https://developer.apple.com/documentation/swiftui/view/healthdataaccessrequest(store:sharetypes:readtypes:trigger:completion:)
#app-main)
- SwiftUI
- View
- healthDataAccessRequest(store:shareTypes:readTypes:trigger:completion:)
Instance Method
healthDataAccessRequest(store:shareTypes:readTypes:trigger:completion:)
Requests permission to save and read the specified HealthKit data types.
@preconcurrency nonisolated func healthDataAccessRequest( store: HKHealthStore,
trigger: some Equatable,
Parameters
store
The HealthKit store where you’re requesting authorization.
shareTypes
A set containing the data types you want to share. This set can contain any concrete subclass of the HKSampleType class (any of the HKQuantityType, HKCategoryType, HKWorkoutType, or HKCorrelationType classes). If the user grants permission, your app can create and save these data types to the HealthKit store.
readTypes
An optional set containing the data types you want to read. This set can contain any concrete subclass of the HKObjectType class (any of the HKCharacteristicType, HKQuantityType, HKCategoryType, HKWorkoutType, or HKCorrelationType classes ). If the user grants permission, your app can read these data types from the HealthKit store.
trigger
A value used to trigger the request. This value must be a State variable. Any change to the variable triggers a request.
completion
A block that the system calls after the request is complete. The system passes the result parameter.
Discussion
HealthKit performs these requests asynchronously when you modify the trigger’s value. If you call this method with a new data type (a type of data that the user hasn’t previously granted or denied permission for in this app), the system automatically displays the authorization sheet when you modify the trigger’s value. The authorization sheet lists all the requested permissions. After the user finishes responding, HealthKit calls the completion block on a background queue. If the user has already chosen to grant or prohibit access to all of the types specified, HealthKit calls the completion when you modify the trigger without prompting the user.
Each data type has two separate permissions, one to read it and one to share it. You can make a single request, and include all the data types your app needs.
@State private var trigger = false
var body: some Scene { WindowGroup { ContentView(enabled: $authenticated) .healthDataAccessRequest(store: store, shareTypes: healthDataTypes, readTypes: healthDataTypes, trigger: trigger) { result in switch result {
case .success(_): authenticated = true case .failure(let error): // Handle the error here. fatalError("*** An error occurred while requesting authentication: (error) ***") }
logger.debug("Authentication Complete.") } .onAppear() { trigger.toggle() } } }
import SwiftUI import HealthKit import HealthKitUI import os
let healthDataTypes: Set = [
HKQuantityType.workoutType(),
HKQuantityType(.heartRate),
HKQuantityType(.activeEnergyBurned),
HKQuantityType(.basalEnergyBurned),
HKQuantityType(.distanceWalkingRunning),
HKQuantityType(.stepCount)
]
private let logger = Logger(subsystem: "example.com.MyWorkoutApp", category: "iOS App")
@main struct MyApp: App {
@State private var authenticated = false @State private var trigger = false
let store = HKHealthStore()
logger.debug("Authentication Complete.") } .onAppear() { trigger.toggle() } } } }
Customize the messages displayed on the permissions sheet by setting the following keys:
-
NSHealthShareUsageDescriptioncustomizes the message for reading data. -
NSHealthUpdateUsageDescriptioncustomizes the message for writing data.
Set these keys in the Target Properties list on the app’s Info tab.
After users set the permissions for your app, they can always change them using either the Settings or the Health app. Your app appears in the Health app’s Sources tab, even if the user didn’t allow permission to read or share data.
See Also
Accessing health data
Asynchronously requests permission to read a data type that requires per-object authorization (such as vision prescriptions).
Requests permission to read the specified HealthKit data types.
Presents a preview of the workout contents as a modal sheet
https://developer.apple.com/documentation/swiftui/view/imageplaygroundpersonalizationpolicy(_:)
#app-main)
- SwiftUI
- View
- imagePlaygroundPersonalizationPolicy(_:)
Instance Method
imagePlaygroundPersonalizationPolicy(_:)
Policy determining whether to support the usage of people in the playground or not.
nonisolated
Parameters
policy
Policy determining whether personalization is enabled or not.
Return Value
An image playground sheet that does or does not support personalization, based on the enabled flag.
Discussion
Enabling people support will allow the user to condition image generation using:
-
A person from their system Photos library
-
A character represented by an appearance and a skin tone
Personalization options are available through several user interfaces, including:
-
A people picker
-
Detection of people names in the prompt text field
-
Importing images containing people faces from the system photo library
Enabled by default when the modifier is not set or when the policy is set to automatic.
https://developer.apple.com/documentation/swiftui/view/imageplaygroundsheet(ispresented:concept:sourceimage:oncompletion:oncancellation:)
#app-main)
- SwiftUI
- View
- imagePlaygroundSheet(isPresented:concept:sourceImage:onCompletion:onCancellation:)
Instance Method
imagePlaygroundSheet(isPresented:concept:sourceImage:onCompletion:onCancellation:)
Presents the system sheet to create images from the specified input.
@MainActor @preconcurrency func imagePlaygroundSheet(
concept: String, sourceImage: Image? = nil,
Parameters
isPresented
A binding to a Boolean value that determines whether to display the sheet.
concept
An initial natural language string that describes the expected contents of the image. The person viewing the creation UI can edit the concepts from inside that UI. concept: str is equivalent to concepts: [.text(str)].
sourceImage
Specify an existing image to use as source input for creating the new image. The person viewing the sheet can override the image you provide, and choose different images and concepts inside the creation UI. If you don’t provide a starting image, the system creates the new image using only the contents of the concepts parameter.
onCompletion
The block to receive the created image. The block has no return value and receives the following parameter:
url
A URL with the path to the image. The system saves the file at a temporary location inside your app container. Move the file to a new location if you intend to keep it after the dismissal of the sheet, or remove it if you don’t.
onCancellation
The block to handle the cancellation of the image-creation process, when the user chooses to exit the creation UI without choosing any image. After executing this block, the system automatically dismisses the sheet.
Discussion
Add this modifier to a view to display the system’s image-creation sheet. When the variable in the isPresented parameter is true, the view presents the sheet. Present the sheet in situations where someone might want to generate a new image for their content. When configuring the sheet, specify an optional starting image and text description to use to create the initial image.
While visible, the sheet allows people to experiment with the contents of an image before returning it to your app. The person viewing the sheet can accept the image they created or cancel the operation. When they make their choice, the system executes the appropriate block.
You can use this modifier only if the device supports creating new images. Check the ImagePlayground/SwiftUICore/EnvironmentValues/supportsImagePlayground environment variable to determine the availability of the feature. The following code creates a button to display the sheet only when the feature is available:
@State private var showSheet = false @State private var createdImageURL: URL? = nil @Environment(.supportsImagePlayground) private var supportsImagePlayground // ....
if supportsImagePlayground { Button("Show Generation Sheet") { showSheet = true }.imagePlaygroundSheet( isPresented: $showSheet, concept: "Dog on a surfboard", sourceImage: sourceImage) { url in createdImageURL = url } }
https://developer.apple.com/documentation/swiftui/view/imageplaygroundsheet(ispresented:concept:sourceimageurl:oncompletion:oncancellation:)
https://developer.apple.com/documentation/swiftui/view/inapppurchaseoptions(_:)
#app-main)
- SwiftUI
- View
- inAppPurchaseOptions(_:)
Instance Method
inAppPurchaseOptions(_:)
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
StoreKitSwiftUI
nonisolated
Parameters
options
The system calls this function before processing a purchase, with the product to be purchased is provided as a parameter. Return a set of purchase options to add to the purchase.
Discussion
In-app stores within this view will add any default purchase options to the set you return, and use the result for configuring the purchase. If you just want to react to in-app purchases beginning without adding purchase options, you can add an action with onInAppPurchaseStart(perform:).
You can remove any options ancestor views may have added by providing nil for the action. This will result in using the default set of purchase options.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
Declares the view as dependent on a collection of In-App Purchase products and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/journalingsuggestionspicker(ispresented:journalingsuggestiontoken:oncompletion:)
https://developer.apple.com/documentation/swiftui/view/journalingsuggestionspicker(ispresented:oncompletion:)
#app-main)
- SwiftUI
- View
- journalingSuggestionsPicker(isPresented:onCompletion:)
Instance Method
journalingSuggestionsPicker(isPresented:onCompletion:)
Presents a visual picker interface that contains events and images that a person can select to retrieve more information.
@MainActor @preconcurrency func journalingSuggestionsPicker(
Parameters
isPresented
A binding to a Bool value that determines whether to show the picker.
onCompletion
Code that you supply, which processes any suggestions that a person may choose in the picker.
Discussion
For more information about the Journaling Suggestions picker, see: doc:presenting-the-suggestions-picker-and-processing-a-selection.
https://developer.apple.com/documentation/swiftui/view/labelicontotitlespacing(_:)
#app-main)
- SwiftUI
- View
- labelIconToTitleSpacing(_:) Beta
Instance Method
labelIconToTitleSpacing(_:)
Set the spacing between the icon and title in labels.
nonisolated
Discussion
Use this modifier to set the value that should be used for the icon-to-title spacing in labels. This applies to label styles and in contexts where the label displays its icon and title stacked horizontally.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/labelreservediconwidth(_:)
#app-main)
- SwiftUI
- View
- labelReservedIconWidth(_:) Beta
Instance Method
labelReservedIconWidth(_:)
Set the width reserved for icons in labels.
nonisolated
Discussion
Use this modifier to set the value that should be used for the reserved icon width in labels. This applies to label styles and in contexts where the label displays its icon and title stacked horizontally.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/labeledcontentstyle(_:)
#app-main)
- SwiftUI
- View
- labeledContentStyle(_:)
Instance Method
labeledContentStyle(_:)
Sets a style for labeled content.
nonisolated
See Also
Grouping inputs
struct Form
A container for grouping controls used for data entry, such as in settings or inspectors.
Sets the style for forms in a view hierarchy.
struct LabeledContent
A container for attaching a label to a value-bearing view.
https://developer.apple.com/documentation/swiftui/view/labelsvisibility(_:)
#app-main)
- SwiftUI
- View
- labelsVisibility(_:)
Instance Method
labelsVisibility(_:)
Controls the visibility of labels of any controls contained within this view.
nonisolated
Discussion
Use this modifier when you want to omit a label from one or more labeled content in your user interface. For example, the first Toggle in the following example hides its label:
VStack { Toggle(isOn: $toggle1) { Text("Toggle 1") } .labelsVisibility(.hidden)
Toggle(isOn: $toggle2) { Text("Toggle 2") } }
The VStack in the example above centers the first toggle’s control element in the available space, while it centers the second toggle’s combined label and control element:
Always provide a label for controls, even when you hide the label, because SwiftUI uses labels for other purposes, including accessibility.
On iOS, a Picker within a Menu hides its label by default. You can use this modifier to explicitly show the label in that context:
Menu { Picker("Flavor", selection: $selectedFlavor) { Text("Chocolate").tag(Flavor.chocolate) Text("Vanilla").tag(Flavor.vanilla) Text("Strawberry").tag(Flavor.strawberry) } .labelsVisibility(.visible) }
See Also
Hiding system elements
Hides the labels of any controls contained within this view.
var labelsVisibility: Visibility
The labels visibility set by labelsVisibility(_:).
Sets the menu indicator visibility for controls within this view.
Sets the visibility of the status bar.
Sets the preferred visibility of the non-transient system views overlaying the app.
enum Visibility
The visibility of a UI element, chosen automatically based on the platform, current context, and other factors.
https://developer.apple.com/documentation/swiftui/view/lineheight(_:)
#app-main)
- SwiftUI
- View
- lineHeight(_:) Beta
Instance Method
lineHeight(_:)
A modifier for the default line height in the view hierarchy.
nonisolated
Discussion
The default value is nil. In that case, SwiftUI automatically chooses an appropriate line height setting for each context.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/listrowinsets(::)
#app-main)
- SwiftUI
- View
- listRowInsets(_:_:) Beta
Instance Method
listRowInsets(_:_:)
Sets the insets of rows in a list on the specified edges.
nonisolated func listRowInsets( _ edges: Edge.Set = .all, _ length: CGFloat?
Parameters
edges
The edges to set the insets to.
length
An amount, given in points, to set the insets to on the specified edges.
Return Value
A view in which the margins of list sections are set to the specified amount
Discussion
Use this modifier to change the default insets of list rows on the specified edges.
In the example below, the Flavor enumeration provides content for list items. The SwiftUI ForEach structure computes views for each element of the Flavor enumeration and extracts the raw value of each of its elements using the resulting text to create each list row item. The listRowInsets(_:_:) modifier then changes the leading inset of each row of the list and leaves the default insets on the other edges untouched:
struct ContentView: View { enum Flavor: String, CaseIterable, Identifiable { var id: String { self.rawValue } case vanilla, chocolate, strawberry }
var body: some View { List { ForEach(Flavor.allCases) { Text($0.rawValue) .listRowInsets(.leading, 25) } } } }
When applying multiple listRowInsets modifiers, modifiers with the same edges will override modifiers higher up in the view hierarchy.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/listsectionindexvisibility(_:)
#app-main)
- SwiftUI
- View
- listSectionIndexVisibility(_:) Beta
Instance Method
listSectionIndexVisibility(_:)
Changes the visibility of the list section index.
nonisolated
Parameters
visibility
The visibility of the list section index.
Discussion
The section index shows the section index labels of sections, which are set using the sectionIndexLabel modifier. These are typically the letters of the alphabet, used for sorted sections.
List(sections) { section in Section(section.title) { ForEach(section.rows) { row in // ... } } .sectionIndexLabel(section.indexTitle) } .listSectionIndexVisibility(.visible)
On iOS, the section index is displayed as a number of vertically stacked letters on the trailing side of the list. Users can jump to a specific section in the list by tapping on the corresponding index label.
On watchOS, the index of the section currently visible is displayed next to the scroll indicator when the user is scrolling through the list using the crown.
By default, the list section index is visible if the list contains any sections with an index label.
The index only shows labels for sections with a sectionIndexLabel modifier. This can be used to hide certain sections from the index.
By hiding section headers of empty sections with an index label, a list section index can be made to show index labels without a corresponding section.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/listsectionmargins(::)
#app-main)
- SwiftUI
- View
- listSectionMargins(_:_:) Beta
Instance Method
listSectionMargins(_:_:)
Set the section margins for the specific edges.
nonisolated func listSectionMargins( _ edges: Edge.Set = .all, _ length: CGFloat?
Parameters
edges
The set of edges to pad for sections in this view. The default is all.
length
An amount, given in points, to pad section on the specified edges.
Return Value
A view in which the margins of list sections are set to the specified amount on the specified edges.
Discussion
Use this modifier on a list section to set customize its margins. Indicate the edges to set the margin of by naming either a single value from Edge.Set, or by specifying an OptionSet that contains edge values. Margins for the other edges remain unchanged.
The default section margins are based on the list style, list section spacing and content margins of the list. Using this modifier overrides these default values completely.
For sections that have headers or footers, the section margins are applied around these.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/lookaroundviewer(ispresented:initialscene:allowsnavigation:showsroadlabels:pointsofinterest:ondismiss:)
#app-main)
- SwiftUI
- View
- lookAroundViewer(isPresented:initialScene:allowsNavigation:showsRoadLabels:pointsOfInterest:onDismiss:)
Instance Method
lookAroundViewer(isPresented:initialScene:allowsNavigation:showsRoadLabels:pointsOfInterest:onDismiss:)
MapKitSwiftUI
@MainActor @preconcurrency func lookAroundViewer(
initialScene: MKLookAroundScene?, allowsNavigation: Bool = true, showsRoadLabels: Bool = true, pointsOfInterest: PointOfInterestCategories = .all,
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/lookaroundviewer(ispresented:scene:allowsnavigation:showsroadlabels:pointsofinterest:ondismiss:)
#app-main)
- SwiftUI
- View
- lookAroundViewer(isPresented:scene:allowsNavigation:showsRoadLabels:pointsOfInterest:onDismiss:)
Instance Method
lookAroundViewer(isPresented:scene:allowsNavigation:showsRoadLabels:pointsOfInterest:onDismiss:)
MapKitSwiftUI
@MainActor @preconcurrency func lookAroundViewer(
allowsNavigation: Bool = true, showsRoadLabels: Bool = true, pointsOfInterest: PointOfInterestCategories = .all,
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/managesubscriptionssheet(ispresented:subscriptiongroupid:)
https://developer.apple.com/documentation/swiftui/view/managedcontentstyle(_:)
#app-main)
- SwiftUI
- View
- managedContentStyle(_:)
Instance Method
managedContentStyle(_:)
Applies a managed content style to the view.
ManagedAppDistributionSwiftUI
@MainActor @preconcurrency
Parameters
style
The style to apply to the view.
Return Value
The styled view.
See Also
Working with managed devices
Presents a modal view that enables users to add devices to their organization.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/manipulable(coordinatespace:operations:inertia:isenabled:onchanged:)
#app-main)
- SwiftUI
- View
- manipulable(coordinateSpace:operations:inertia:isEnabled:onChanged:) Beta
Instance Method
manipulable(coordinateSpace:operations:inertia:isEnabled:onChanged:)
Allows this view to be manipulated using common hand gestures.
nonisolated func manipulable( coordinateSpace: some CoordinateSpaceProtocol = .local, operations: Manipulable.Operation.Set = .all, inertia: Manipulable.Inertia = .medium, isEnabled: Bool = true,
Parameters
coordinateSpace
The coordinate space of the manipulation gesture event locations.
operations
The set of allowed operations that can be applied when a person manipulates this view.
inertia
The inertia of this view that defines how much it resists being manipulated.
isEnabled
The Boolean value that indicates whether the manipulation gesture added by this view modifier is enabled or not.
onChanged
The action to perform with each new manipulation gesture event.
Return Value
A view that can be manipulated using common hand gestures.
Discussion
When a person ends the manipulation gesture, the view will
https://developer.apple.com/documentation/swiftui/view/manipulable(transform:coordinatespace:operations:inertia:isenabled:onchanged:)
https://developer.apple.com/documentation/swiftui/view/manipulable(using:)
#app-main)
- SwiftUI
- View
- manipulable(using:) Beta
Instance Method
manipulable(using:)
Allows the view to be manipulated using a manipulation gesture attached to a different view.
nonisolated
Parameters
gestureState
The manipulation gesture state that’s updated by a manipulation gesture added to a different view.
Return Value
A view that can be manipulated by a manipulation gesture attached to a different view.
Discussion
Use this view modifier alongside manipulationGesture(updating:coordinateSpace:operations:inertia:isEnabled:onChanged:) when you want to allow a person to manipulate a view by interacting with a different view.
In the following example, a person can begin a manipulation gesture attached to a deck of cards which, in turn, manipulates a single card instead of the entire deck:
struct CardDeck: View { @State private var manipulationState = Manipulable.GestureState()
var body: some View { ZStack { Model3D(named: "CardDeck") .manipulationGesture(updating: $manipulationState) Model3D(named: "Card") .manipulable(using: manipulationState) .opacity(manipulationState.isActive ? 1 : 0) } } }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/manipulationgesture(updating:coordinatespace:operations:inertia:isenabled:onchanged:)
https://developer.apple.com/documentation/swiftui/view/mapcamerakeyframeanimator(trigger:keyframes:)
#app-main)
- SwiftUI
- View
- mapCameraKeyframeAnimator(trigger:keyframes:)
Instance Method
mapCameraKeyframeAnimator(trigger:keyframes:)
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
MapKitSwiftUI
@MainActor @preconcurrency func mapCameraKeyframeAnimator( trigger: some Equatable,
Parameters
trigger
A value to observe for changes.
keyframes
A keyframes builder closure that is called when starting a new keyframe animation. The current map camera is provided as the only parameter.
Discussion
When the trigger value changes, the map calls the keyframes closure to generate the keyframes that will animate the camera. The animation will continue for the duration of the keyframes that you specify.
If the user performs a gesture while the animation is in progress, the animation will be immediately removed, allowing the interaction to take control of the camera.
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/mapcontrolvisibility(_:)
#app-main)
- SwiftUI
- View
- mapControlVisibility(_:)
Instance Method
mapControlVisibility(_:)
Configures all Map controls in the environment to have the specified visibility
MapKitSwiftUI
@MainActor @preconcurrency
Parameters
visibility
How modified map controls should show or hide
Discussion
MapCompass, MapScaleView, and MapPitchToggle may automatically show and hide based on the current state of the Map. That may not be appropriate for all use cases, where always showing a control may be desirable.
HStack { MapCompass() MapScaleView() MapPitchToggle() } .mapControls(.visible)
Other controls don’t have an automatic visibility behavior, so they will always be visible when automatic is specified. Controls may also be hidden via this modifier when conditionalizing the view is not appropriate
MapUserLocationButton() .mapControls(.automatic) MapZoomStepper() .mapControls(.hidden)
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/mapcontrols(_:)
#app-main)
- SwiftUI
- View
- mapControls(_:)
Instance Method
mapControls(_:)
Configures all Map views in the associated environment to have standard size and position controls
MapKitSwiftUI
@MainActor @preconcurrency
Parameters
content
A view builder returning the controls you wish your Map
Discussion
You provide the controls you want to appear atop your map. When using a control in conjunction with .mapControls you don’t need to specify a scope. Views that are not MapKit controls will be ignored.
Map() .mapControls { MapScaleView() MapUserLocationButton() }
Controls can be modified individually or all at once. Custom frames and alignments set on controls are ignored.
Map() .mapControls { MapCompass() .mapControls(.visible) MapPitchToggle() .buttonBorderShape(.circular) .tint(.purple) } .controlSize(.large)
On watchOS, space is at a premium. When using the mapControls modifier, MapUserLocationButton and MapCompass are automatically combined if present.
Map() .mapControls { MapUserLocationButton() MapCompass() }
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/mapfeatureselectionaccessory(_:)
#app-main)
- SwiftUI
- View
- mapFeatureSelectionAccessory(_:)
Instance Method
mapFeatureSelectionAccessory(_:)
Specifies the selection accessory to display for a MapFeature
MapKitSwiftUI
@MainActor @preconcurrency
Parameters
style
The map item detail selection accessory style. If nil, no selection accessory will be displayed.
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/mapfeatureselectioncontent(content:)
#app-main)
- SwiftUI
- View
- mapFeatureSelectionContent(content:)
Instance Method
mapFeatureSelectionContent(content:)
Specifies a custom presentation for the currently selected feature.
MapKitSwiftUI
@MainActor @preconcurrency
Parameters
content
Generates the custom presentation for a given map feature.
Discussion
The supported presentation options are Annotation, and Marker. Other types of map content will be ignored and handled as though no content was returned.
If empty map content is returned, the system presentation will be used.
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/mapfeatureselectiondisabled(_:)
#app-main)
- SwiftUI
- View
- mapFeatureSelectionDisabled(_:)
Instance Method
mapFeatureSelectionDisabled(_:)
Specifies which map features should have selection disabled.
MapKitSwiftUI
@MainActor @preconcurrency
Parameters
selectionDisabled
Determines if selection should be disabled for a given map feature.
Discussion
The selectionDisabled parameter takes a closure which maps map features, to booleans. If that closure returns true for a given map feature, that map feature will be considered unselectable.
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/mapitemdetailpopover(ispresented:item:displaysmap:attachmentanchor:)
https://developer.apple.com/documentation/swiftui/view/mapitemdetailpopover(ispresented:item:displaysmap:attachmentanchor:arrowedge:)
#app-main)
- SwiftUI
- View
- mapItemDetailPopover(isPresented:item:displaysMap:attachmentAnchor:arrowEdge:)
Instance Method
mapItemDetailPopover(isPresented:item:displaysMap:attachmentAnchor:arrowEdge:)
Presents a map item detail popover.
MapKitSwiftUI
@MainActor @preconcurrency func mapItemDetailPopover(
item: MKMapItem?, displaysMap: Bool = true, attachmentAnchor: PopoverAttachmentAnchor = .rect(.bounds), arrowEdge: Edge
Parameters
isPresented
The binding to whether the detail sheet should be shown.
item
The map item to display. If nil, a “loading” view is displayed.
displaysMap
If an inline map should be displayed with the place data. A value of true must be specified if the application UI is not already showing the place in a map view.
attachmentAnchor
The positioning anchor that defines the attachment point of the popover. The default is bounds.
arrowEdge
The edge of the attachmentAnchor that defines the location of the popover’s arrow.
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
https://developer.apple.com/documentation/swiftui/view/mapitemdetailpopover(item:displaysmap:attachmentanchor:)
#app-main)
- SwiftUI
- View
- mapItemDetailPopover(item:displaysMap:attachmentAnchor:)
Instance Method
mapItemDetailPopover(item:displaysMap:attachmentAnchor:)
Presents a map item detail popover.
MapKitSwiftUI
@MainActor @preconcurrency func mapItemDetailPopover(
displaysMap: Bool = true, attachmentAnchor: PopoverAttachmentAnchor = .rect(.bounds)
Parameters
item
When item is non- nil, a detail popover is displayed for the map item.
displaysMap
If an inline map should be displayed with the place data. A value of true must be specified if the application UI is not already showing the place in a map view.
attachmentAnchor
The positioning anchor that defines the attachment point of the popover. The default is bounds.
Discussion
Use this modifier if you want the system to choose the best orientation of the popover’s arrow. If you want to specify a particular edge for the arrow, use mapItemDetailPopover(item:displaysMap:attachmentAnchor:arrowEdge:).
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
https://developer.apple.com/documentation/swiftui/view/mapitemdetailpopover(item:displaysmap:attachmentanchor:arrowedge:)
#app-main)
- SwiftUI
- View
- mapItemDetailPopover(item:displaysMap:attachmentAnchor:arrowEdge:)
Instance Method
mapItemDetailPopover(item:displaysMap:attachmentAnchor:arrowEdge:)
Presents a map item detail popover.
MapKitSwiftUI
@MainActor @preconcurrency func mapItemDetailPopover(
displaysMap: Bool = true, attachmentAnchor: PopoverAttachmentAnchor = .rect(.bounds), arrowEdge: Edge
Parameters
item
When item is non- nil, a detail popover is displayed for the map item.
displaysMap
If an inline map should be displayed with the place data. A value of true must be specified if the application UI is not already showing the place in a map view.
attachmentAnchor
The positioning anchor that defines the attachment point of the popover. The default is bounds.
arrowEdge
The edge of the attachmentAnchor that defines the location of the popover’s arrow.
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
https://developer.apple.com/documentation/swiftui/view/mapitemdetailsheet(ispresented:item:displaysmap:)
#app-main)
- SwiftUI
- View
- mapItemDetailSheet(isPresented:item:displaysMap:)
Instance Method
mapItemDetailSheet(isPresented:item:displaysMap:)
Presents a map item detail sheet.
MapKitSwiftUI
@MainActor @preconcurrency func mapItemDetailSheet(
item: MKMapItem?, displaysMap: Bool = true
Parameters
isPresented
The binding to whether the detail sheet should be shown.
item
The map item to display. If nil, a “loading” view is displayed.
displaysMap
If an inline map should be displayed with the place data. A value of true must be specified if the application UI is not already showing the place in a map view.
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/mapitemdetailsheet(item:displaysmap:)
#app-main)
- SwiftUI
- View
- mapItemDetailSheet(item:displaysMap:)
Instance Method
mapItemDetailSheet(item:displaysMap:)
Presents a map item detail sheet.
MapKitSwiftUI
@MainActor @preconcurrency func mapItemDetailSheet(
displaysMap: Bool = true
Parameters
item
When item is non- nil, a detail sheet is displayed for the map item.
displaysMap
If an inline map should be displayed with the place data. A value of true must be specified if the application UI is not already showing the place in a map view.
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/mapscope(_:)
#app-main)
- SwiftUI
- View
- mapScope(_:)
Instance Method
mapScope(_:)
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
MapKitSwiftUI
@MainActor @preconcurrency
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/mapstyle(_:)
#app-main)
- SwiftUI
- View
- mapStyle(_:)
Instance Method
mapStyle(_:)
Specifies the map style to be used.
MapKitSwiftUI
@MainActor @preconcurrency
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
func onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/matchedtransitionsource(id:in:)
#app-main)
- SwiftUI
- View
- matchedTransitionSource(id:in:)
Instance Method
matchedTransitionSource(id:in:)
Identifies this view as the source of a navigation transition, such as a zoom transition.
nonisolated func matchedTransitionSource( id: some Hashable, in namespace: Namespace.ID
Parameters
id
The identifier, often derived from the identifier of the data being displayed by the view.
namespace
The namespace in which defines the id. New namespaces are created by adding an Namespace variable to a View type and reading its value in the view’s body method.
See Also
Defining transitions
func transition(_:)
Associates a transition with the view.
protocol Transition
A description of view changes to apply when a view is added to and removed from the view hierarchy.
struct TransitionProperties
The properties a Transition can have.
enum TransitionPhase
An indication of which the current stage of a transition.
struct AsymmetricTransition
A composite Transition that uses a different transition for insertion versus removal.
struct AnyTransition
A type-erased transition.
Modifies the view to use a given transition as its method of animating changes to the contents of its views.
var contentTransition: ContentTransition
The current method of animating the contents of views.
var contentTransitionAddsDrawingGroup: Bool
A Boolean value that controls whether views that render content transitions use GPU-accelerated rendering.
struct ContentTransition
A kind of transition that applies to the content within a single view, rather than to the insertion or removal of a view.
struct PlaceholderContentView
A placeholder used to construct an inline modifier, transition, or other helper type.
Sets the navigation transition style for this view.
protocol NavigationTransition
A type that defines the transition to use when navigating to a view.
protocol MatchedTransitionSourceConfiguration
A configuration that defines the appearance of a matched transition source.
https://developer.apple.com/documentation/swiftui/view/matchedtransitionsource(id:in:configuration:)
#app-main)
- SwiftUI
- View
- matchedTransitionSource(id:in:configuration:)
Instance Method
matchedTransitionSource(id:in:configuration:)
Identifies this view as the source of a navigation transition, such as a zoom transition.
nonisolated func matchedTransitionSource( id: some Hashable, in namespace: Namespace.ID,
Parameters
id
The identifier, often derived from the identifier of the data being displayed by the view.
namespace
The namespace in which defines the id. New namespaces are created by adding an Namespace variable to a View type and reading its value in the view’s body method.
configuration
A closure that you can use to apply styling to the source.
Discussion
The appearance of the source can be configured using the configuration trailing closure. Any modifiers applied will be smoothly interpolated when a zoom transition originates from this matched transition source.
MyView() .matchedTransitionSource(id: someID, in: someNamespace) { source in source .cornerRadius(8.0) }
See Also
Defining transitions
func transition(_:)
Associates a transition with the view.
protocol Transition
A description of view changes to apply when a view is added to and removed from the view hierarchy.
struct TransitionProperties
The properties a Transition can have.
enum TransitionPhase
An indication of which the current stage of a transition.
struct AsymmetricTransition
A composite Transition that uses a different transition for insertion versus removal.
struct AnyTransition
A type-erased transition.
Modifies the view to use a given transition as its method of animating changes to the contents of its views.
var contentTransition: ContentTransition
The current method of animating the contents of views.
var contentTransitionAddsDrawingGroup: Bool
A Boolean value that controls whether views that render content transitions use GPU-accelerated rendering.
struct ContentTransition
A kind of transition that applies to the content within a single view, rather than to the insertion or removal of a view.
struct PlaceholderContentView
A placeholder used to construct an inline modifier, transition, or other helper type.
Sets the navigation transition style for this view.
protocol NavigationTransition
A type that defines the transition to use when navigating to a view.
protocol MatchedTransitionSourceConfiguration
A configuration that defines the appearance of a matched transition source.
https://developer.apple.com/documentation/swiftui/view/materialactiveappearance(_:)
#app-main)
- SwiftUI
- View
- materialActiveAppearance(_:)
Instance Method
materialActiveAppearance(_:)
Sets an explicit active appearance for materials in this view.
nonisolated
See Also
Transforming colors
Brightens this view by the specified amount.
Sets the contrast and separation between similar colors in this view.
Inverts the colors in this view.
Adds a color multiplication effect to this view.
Adjusts the color saturation of this view.
Adds a grayscale effect to this view.
Applies a hue rotation effect to this view.
Adds a luminance to alpha effect to this view.
var materialActiveAppearance: MaterialActiveAppearance
The behavior materials should use for their active state, defaulting to automatic.
struct MaterialActiveAppearance
The behavior for how materials appear active and inactive.
https://developer.apple.com/documentation/swiftui/view/multilinetextalignment(strategy:)
#app-main)
- SwiftUI
- View
- multilineTextAlignment(strategy:) Beta
Instance Method
multilineTextAlignment(strategy:)
A modifier for the default text alignment strategy in the view hierarchy.
nonisolated
Discussion
To control the alignment explicitly at a view level, choose the layoutBased mode and set the multilineTextAlignment to the appropriate value.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/navigationlinkindicatorvisibility(_:)
https://developer.apple.com/documentation/swiftui/view/navigationtransition(_:)
#app-main)
- SwiftUI
- View
- navigationTransition(_:)
Instance Method
navigationTransition(_:)
Sets the navigation transition style for this view.
nonisolated
Discussion
Add this modifier to a view that appears within a NavigationStack or a sheet, outside of any containers such as VStack.
struct ContentView: View { @Namespace private var namespace var body: some View { NavigationStack { NavigationLink { DetailView() .navigationTransition(.zoom(sourceID: "world", in: namespace)) } label: { Image(systemName: "globe") .matchedTransitionSource(id: "world", in: namespace) } } } }
See Also
Defining transitions
func transition(_:)
Associates a transition with the view.
protocol Transition
A description of view changes to apply when a view is added to and removed from the view hierarchy.
struct TransitionProperties
The properties a Transition can have.
enum TransitionPhase
An indication of which the current stage of a transition.
struct AsymmetricTransition
A composite Transition that uses a different transition for insertion versus removal.
struct AnyTransition
A type-erased transition.
Modifies the view to use a given transition as its method of animating changes to the contents of its views.
var contentTransition: ContentTransition
The current method of animating the contents of views.
var contentTransitionAddsDrawingGroup: Bool
A Boolean value that controls whether views that render content transitions use GPU-accelerated rendering.
struct ContentTransition
A kind of transition that applies to the content within a single view, rather than to the insertion or removal of a view.
struct PlaceholderContentView
A placeholder used to construct an inline modifier, transition, or other helper type.
protocol NavigationTransition
A type that defines the transition to use when navigating to a view.
Identifies this view as the source of a navigation transition, such as a zoom transition.
protocol MatchedTransitionSourceConfiguration
A configuration that defines the appearance of a matched transition source.
https://developer.apple.com/documentation/swiftui/view/onappintentexecution(_:perform:)
#app-main)
- SwiftUI
- View
- onAppIntentExecution(_:perform:)
Instance Method
onAppIntentExecution(_:perform:)
Registers a handler to invoke in response to the specified app intent that your app receives.
AppIntentsSwiftUI
nonisolated
_ intent: I.Type = I.self,
Parameters
intent
The type of App Intent that the action closure handles.
action
A closure that SwiftUI calls when the specified app intent is being performed. The closure takes the app intent instance as an input parameter.
Return Value
A view that handles the specified app intent’s perform
Discussion
Use this view modifier to receive instances in a particular scene within your app. The scene that SwiftUI routes the incoming user activity to depends on the structure of your app, what scenes are active, and other configuration. For more information, see handlesExternalEvents(matching:).
If the app intent implements a perform() method, it will be called after the action closure. This can be useful if your app intent supports running in the background via the AppIntent.IntentModes API
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/onapplepaycouponcodechange(perform:)
https://developer.apple.com/documentation/swiftui/view/onapplepaypaymentmethodchange(perform:)
#app-main)
- SwiftUI
- View
- onApplePayPaymentMethodChange(perform:)
Instance Method
onApplePayPaymentMethodChange(perform:)
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
PassKitSwiftUI
nonisolated
Return Value
An update to the payment request method.
See Also
Accessing Apple Pay and Wallet
A view that displays a button for identity verification.
Sets the button’s style.
Sets the style to be used by the button. (see PKAddPassButtonStyle).
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
Sets the action on the PayLaterView. See PKPayLaterAction.
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Sets the style to be used by the button. (see PKIdentityButtonStyle).
Provides a task to perform before this view appears
https://developer.apple.com/documentation/swiftui/view/onapplepayshippingcontactchange(perform:)
#app-main)
- SwiftUI
- View
- onApplePayShippingContactChange(perform:)
Instance Method
onApplePayShippingContactChange(perform:)
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
PassKitSwiftUI
nonisolated
Return Value
An update to the payment request shipping methods.
See Also
Accessing Apple Pay and Wallet
A view that displays a button for identity verification.
Sets the button’s style.
Sets the style to be used by the button. (see PKAddPassButtonStyle).
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
Sets the action on the PayLaterView. See PKPayLaterAction.
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Sets the style to be used by the button. (see PKIdentityButtonStyle).
Provides a task to perform before this view appears
https://developer.apple.com/documentation/swiftui/view/onapplepayshippingmethodchange(perform:)
#app-main)
- SwiftUI
- View
- onApplePayShippingMethodChange(perform:)
Instance Method
onApplePayShippingMethodChange(perform:)
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
PassKitSwiftUI
nonisolated
Return Value
An update to the payment request shipping method.
See Also
Accessing Apple Pay and Wallet
A view that displays a button for identity verification.
Sets the button’s style.
Sets the style to be used by the button. (see PKAddPassButtonStyle).
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
Sets the action on the PayLaterView. See PKPayLaterAction.
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Sets the style to be used by the button. (see PKIdentityButtonStyle).
Provides a task to perform before this view appears
https://developer.apple.com/documentation/swiftui/view/oncameracaptureevent(isenabled:defaultsounddisabled:action:)
https://developer.apple.com/documentation/swiftui/view/oncameracaptureevent(isenabled:defaultsounddisabled:primaryaction:secondaryaction:)
https://developer.apple.com/documentation/swiftui/view/ondragsessionupdated(_:)
https://developer.apple.com/documentation/swiftui/view/ondropsessionupdated(_:)
#app-main)
- SwiftUI
- View
- onDropSessionUpdated(_:) Beta
Instance Method
onDropSessionUpdated(_:)
Specifies an action to perform on each update of an ongoing drop operation activated by dropDestination(_:) or other drop modifiers.
nonisolated
Discussion
The onUpdate closure is called when the closest drop session in the child view hierarchy becomes active.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/ongeometrychange3d(for:of:action:)
https://developer.apple.com/documentation/swiftui/view/oninapppurchasecompletion(perform:)
#app-main)
- SwiftUI
- View
- onInAppPurchaseCompletion(perform:)
Instance Method
onInAppPurchaseCompletion(perform:)
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
StoreKitSwiftUI
nonisolated
Parameters
action
The action to perform, with the product value and the purchase result provided as parameters.
Discussion
By default, transactions from successful in-app store view purchases will be emitted from Transaction.updates. If the purchase fails with an error, an alert will be displayed. You can revert a view ) modifier.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
Declares the view as dependent on a collection of In-App Purchase products and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/oninapppurchasestart(perform:)
https://developer.apple.com/documentation/swiftui/view/onmapcamerachange(frequency:_:)
#app-main)
- SwiftUI
- View
- onMapCameraChange(frequency:_:)
Instance Method
onMapCameraChange(frequency:_:)
Performs an action when Map camera framing changes
MapKitSwiftUI
@MainActor @preconcurrency func onMapCameraChange( frequency: MapCameraUpdateFrequency = .onEnd,
Show all declarations
Parameters
frequency
How frequently the action should be performed during a camera interaction.
action
A closure to run when the camera framing changes.
See Also
Getting location information
@MainActor @preconcurrency struct LocationButton
A SwiftUI button that grants one-time location authorization.
A view that displays an embedded map interface.
Specifies the map style to be used.
Creates a mapScope that SwiftUI uses to connect map controls to an associated map.
Specifies which map features should have selection disabled.
Specifies the selection accessory to display for a MapFeature
Specifies a custom presentation for the currently selected feature.
Configures all Map views in the associated environment to have standard size and position controls
Configures all Map controls in the environment to have the specified visibility
Uses the given keyframes to animate the camera of a Map when the given trigger value changes.
Presents a map item detail popover.
https://developer.apple.com/documentation/swiftui/view/onopenurl(prefersinapp:)
#app-main)
- SwiftUI
- View
- onOpenURL(prefersInApp:) Beta
Instance Method
onOpenURL(prefersInApp:)
Sets an OpenURLAction that prefers opening URL with an in-app browser. It’s equivalent to calling .onOpenURL(_:)
@MainActor @preconcurrency
Discussion
.onOpenURL { _ in .systemAction(prefersInApp: prefersInApp) }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/onworldrecenter(action:)
https://developer.apple.com/documentation/swiftui/view/paylaterviewaction(_:)
#app-main)
- SwiftUI
- View
- payLaterViewAction(_:)
Instance Method
payLaterViewAction(_:)
Sets the action on the PayLaterView. See PKPayLaterAction.
PassKitSwiftUI
nonisolated
See Also
Accessing Apple Pay and Wallet
A view that displays a button for identity verification.
Sets the button’s style.
Sets the style to be used by the button. (see PKAddPassButtonStyle).
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Sets the style to be used by the button. (see PKIdentityButtonStyle).
Provides a task to perform before this view appears
https://developer.apple.com/documentation/swiftui/view/paylaterviewdisplaystyle(_:)
#app-main)
- SwiftUI
- View
- payLaterViewDisplayStyle(_:)
Instance Method
payLaterViewDisplayStyle(_:)
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
PassKitSwiftUI
nonisolated
See Also
Accessing Apple Pay and Wallet
A view that displays a button for identity verification.
Sets the button’s style.
Sets the style to be used by the button. (see PKAddPassButtonStyle).
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
Sets the action on the PayLaterView. See PKPayLaterAction.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Sets the style to be used by the button. (see PKIdentityButtonStyle).
Provides a task to perform before this view appears
https://developer.apple.com/documentation/swiftui/view/paywithapplepaybuttondisablecardart()
#app-main)
- SwiftUI
- View
- payWithApplePayButtonDisableCardArt() Beta
Instance Method
payWithApplePayButtonDisableCardArt()
Sets the features that should be allowed to show on the payment buttons.
PassKitSwiftUI
nonisolated
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/paywithapplepaybuttonstyle(_:)
https://developer.apple.com/documentation/swiftui/view/popovertip(_:arrowedge:action:)
#app-main)
- SwiftUI
- View
- popoverTip(_:arrowEdge:action:)
Instance Method
popoverTip(_:arrowEdge:action:)
Presents a popover tip on the modified view.
@preconcurrency nonisolated func popoverTip( _ tip: (any Tip)?, arrowEdge: Edge? = nil,
Parameters
tip
The tip to display.
arrowEdge
The edge of the attachmentAnchor that defines the location of the popover’s arrow. By default, the system will choose the best orientation of the popover’s arrow.
action
The action to perform when the user triggers a tip’s button.
Discussion
Use this modifier to present a tip as a popover on an existing view when the tip becomes eligible for display.
import SwiftUI import TipKit
// Define your tip's content. struct SampleTip: Tip { var title: Text { Text("Save as a Favorite") }
var message: Text? { Text("Your favorite backyards always appear at the top of the list.") }
var image: Image? { Image(systemName: "star") } }
struct SampleView: View { // Create an instance of your tip. var tip = SampleTip()
var body: some View {
VStack {
// Add .popoverTip to the view you want to modify.
// Tips.configure(options:) must be called before your tip will be eligible for display.
Image(systemName: "star")
.popoverTip(tip)
}
}
}
See Also
Providing tips
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
Sets the corner radius for an inline tip view.
Sets the size for a tip’s image.
Sets the given style for TipView within the view hierarchy.
Sets the style for a tip’s image.
https://developer.apple.com/documentation/swiftui/view/posttophotossharedalbumsheet(ispresented:items:photolibrary:defaultalbumidentifier:completion:)
#app-main)
- SwiftUI
- View
- postToPhotosSharedAlbumSheet(isPresented:items:photoLibrary:defaultAlbumIdentifier:completion:) Beta
Instance Method
postToPhotosSharedAlbumSheet(isPresented:items:photoLibrary:defaultAlbumIdentifier:completion:)
Presents an “Add to Shared Album” sheet that allows the user to post the given items to a shared album.
PhotosUISwiftUI
@MainActor func postToPhotosSharedAlbumSheet(
items: [PHPickerResult], photoLibrary: PHPhotoLibrary, defaultAlbumIdentifier: String? = nil,
Show all declarations
Discussion
-
isPresented: The binding to whether the sheet should be shown.
-
items: The items to be posted to the shared album.
-
photoLibrary: Library to choose from.
-
defaultAlbumIdentifier: Identifier for the shared album to be pre-selected. If none provided user can manually choose the shared album in UI.
-
completion: Called with the result on completion of the request.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/preferredwindowclippingmargins(::)
https://developer.apple.com/documentation/swiftui/view/presentationbreakthrougheffect(_:)
#app-main)
- SwiftUI
- View
- presentationBreakthroughEffect(_:) Beta
Instance Method
presentationBreakthroughEffect(_:)
Changes the way the enclosing presentation breaks through content occluding it.
nonisolated
Parameters
effect
The type of effect to apply when a presentation element is occluded by other content.
Discussion
Use this modifier to disable or customize a breakthrough effect for the enclosing presentation.
Breakthrough is an effect allowing elements to be visible to the user even when other app content (3D models, UI elements) is occluding it. The way the element appears depends on the chosen BreakthroughEffect.
Most system presentations appear with a breakthrough effect by default. For these cases, the presentationBreakthroughEffect modifier allows customization of the type of effect. This is achieved by applying the modifier to the content of the presentation:
Button("Show Details") { isShowingDetails = true } .popover(isPresented: $isShowingDetails) { DetailsView() .presentationBreakthroughEffect(.prominent) }
Only popovers allow breakthrough to be disabled altogether. Passing a .none value for a sheet doesn’t have any effect.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/presentationpreventsapptermination(_:)
#app-main)
- SwiftUI
- View
- presentationPreventsAppTermination(_:)
Instance Method
presentationPreventsAppTermination(_:)
Whether a presentation prevents the app from being terminated/quit by the system or app termination menu item.
nonisolated
Discussion
SwiftUI uses the buttons in a sheet’s toolbar to determine whether a particular sheet should block termination by default. If there is a singular toolbar item with the confirmationAction or the cancellationAction placement and no other toolbar items, the sheet will not prevent termination by default.
Use this modifier to specify whether a sheet should prevent app termination. Pass nil to explicitly request the automatic behavior/for the inert version of this modifier. Non-nil values will override nil, and true takes precedence over false.
Use this modifier within the content argument to View/sheet
struct LaunchScreen: View {
@State private var presentLogin = false
var body: some View {
HomeView()
.sheet(isPresented: $presentLogin) {
LoginView()
// explicitly allow app termination because the
// default behavior would resolve to true.
.presentationPreventsAppTermination(false)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { presentLogin = false }
}
ToolbarItem(placement: .confirmationAction) {
Button("Login") {
// Attempt login...
presentLogin = false
}
}
}
}
}
}
https://developer.apple.com/documentation/swiftui/view/productdescription(_:)
#app-main)
- SwiftUI
- View
- productDescription(_:)
Instance Method
productDescription(_:)
Configure the visibility of labels displaying an in-app purchase product description within the view.
StoreKitSwiftUI
nonisolated
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
Declares the view as dependent on a collection of In-App Purchase products and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/producticonborder()
https://developer.apple.com/documentation/swiftui/view/productviewstyle(_:)
#app-main)
- SwiftUI
- View
- productViewStyle(_:)
Instance Method
productViewStyle(_:)
Sets the style for In-App Purchase product views within a view.
StoreKitSwiftUI
nonisolated
Parameters
style
The style to apply to the in-app purchase product views within the view.
Discussion
This modifier styles any ProductView or StoreView instances within a view.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
Declares the view as dependent on a collection of In-App Purchase products and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/realityviewcameracontrols(_:)
#app-main)
- SwiftUI
- View
- realityViewCameraControls(_:)
Instance Method
realityViewCameraControls(_:)
Adds gestures that control the position and direction of a virtual camera.
RealityKitSwiftUI
@MainActor @preconcurrency
Discussion
You can use a drag gesture from a mouse, trackpad, or screen touches with iOS and iPadOS devices to .tilt, .pan, .orbit, or .dolly a virtual camera.
See Also
Configuring camera controls
var realityViewCameraControls: CameraControls
The camera controls for the reality view.
https://developer.apple.com/documentation/swiftui/view/realityviewlayoutbehavior(_:)
https://developer.apple.com/documentation/swiftui/view/rotation3dlayout(_:)
#app-main)
- SwiftUI
- View
- rotation3DLayout(_:) Beta
Instance Method
rotation3DLayout(_:)
Rotates a view with impacts to its frame in a containing layout
nonisolated
Parameters
rotation
A rotation to apply to the view and its frame.
Discussion
The following example will rotate the top plane by 45 degrees while adjusting its frame to account for this rotation. The VStack sizes to fit the rotated and standard models.
VStack { Model3D(named: "plane") .rotation3DLayout(Rotation3D(angle: .degrees(45), axis: .z)) Model3D(named: "plane")
}
The layout system will use a bounding box that completely contains the rotated view, meaning this modifier can change the size of the view it is applied to.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/rotation3dlayout(_:axis:)
#app-main)
- SwiftUI
- View
- rotation3DLayout(_:axis:) Beta
Instance Method
rotation3DLayout(_:axis:)
Rotates a view with impacts to its frame in a containing layout
nonisolated func rotation3DLayout( _ angle: Angle, axis: (x: CGFloat, y: CGFloat, z: CGFloat)
Show all declarations
Parameters
angle
The angle by which to rotate the view and its frame.
axis
The axis of rotation.
Discussion
The following example will rotate the top plane by 45 degrees while adjusting its frame to account for this rotation. The VStack sizes to fit the rotated and standard models.
VStack { Model3D(named: "plane") .rotation3DLayout(.degrees(45), axis: (x: 0, y: 0, z: 1)) Model3D(named: "plane")
}
The layout system will use a bounding box that completely contains the rotated view, meaning this modifier can change the size of the view it is applied to.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/safeareabar(edge:alignment:spacing:content:)
#app-main)
- SwiftUI
- View
- safeAreaBar(edge:alignment:spacing:content:) Beta
Instance Method
safeAreaBar(edge:alignment:spacing:content:)
Renders the provided content appropriately to be displayed as a custom bar.
nonisolated func safeAreaBar( edge: HorizontalEdge, alignment: VerticalAlignment = .center, spacing: CGFloat? = nil,
Show all declarations
Discussion
Similar to a View/safeAreaInset(edge:alignment:spacing:content) modifier, the modified view will have its horizontal safe area inset by the height of the content.
In addition to adjusting the safe area, the bar modifier configures the content to support views to automatically extend the edge effect of any scroll view’s the bar adjusts safe area of.
See Also
Configuring scroll edge effects
Configures the scroll edge effect style for scroll views within this hierarchy.
Beta
Disables any scroll edge effects for scroll views within this hierarchy.
struct ScrollEdgeEffectStyle
A structure that defines the style of pocket a scroll view will have.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/scaledtofill3d()
#app-main)
- SwiftUI
- View
- scaledToFill3D() Beta
Instance Method
scaledToFill3D()
Scales this view to fill its parent.
nonisolated
Return Value
A view that scales this view to fit its parent, maintaining this view’s aspect ratio.
Discussion
This view’s 3D aspect ratio is maintained as the view scales. This method is equivalent to calling aspectRatio3D(nil, contentMode: .fill).
Model3D(named: "Sphere") { resolved in resolved .resizable() .scaledToFill3D() } placeholder: { ProgressView() } .frame(width: 300, height: 100) .frame(depth: 300) .border(Color(white: 0.75))
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/scaledtofit3d()
#app-main)
- SwiftUI
- View
- scaledToFit3D() Beta
Instance Method
scaledToFit3D()
Scales this view to fit its parent.
nonisolated
Return Value
A view that scales this view to fit its parent, maintaining this view’s aspect ratio.
Discussion
This view’s 3D aspect ratio is maintained as the view scales. This method is equivalent to calling aspectRatio3D(nil, contentMode: .fit).
Model3D(named: "Plane") { resolved in resolved .resizable() .scaledToFit3D() } placeholder: { ProgressView() } .frame(width: 400, height: 400) .frame(depth: 200) .border(Color(white: 0.75))
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/scrolledgeeffectdisabled(_:for:)
#app-main)
- SwiftUI
- View
- scrollEdgeEffectDisabled(_:for:) Beta
Instance Method
scrollEdgeEffectDisabled(_:for:)
Disables any scroll edge effects for scroll views within this hierarchy.
nonisolated func scrollEdgeEffectDisabled( _ disabled: Bool = true, for edges: Edge.Set = .all
Discussion
By default, a scroll view will render an automatic edge effect style. You use this modifier to disable the rendering of any edge effects for scroll views within this hierarchy.
ScrollView { LazyVStack { ForEach(data) { item in RowView(item) } } } .scrollEdgeEffectDisabled()
See Also
Configuring scroll edge effects
Configures the scroll edge effect style for scroll views within this hierarchy.
Beta
struct ScrollEdgeEffectStyle
A structure that defines the style of pocket a scroll view will have.
func safeAreaBar(edge:alignment:spacing:content:)
Renders the provided content appropriately to be displayed as a custom bar.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/scrolledgeeffectstyle(_:for:)
#app-main)
- SwiftUI
- View
- scrollEdgeEffectStyle(_:for:) Beta
Instance Method
scrollEdgeEffectStyle(_:for:)
Configures the scroll edge effect style for scroll views within this hierarchy.
nonisolated func scrollEdgeEffectStyle( _ style: ScrollEdgeEffectStyle?, for edges: Edge.Set
Discussion
By default, a scroll view will render an automatic edge effect. You use this modifier to change rendered edge effect style.
ScrollView { LazyVStack { ForEach(data) { item in RowView(item) } } } .scrollEdgeEffectStyle(.hard)
See Also
Configuring scroll edge effects
Disables any scroll edge effects for scroll views within this hierarchy.
Beta
struct ScrollEdgeEffectStyle
A structure that defines the style of pocket a scroll view will have.
func safeAreaBar(edge:alignment:spacing:content:)
Renders the provided content appropriately to be displayed as a custom bar.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/scrollinputbehavior(_:for:)
#app-main)
- SwiftUI
- View
- scrollInputBehavior(_:for:)
Instance Method
scrollInputBehavior(_:for:)
Enables or disables scrolling in scrollable views when using particular inputs.
@MainActor @preconcurrency func scrollInputBehavior( _ behavior: ScrollInputBehavior, for input: ScrollInputKind
Parameters
behavior
Whether scrolling should be enabled or disabled for this input.
input
The input for which to enable or disable scrolling.
Discussion
In contrast to scrollDisabled(_:), this modifier will enable or disable scrolling only for particular inputs. The following, for instance, disables double-tap-to-scroll on watchOS while preserving the ability to scroll via touch and the Digital Crown:
ScrollView(...) .scrollInputBehavior(.disabled, for: .handGestureShortcut)
If scrollDisabled(true) has been applied to this view, scrolling will be disabled for all inputs and this modifier cannot be used to re-enable scrolling.
See Also
Managing scrolling for different inputs
struct ScrollInputKind
Inputs used to scroll views.
struct ScrollInputBehavior
A type that defines whether input should scroll a view.
https://developer.apple.com/documentation/swiftui/view/searchtoolbarbehavior(_:)
#app-main)
- SwiftUI
- View
- searchToolbarBehavior(_:) Beta
Instance Method
searchToolbarBehavior(_:)
Configures the behavior for search in the toolbar.
nonisolated
Discussion
This modifier can be used to change the default behavior of a search field that appears in the toolbar. Place this modifier after the searchable(text:isPresented:placement:prompt:) modifier that renders search in the toolbar.
On iPhone, the search field in the bottom toolbar can be configured to appear as a button-like control when inactive:
@State private var searchText = ""
NavigationStack { RecipeList() .searchable($searchText) .searchToolbarBehavior(.minimized) }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/sectionindexlabel(_:)
#app-main)
- SwiftUI
- View
- sectionIndexLabel(_:) Beta
Instance Method
sectionIndexLabel(_:)
Sets the label that is used in a section index to point to this section, typically only a single character long.
nonisolated
Show all declarations
Parameters
label
The label to display in the section index, or nil to display no label for this section.
Discussion
- See also
listSectionIndexVisibility(_:)
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/signinwithapplebuttonstyle(_:)
https://developer.apple.com/documentation/swiftui/view/spatialoverlay(alignment:content:)
#app-main)
- SwiftUI
- View
- spatialOverlay(alignment:content:) Beta
Instance Method
spatialOverlay(alignment:content:)
Adds secondary views within the 3D bounds of this view.
nonisolated
alignment: Alignment3D = .center,
Parameters
alignment
The alignment with a default value of center that you use to position the secondary view.
content
The view builder which produces views to occupy the same 3D space as this view. Multiple views provided by content are organized into a SpatialContainer.
Return Value
A view that adds content within the view’s 3D bounds.
Discussion
Multiple views provided by content are stacked depthwise.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/spatialoverlaypreferencevalue(:alignment::)
#app-main)
- SwiftUI
- View
- spatialOverlayPreferenceValue(_:alignment:_:) Beta
Instance Method
spatialOverlayPreferenceValue(_:alignment:_:)
Uses the specified preference value from the view to produce another view occupying the same 3D space of the first view.
nonisolated
_ key: K.Type, alignment: Alignment3D = .center,
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/storebutton(_:for:)
#app-main)
- SwiftUI
- View
- storeButton(_:for:)
Instance Method
storeButton(_:for:)
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
StoreKitSwiftUI
nonisolated func storeButton( _ visibility: Visibility, for buttonKinds: StoreButtonKind...
Parameters
visibility
The preferred visibility of the buttons.
buttonKinds
The type of store button.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
Declares the view as dependent on a collection of In-App Purchase products and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/storeproducttask(for:priority:action:)
#app-main)
- SwiftUI
- View
- storeProductTask(for:priority:action:)
Instance Method
storeProductTask(for:priority:action:)
Declares the view as dependent on an In-App Purchase product and returns a modified view.
StoreKitSwiftUI
nonisolated func storeProductTask( for id: Product.ID, priority: TaskPriority = .medium,
Parameters
id
The product ID to load from the App Store. The task restarts whenever this parameter changes.
priority
The task priority to use when creating the task.
action
The action to perform when the task’s state changes.
Discussion
Before a view modified with this method appears, a task will start in the background to load the product from the App Store. While the view is presented, the task will call action whenever the product changes or the task’s state changes.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on a collection of In-App Purchase products and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/storeproductstask(for:priority:action:)
https://developer.apple.com/documentation/swiftui/view/subscriptionintroductoryoffer(applyoffer:compactjws:)
#app-main)
- SwiftUI
- View
- subscriptionIntroductoryOffer(applyOffer:compactJWS:) Beta
Instance Method
subscriptionIntroductoryOffer(applyOffer:compactJWS:)
Selects the introductory offer eligibility preference to apply to a purchase a customer makes from a subscription store view.
StoreKitSwiftUI
nonisolated func subscriptionIntroductoryOffer(
Parameters
applyOffer
The system calls this function before drawing the given subscription product on the subscription store view. Return if the introductory offer should be applied to a given product, if any, to have system-provided UI reflect the discounted terms under the selected offer.
compactJWS
The system calls this function before processing a purchase, with the product to be purchased provided as a parameter. Return a compact JWS signature you generate on your server that validates the selected offer eligibility preference. Errors thrown from this closure will be surfaced via the onInAppPurchaseCompletion(perform:) modifier. For information about generating the JWS signature, see Generating JWS to sign App Store requests.
Discussion
Subscription stores within this view uses the introductory subscription offers to configure the appearance of the subscription plans displayed, when you use a system-provided SubscriptionStoreControlStyle to style the in-app subscription store. Standard ProductViewStyle instances don’t show introductory or promotional offers in UI, instead use SubscriptionStoreView.
Determine if the introductory offer should be displayed in the view and applied to the purchase using the applyOffer. If the signature passes validation, the system applies or removes the offer to the purchases according to the offer eligibility preference. If the signature fails validation, the purchase will fail with Product.PurchaseError.invalidOfferSignature.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/subscriptionofferviewbuttonvisibility(_:for:)
#app-main)
- SwiftUI
- View
- subscriptionOfferViewButtonVisibility(_:for:) Beta
Instance Method
subscriptionOfferViewButtonVisibility(_:for:)
StoreKitSwiftUI
nonisolated func subscriptionOfferViewButtonVisibility( _ visibility: Visibility, for buttonKinds: SubscriptionOfferViewButtonKind...
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/subscriptionofferviewdetailaction(_:)
#app-main)
- SwiftUI
- View
- subscriptionOfferViewDetailAction(_:) Beta
Instance Method
subscriptionOfferViewDetailAction(_:)
StoreKitSwiftUI
nonisolated
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/subscriptionofferviewstyle(_:)
#app-main)
- SwiftUI
- View
- subscriptionOfferViewStyle(_:) Beta
Instance Method
subscriptionOfferViewStyle(_:)
StoreKitSwiftUI
nonisolated
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/subscriptionpromotionaloffer(offer:compactjws:)
#app-main)
- SwiftUI
- View
- subscriptionPromotionalOffer(offer:compactJWS:) Beta
Instance Method
subscriptionPromotionalOffer(offer:compactJWS:)
Selects a promotional offer to apply to a purchase a customer makes from a subscription store view.
StoreKitSwiftUI
nonisolated func subscriptionPromotionalOffer(
Parameters
offer
The system calls this function before drawing the given subscription product on the subscription store view. Return the promotional offer to apply to the product, if any, to have system-provided UI reflect the discounted terms under the selected offer.
compactJWS
The system calls this function before processing a purchase, with the product to be purchased provided as a parameter, along with the selected subscription offer to be applied to the purchase. Return a compact JWS signature you generate on your server that validates the selected offer. Errors thrown from this closure will be surfaced via the onInAppPurchaseCompletion(perform:) modifier. For information about generating the JWS signature, see Generating JWS to sign App Store requests..
Discussion
Subscription stores within this view uses the specified subscription offer to configure the appearance of the subscription plans displayed, when you use a system-provided SubscriptionStoreControlStyle to style the in-app subscription store. Standard ProductViewStyle instances don’t show introductory or promotional offers in UI. Use the SubscriptionStoreView instead to show these offers in the UI.
If the signature passes validation for the offer you select, the system applies the offer to the purchase. If the signature fails validation for the offer you select, the purchase fails with Product.PurchaseError.invalidOfferSignature.
Promotional offers you select in this modifier overwrite any offers you specified in ancestor views.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/subscriptionpromotionaloffer(offer:signature:)
#app-main)
- SwiftUI
- View
- subscriptionPromotionalOffer(offer:signature:) Deprecated
Instance Method
subscriptionPromotionalOffer(offer:signature:)
Selects a promotional offer to apply to a purchase a customer makes from a subscription store view.
StoreKitSwiftUIiOS 17.4–26.0DeprecatediPadOS 17.4–26.0DeprecatedmacOS 14.4–26.0DeprecatedtvOS 17.4–26.0DeprecatedvisionOS 1.1–26.0DeprecatedwatchOS 10.4–26.0Deprecated
nonisolated func subscriptionPromotionalOffer(
Parameters
offer
The system calls this function before drawing the given subscription product on the subscription store view. Return the promotional offer to apply to the product, if any, to have system-provided UI reflect the discounted terms under the selected offer.
signature
The system calls this function before processing a purchase, with the product to be purchased provided as a parameter, along with the selected subscription offer to be applied to the purchase. Return a signature you generate on your server that validates the selected offer. Errors thrown from this closure will be surfaced via the onInAppPurchaseCompletion(perform:) modifier. For information about generating the signature, see Generating a signature for promotional offers.
Discussion
Subscription stores within this view uses the specified subscription offer to configure the appearance of the subscription plans displayed, when you use a system-provided SubscriptionStoreControlStyle to style the in-app subscription store. Standard ProductViewStyle instances don’t show introductory or promotional offers in UI. Use the SubscriptionStoreView instead to show these offers in the UI.
If the signature passes validation for the offer you select, the system applies the offer to the purchase. If the signature fails validation for the offer you select, the purchase fails with Product.PurchaseError.invalidOfferSignature.
Promotional offers you select in this modifier overwrite any offers you specified in ancestor views.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstorebuttonlabel(_:)
https://developer.apple.com/documentation/swiftui/view/subscriptionstorecontrolbackground(_:)
#app-main)
- SwiftUI
- View
- subscriptionStoreControlBackground(_:)
Instance Method
subscriptionStoreControlBackground(_:)
Set a standard effect to use for the background of subscription store view controls within the view.
StoreKitSwiftUI
nonisolated
Show all declarations
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstorecontrolicon(icon:)
#app-main)
- SwiftUI
- View
- subscriptionStoreControlIcon(icon:)
Instance Method
subscriptionStoreControlIcon(icon:)
Sets a view to use to decorate individual subscription options within a subscription store view.
StoreKitSwiftUI
nonisolated
Parameters
icon
A closure that takes a Product and Product.SubscriptionInfo and returns a view.
Discussion
You can adjust this view to provide a different appearance for each subscription option.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstorecontrolstyle(_:)
#app-main)
- SwiftUI
- View
- subscriptionStoreControlStyle(_:)
Instance Method
subscriptionStoreControlStyle(_:)
Sets the control style for subscription store views within a view.
StoreKitSwiftUI
nonisolated
Discussion
This view modifier set the style of controls for SubscriptionStoreView instances within a view.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstorecontrolstyle(_:placement:)
#app-main)
- SwiftUI
- View
- subscriptionStoreControlStyle(_:placement:)
Instance Method
subscriptionStoreControlStyle(_:placement:)
Sets the control style and control placement for subscription store views within a view.
StoreKitSwiftUI
nonisolated
_ style: S, placement: S.Placement
Parameters
style
The subscription store control style to use when drawing the subscription controls of SubscriptionStoreView instances within a view.
placement
The desired region of the subscription store view for placing the subscription controls.
Discussion
This modifier sets the style and placement of the subscription controls in any SubscriptionStoreView instance within a view.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstoreoptiongroupstyle(_:)
#app-main)
- SwiftUI
- View
- subscriptionStoreOptionGroupStyle(_:)
Instance Method
subscriptionStoreOptionGroupStyle(_:)
Sets the style subscription store views within this view use to display groups of subscription options.
StoreKitSwiftUI
nonisolated
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepickeritembackground(_:)
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepickeritembackground(_:in:)
#app-main)
- SwiftUI
- View
- subscriptionStorePickerItemBackground(_:in:)
Instance Method
subscriptionStorePickerItemBackground(_:in:)
Sets the background shape and style for subscription store view picker items within a view.
StoreKitSwiftUI
nonisolated func subscriptionStorePickerItemBackground( _ backgroundStyle: some ShapeStyle, in shape: some Shape
Parameters
backgroundStyle
A ShapeStyle that determines the background style for the subscription store view picker items.
shape
An instance of a type that conforms to Shape and determines the shape of the subscription store view picker items. Omit the shape parameter to use the default shape.
Discussion
Use this view modifier to customize the shape of the picker options in a subscription store view, as well as the background style.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepolicydestination(for:destination:)
#app-main)
- SwiftUI
- View
- subscriptionStorePolicyDestination(for:destination:)
Instance Method
subscriptionStorePolicyDestination(for:destination:)
Configures a view as the destination for a policy button action in subscription store views.
StoreKitSwiftUI
nonisolated func subscriptionStorePolicyDestination( for button: SubscriptionStorePolicyKind,
Parameters
button
The policy button to associate the URL with.
destination
The view to present when someone chooses to view the policy.
Discussion
Except on tvOS, you can also set a URL as the destination using subscriptionStorePolicyDestination(url:for:). If you do not set a destination, the system will use the automatic behavior. Check the documentation for the value you provide for button to understand the automatic behavior.
By default, the subscription store shows the & buttons if you set a destination for at least one policy. The policy that is not explicitly set will use the automatic behavior. You can override this behavior using the storeButton(_:for:) modifier, with policies as the second parameter.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepolicydestination(url:for:)
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepolicyforegroundstyle(_:)
#app-main)
- SwiftUI
- View
- subscriptionStorePolicyForegroundStyle(_:)
Instance Method
subscriptionStorePolicyForegroundStyle(_:)
Sets the style for the and buttons within a subscription store view.
StoreKitSwiftUI
nonisolated
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepolicyforegroundstyle(::)
#app-main)
- SwiftUI
- View
- subscriptionStorePolicyForegroundStyle(_:_:)
Instance Method
subscriptionStorePolicyForegroundStyle(_:_:)
Sets the primary and secondary style for the and buttons within a subscription store view.
StoreKitSwiftUI
nonisolated func subscriptionStorePolicyForegroundStyle( _ primary: some ShapeStyle, _ secondary: some ShapeStyle
Parameters
primary
The color or pattern to use for the and buttons
secondary
The color or pattern to use for the conjunction between the buttons in the policy section
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/subscriptionstoresigninaction(_:)
#app-main)
- SwiftUI
- View
- subscriptionStoreSignInAction(_:)
Instance Method
subscriptionStoreSignInAction(_:)
Adds an action to perform when a person uses the sign-in button on a subscription store view within a view.
StoreKitSwiftUI
nonisolated
Parameters
action
The action to perform. Pass nil to remove the sign in action for subscription stores within this view. The default value is nil.
Discussion
You can only have one sign in action for a view. If an ancestor view specifies a sign in action, using this modifier will replace the ancestor’s sign in action.
If the value is nil, subscription stores will never show a sign in button. You can also hide the sign in button without removing the action by using the storeButton(_:for:) modifier, providing signIn as the button kind.
See Also
Interacting with the App Store and Apple Music
Presents a StoreKit overlay when a given condition is true.
Display the refund request sheet for the given transaction.
Presents a sheet that enables users to redeem subscription offer codes that you configure in App Store Connect.
Initiates the process of presenting a sheet with subscription offers for Apple Music when the isPresented binding is true.
Declares the view as dependent on the entitlement of an In-App Purchase product, and returns a modified view.
Add a function to call before initiating a purchase from StoreKit view within this view, providing a set of options for the purchase.
Add an action to perform when a purchase initiated from a StoreKit view within this view completes.
Add an action to perform when a user triggers the purchase button on a StoreKit view within this view.
Adds a standard border to an in-app purchase product’s icon .
Sets the style for In-App Purchase product views within a view.
Configure the visibility of labels displaying an in-app purchase product description within the view.
Specifies the visibility of auxiliary buttons that store view and subscription store view instances may use.
Declares the view as dependent on an In-App Purchase product and returns a modified view.
https://developer.apple.com/documentation/swiftui/view/symbolcolorrenderingmode(_:)
#app-main)
- SwiftUI
- View
- symbolColorRenderingMode(_:) Beta
Instance Method
symbolColorRenderingMode(_:)
Sets the color rendering mode for symbol images.
nonisolated
Parameters
mode
The color rendering mode, or nil to use the default mode.
Return Value
A view that specifies the color rendering mode for symbol images.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/symbolvariablevaluemode(_:)
https://developer.apple.com/documentation/swiftui/view/tabbarminimizebehavior(_:)
#app-main)
- SwiftUI
- View
- tabBarMinimizeBehavior(_:) Beta
Instance Method
tabBarMinimizeBehavior(_:)
Sets the behavior for tab bar minimization.
nonisolated
Parameters
behavior
The minimize behavior.
Discussion
The following TabView minimizes its tab bar when scrolling in the ‘Numbers’ or ‘Alerts’ tabs on iPhone.
struct ContentView: View { var body: some View { TabView { Tab("Numbers", systemImage: "number") { ScrollView { ForEach(0 ..< 50) { index in Text("(index)") .padding() } } } Tab("Alerts", systemImage: "bell") { AlertsView() } } .tabBarMinimizeBehavior(.onScrollDown) } }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/tabviewbottomaccessory(content:)
#app-main)
- SwiftUI
- View
- tabViewBottomAccessory(content:) Beta
Instance Method
tabViewBottomAccessory(content:)
nonisolated
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/tabletopgame(_:parent:automaticupdate:)
https://developer.apple.com/documentation/swiftui/view/tabletopgame(_:parent:automaticupdate:interaction:)
https://developer.apple.com/documentation/swiftui/view/textcontenttype(_:)
#app-main)
- SwiftUI
- View
- textContentType(_:)
Instance Method
textContentType(_:)
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on macOS.
nonisolated
Show all declarations
Parameters
textContentType
One of the content types available in the NSTextContentType structure that identify the semantic meaning expected for a text-entry area.
Discussion
Use this method to set the content type for input text. For example, you can configure a TextField for the entry of a username:
TextField("Enter your username", text: $username) .textContentType(.username)
See Also
Managing text entry
Sets whether to disable autocorrection for this view.
var autocorrectionDisabled: Bool
A Boolean value that determines whether the view hierarchy has auto-correction enabled.
Sets the keyboard type for this view.
Configures the behavior in which scrollable content interacts with the software keyboard.
Sets how often the shift key in the keyboard is automatically enabled.
struct TextInputAutocapitalization
The kind of autocapitalization behavior applied during text input.
Associates a fully formed string with the value of this view when used as a text input suggestion
Configures the text input suggestions for this view.
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on a watchOS device.
Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on an iOS or tvOS device.
struct TextInputFormattingControlPlacement
A structure defining the system text formatting controls available on each platform.
Beta
https://developer.apple.com/documentation/swiftui/view/textinputformattingcontrolvisibility(_:for:)
#app-main)
- SwiftUI
- View
- textInputFormattingControlVisibility(_:for:) Beta
Instance Method
textInputFormattingControlVisibility(_:for:)
Define which system text formatting controls are available.
@MainActor @preconcurrency func textInputFormattingControlVisibility( _ visibility: Visibility, for placement: TextInputFormattingControlPlacement.Set
Parameters
visibility
Whether the control may become visible to the user
placement
The onscreen control to modify
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/textrenderer(_:)
#app-main)
- SwiftUI
- View
- textRenderer(_:)
Instance Method
textRenderer(_:)
Returns a new view such that any text views within it will use renderer to draw themselves.
nonisolated
Parameters
renderer
The renderer value.
Return Value
A new view that will use renderer to draw its text views.
See Also
Rendering text
Creating visual effects with SwiftUI
Add scroll effects, rich color treatments, custom transitions, and advanced effects using shaders and a text renderer.
protocol TextAttribute
A value that you can attach to text views and that text renderers can query.
protocol TextRenderer
A value that can replace the default text view rendering behavior.
struct TextProxy
A proxy for a text view that custom text renderers use.
https://developer.apple.com/documentation/swiftui/view/textselectionaffinity(_:)
#app-main)
- SwiftUI
- View
- textSelectionAffinity(_:)
Instance Method
textSelectionAffinity(_:)
Sets the direction of a selection or cursor relative to a text character.
nonisolated
Parameters
affinity
The text selection affinity strategy to apply.
Return Value
A view that uses the specified selection affinity strategy.
Discussion
Use this modifier when you need to handle line breaks in a specific way, alter cursor movement or deal with bidirectional text (text that contains both LTR and RTL scripts, like English and Arabic combined).
Selection affinity also determines whether, for example, the insertion point appears after the last character on a line or before the first character on the following line in cases where text wraps across line boundaries.
Given the scenario hello|مرحبا, where | represents the cursor & مرحبا represents “hello” in Arabic, the ambiguity arises because:
-
If the cursor is associated with the end of the English word, it would be as if you’re continuing to type in English (LTR).
-
If the cursor is associated with the beginning of the Arabic word, it would also be as if you’re continuing to type in Arabic (RTL).
This modifier helps resolve this ambiguity by determining the direction or association of the cursor relative to the surrounding text.
The following example shows how you would specify a specific selection affinity on the given hierarchy:
struct SuggestionTextEditor: View { @State var text: String = "" @State var selection: TextSelection? = nil
var body: some View { VStack { TextEditor(text: $text, selection: $selection) // A helper view that offers live suggestions based on selection. SuggestionsView( substrings: getSubstrings(text: text, indices: selection?.indices)) } .textSelectionAffinity(.upstream) }
private func getSubstrings( text: String, indices: TextSelection.Indices?
// Resolve substrings representing the current selection... } }
struct SuggestionsView: View { ... }
See Also
Selecting text
Controls whether people can select text within this view.
protocol TextSelectability
A type that describes the ability to select text.
struct TextSelection
Represents a selection of text.
var textSelectionAffinity: TextSelectionAffinity
A representation of the direction or association of a selection or cursor relative to a text character. This concept becomes much more prominent when dealing with bidirectional text (text that contains both LTR and RTL scripts, like English and Arabic combined).
enum TextSelectionAffinity
struct AttributedTextSelection
Represents a selection of attributed text.
Beta
https://developer.apple.com/documentation/swiftui/view/tipbackground(_:)
#app-main)
- SwiftUI
- View
- tipBackground(_:)
Instance Method
tipBackground(_:)
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
nonisolated
Parameters
style
An instance of a type that conforms to ShapeStyle that SwiftUI draws behind the modified view.
Return Value
A view with the specified style drawn behind it.
See Also
Providing tips
Presents a popover tip on the modified view.
Sets the corner radius for an inline tip view.
Sets the size for a tip’s image.
Sets the given style for TipView within the view hierarchy.
Sets the style for a tip’s image.
https://developer.apple.com/documentation/swiftui/view/tipcornerradius(_:antialiased:)
#app-main)
- SwiftUI
- View
- tipCornerRadius(_:antialiased:)
Instance Method
tipCornerRadius(_:antialiased:)
Sets the corner radius for an inline tip view.
nonisolated func tipCornerRadius( _ cornerRadius: CGFloat, antialiased: Bool = true
See Also
Providing tips
Presents a popover tip on the modified view.
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
Sets the size for a tip’s image.
Sets the given style for TipView within the view hierarchy.
Sets the style for a tip’s image.
https://developer.apple.com/documentation/swiftui/view/tipimagesize(_:)
#app-main)
- SwiftUI
- View
- tipImageSize(_:)
Instance Method
tipImageSize(_:)
Sets the size for a tip’s image.
nonisolated
See Also
Providing tips
Presents a popover tip on the modified view.
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
Sets the corner radius for an inline tip view.
Sets the given style for TipView within the view hierarchy.
Sets the style for a tip’s image.
https://developer.apple.com/documentation/swiftui/view/tipimagestyle(_:)
#app-main)
- SwiftUI
- View
- tipImageStyle(_:)
Instance Method
tipImageStyle(_:)
Sets the style for a tip’s image.
nonisolated
See Also
Providing tips
Presents a popover tip on the modified view.
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
Sets the corner radius for an inline tip view.
Sets the size for a tip’s image.
Sets the given style for TipView within the view hierarchy.
https://developer.apple.com/documentation/swiftui/view/tipimagestyle(::)
#app-main)
- SwiftUI
- View
- tipImageStyle(_:_:)
Instance Method
tipImageStyle(_:_:)
Sets the style for a tip’s image.
nonisolated
_ primary: S1, _ secondary: S2
See Also
Providing tips
Presents a popover tip on the modified view.
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
Sets the corner radius for an inline tip view.
Sets the size for a tip’s image.
Sets the given style for TipView within the view hierarchy.
https://developer.apple.com/documentation/swiftui/view/tipimagestyle(::_:)
#app-main)
- SwiftUI
- View
- tipImageStyle(_:_:_:)
Instance Method
tipImageStyle(_:_:_:)
Sets the style for a tip’s image.
nonisolated
_ primary: S1, _ secondary: S2, _ tertiary: S3
See Also
Providing tips
Presents a popover tip on the modified view.
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
Sets the corner radius for an inline tip view.
Sets the size for a tip’s image.
Sets the given style for TipView within the view hierarchy.
https://developer.apple.com/documentation/swiftui/view/tipviewstyle(_:)
#app-main)
- SwiftUI
- View
- tipViewStyle(_:)
Instance Method
tipViewStyle(_:)
Sets the given style for TipView within the view hierarchy.
nonisolated
Parameters
style
The style to set.
Return Value
A view that uses the specified style on its child views.
Discussion
For more information on styling tips, see TipKit/TipViewStyle.
See Also
Providing tips
Presents a popover tip on the modified view.
Sets the tip’s view background to a style. Currently this only applies to inline tips, not popover tips.
Sets the corner radius for an inline tip view.
Sets the size for a tip’s image.
Sets the style for a tip’s image.
https://developer.apple.com/documentation/swiftui/view/toolbaritemhidden(_:)
#app-main)
- SwiftUI
- View
- toolbarItemHidden(_:)
Instance Method
toolbarItemHidden(_:)
Hides an individual view within a control group toolbar item.
nonisolated
Parameters
hidden
Whether the view in a control group toolbar item is hidden.
Discussion
Use this modifier to hide individual views of a ControlGroup without hiding the entire group. On macOS and iOS, hidden items will be displayed during user customization.
The following example displays a collaboration button in a group when there is an active collaboration session.
struct ContentView { @State private var inCollaboration = false
var body: some View { BrowserView() .toolbar(id: "browserToolbar") { ToolbarItem(id: "share") { ControlGroup { ShareButton() CollaborationButton() .toolbarItemHidden(!inCollaboration) } } } } }
https://developer.apple.com/documentation/swiftui/view/transactiontask(_:action:)
#app-main)
- SwiftUI
- View
- transactionTask(_:action:)
Instance Method
transactionTask(_:action:)
Provides a task to perform before this view appears
SecureElementCredentialSwiftUI
nonisolated func transactionTask( _ configuration: CredentialTransaction.Configuration?,
Parameters
configuration
A configuration containing information about the transaction task. When the task is completed or an error is encountered while performing the task, the system invalidates this configuration, and the CredentialTransaction is invalidated.
action
A closure that will be called when isPerformingTransaction is true. It provides a CredentialTransaction instance that can be used to perform transactions.
Discussion
This task provides an instance of a CredentialTransaction to be used to perform transactions.
A typical client should use the APIs in the following sequence:
-
acquirePresentmentIntentAssertion()prior to showing any proprietary payment UI -
relinquish()the assertion before invoking the transaction API -
configuration.invalidate()after presenting the credential -
Optionally,
acquirePresentmentIntentAssertion()to finish up any proprietary payment UI -
relinquish()the assertion
For example:
struct TransactionView: View { @State private var configuration: CredentialTransaction.Configuration? private var assertion: PresentmentIntentAssertion // acquirePresentmentIntentAssertion() before transitioning into this view (step 1) private var activeSession: CredentialSession private var selectedCredential: Credential
var body: some View { VStack { Button("Perform Transaction") { guard let configuration else { configuration = activeSession.configuration() return }
configuration.invalidate() // step 3 // Optional assertion = try await session.acquirePresentmentIntentAssertion() // step 4 // handle any proprietary UI try await assertion.relinquish() // step 5 // Optional end } .transactionTask(configuration) { transaction in do { try await assertion.relinquish() // step 2 try await transaction.performTransaction(using: selectedCredential) } catch { // code to handle error } } } } }
See Also
Accessing Apple Pay and Wallet
A view that displays a button for identity verification.
Sets the button’s style.
Sets the style to be used by the button. (see PKAddPassButtonStyle).
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
Sets the action on the PayLaterView. See PKPayLaterAction.
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Sets the style to be used by the button. (see PKIdentityButtonStyle).
https://developer.apple.com/documentation/swiftui/view/translationpresentation(ispresented:text:attachmentanchor:arrowedge:replacementaction:)
#app-main)
- SwiftUI
- View
- translationPresentation(isPresented:text:attachmentAnchor:arrowEdge:replacementAction:)
Instance Method
translationPresentation(isPresented:text:attachmentAnchor:arrowEdge:replacementAction:)
Presents a translation popover when a given condition is true.
TranslationSwiftUI
nonisolated func translationPresentation(
text: String, attachmentAnchor: PopoverAttachmentAnchor = .rect(.bounds), arrowEdge: Edge = .top,
Parameters
isPresented
A binding to a Boolean value that determines whether to present the popover.
text
The text to be translated. Changing this after the popover presents has no effect.
attachmentAnchor
The positioning anchor that defines the attachment point of the popover. The default is bounds.
arrowEdge
The edge of the attachmentAnchor that defines the location of the popover’s arrow in macOS. The default is Edge.top. iOS ignores this parameter.
replacementAction
An optional action to perform when someone interacts with the “Replace with Translation” button. The “Replace with Translation” button appears when you provide this action.
Discussion
Use this method to show a system UI translation popover when the translationVisible Boolean variable is true. Attach this view modifier to the containing view holding the text to translate. Then set the isPresented Boolean binding to true when you want the popover to display. When you do, a system UI translation popover appears offering a translation.
In the example below, the popover appears when the user toggles the translationVisible state variable by pressing the Translate button.
struct ContentView: View { @State private var translationVisible = false private var originalText = "Hallo, Welt!"
var body: some View { VStack { Text(verbatim: originalText) .translationPresentation(isPresented: $translationVisible, text: originalText) Button("Translate") { translationVisible.toggle() } } } }
To replace the original text with the translation, pass in a trailing closure to the replacementAction parameter. When you do, a Replace with Translation button appears in the system UI. When the user taps this button, the closure returns a translation of the text as a string. Use that string to update the original text with the translated text as shown below:
struct ReplaceTranslation: View { @State private var translationVisible = false @State private var originalText = "Hallo, Welt!"
var body: some View { VStack(spacing: 20) { TextField("Text to translate", text: $originalText, axis: .vertical) .textFieldStyle(.roundedBorder) .translationPresentation(isPresented: $translationVisible, text: originalText) { translatedString in // Update the original text with the translated result. originalText = translatedString } Button("Translate") { translationVisible.toggle() } } .padding() } }
If the system can’t detect the source language, it asks the user to select the language to translate from. For a list of supported languages see LanguageAvailability.supportedLanguages.
While this function does support long strings of text, it works best with short ones (no more than a couple of sentences or phrases in length).
See Also
Showing a translation
Adds a task to perform before this view appears or when the translation configuration changes.
Adds a task to perform before this view appears or when the specified source or target languages change.
https://developer.apple.com/documentation/swiftui/view/translationtask(_:action:)
#app-main)
- SwiftUI
- View
- translationTask(_:action:)
Instance Method
translationTask(_:action:)
Adds a task to perform before this view appears or when the translation configuration changes.
TranslationSwiftUI
nonisolated func translationTask( _ configuration: TranslationSession.Configuration?,
Parameters
configuration
A configuration for a TranslationSession. When this configuration is non-nil and changes. the action runs providing an instance of TranslationSession to perform translations.
action
A closure that runs when the configuration is non-nil and changes. This closure runs when the view appears if configuration is initially non-nil. It provides a TranslationSession instance to perform one or multiple translations.
Discussion
This task provides an instance of TranslationSession to use in translations. Whenever TranslationSession/Configuration changes and isn’t nil, the closure action runs, providing a TranslationSession instance to perform one or more translations.
For example, you can create a TranslationSession/Configuration in response to a button press to trigger translation:
struct ContentView: View { @State private var sourceText = "Hallo, Welt!" var sourceLanguage: Locale.Language? var targetLanguage: Locale.Language?
@State private var targetText: String? @State private var configuration: TranslationSession.Configuration?
var body: some View { VStack { Text(targetText ?? sourceText) Button("Translate") { guard configuration == nil else { configuration?.invalidate() return }
configuration = TranslationSession.Configuration( source: sourceLanguage, target: targetLanguage) } .translationTask(configuration) { session in Task { @MainActor in do { let response = try await session.translate(sourceText) targetText = response.targetText } catch { // code to handle error } } } } } }
The system throws a fatalError if you use a TranslationSession instance after the view it attaches to disappears, or if you use it after changing the configuration, causing the action closure to provide a new TranslationSession instance.
See Also
Showing a translation
Presents a translation popover when a given condition is true.
Adds a task to perform before this view appears or when the specified source or target languages change.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/translationtask(source:target:action:)
#app-main)
- SwiftUI
- View
- translationTask(source:target:action:)
Instance Method
translationTask(source:target:action:)
Adds a task to perform before this view appears or when the specified source or target languages change.
TranslationSwiftUI
nonisolated func translationTask( source: Locale.Language? = nil, target: Locale.Language? = nil,
Parameters
source
The language the source content is in. If this is nil the session tries to identify the language, and prompt the user to pick the source language if it’s unclear. All text translated within the session should be in the same source language. Changing this value cancels previous tasks and creates a new one to perform translations again.
target
The language to translate content into. A nil value means the session picks a target according to the user’s Locale.preferredLanguages, and the source. Changing this value cancels previous tasks and create a new one to perform translations again.
action
A closure that runs when the view first appears, and when source or target change. It provides a TranslationSession instance to perform one or multiple translations.
Discussion
This task provides an instance of TranslationSession to use to perform translations.
If you need to perform new translations again with the same source and target language, it’s better to use translationTask(_:action:) and call TranslationSession/Configuration/invalidate().
For example, you can translate when content appears:
struct ContentView: View { var sourceText = "Hallo, Welt!" var sourceLanguage: Locale.Language? var targetLanguage: Locale.Language?
@State private var targetText: String?
var body: some View { Text(targetText ?? sourceText) .translationTask( source: sourceLanguage, target: targetLanguage ) { session in Task { @MainActor in do { let response = try await session.translate(sourceText) targetText = response.targetText } catch { // code to handle error } } } } }
The system throws a fatalError if you use a TranslationSession instance after the view it attaches to disappears, or if you use it after changing the source or target parameters, causing the action closure to provide a new TranslationSession instance.
See Also
Showing a translation
Presents a translation popover when a given condition is true.
Adds a task to perform before this view appears or when the translation configuration changes.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/verifyidentitywithwalletbuttonstyle(_:)
#app-main)
- SwiftUI
- View
- verifyIdentityWithWalletButtonStyle(_:)
Instance Method
verifyIdentityWithWalletButtonStyle(_:)
Sets the style to be used by the button. (see PKIdentityButtonStyle).
PassKitSwiftUI
nonisolated
See Also
Accessing Apple Pay and Wallet
A view that displays a button for identity verification.
Sets the button’s style.
Sets the style to be used by the button. (see PKAddPassButtonStyle).
Called when a user has entered or updated a coupon code. This is required if the user is being asked to provide a coupon code.
Called when a payment method has changed and asks for an update payment request. If this modifier isn’t provided Wallet will assume the payment method is valid.
Called when a user selected a shipping address. This is required if the user is being asked to provide a shipping contact.
Called when a user selected a shipping method. This is required if the user is being asked to provide a shipping method.
Sets the action on the PayLaterView. See PKPayLaterAction.
Sets the display style on the PayLaterView. See PKPayLaterDisplayStyle.
Sets the style to be used by the button. (see PayWithApplePayButtonStyle).
Provides a task to perform before this view appears
https://developer.apple.com/documentation/swiftui/view/webviewbackforwardnavigationgestures(_:)
#app-main)
- SwiftUI
- View
- webViewBackForwardNavigationGestures(_:)
Instance Method
webViewBackForwardNavigationGestures(_:)
Determines whether horizontal swipe gestures trigger backward and forward page navigation.
WebKitSwiftUI
nonisolated
https://developer.apple.com/documentation/swiftui/view/webviewcontentbackground(_:)
#app-main)
- SwiftUI
- View
- webViewContentBackground(_:)
Instance Method
webViewContentBackground(_:)
Specifies the visibility of the webpage’s natural background color within this view.
WebKitSwiftUI
nonisolated
Parameters
visibility
The visibility to use for the background.
Discussion
By default, WebViews are opaque, and use the page’s natural background color as their background color. Use this modifier if you would like to not use this behavior and instead provide a custom background using SwiftUI.
https://developer.apple.com/documentation/swiftui/view/webviewcontextmenu(menu:)
https://developer.apple.com/documentation/swiftui/view/webviewelementfullscreenbehavior(_:)
#app-main)
- SwiftUI
- View
- webViewElementFullscreenBehavior(_:)
Instance Method
webViewElementFullscreenBehavior(_:)
Determines whether a web view can display content full screen.
WebKitSwiftUI
nonisolated
https://developer.apple.com/documentation/swiftui/view/webviewlinkpreviews(_:)
#app-main)
- SwiftUI
- View
- webViewLinkPreviews(_:)
Instance Method
webViewLinkPreviews(_:)
Determines whether pressing a link displays a preview of the destination for the link.
WebKitSwiftUI
nonisolated
https://developer.apple.com/documentation/swiftui/view/webviewmagnificationgestures(_:)
#app-main)
- SwiftUI
- View
- webViewMagnificationGestures(_:)
Instance Method
webViewMagnificationGestures(_:)
Determines whether magnify gestures change the view’s magnification.
WebKitSwiftUI
nonisolated
https://developer.apple.com/documentation/swiftui/view/webviewonscrollgeometrychange(for:of:action:)
#app-main)
- SwiftUI
- View
- webViewOnScrollGeometryChange(for:of:action:)
Instance Method
webViewOnScrollGeometryChange(for:of:action:)
Adds an action to be performed when a value, created from a scroll geometry, changes.
WebKitSwiftUI
nonisolated
for type: T.Type,
Parameters
type
The type of value transformed from a ScrollGeometry.
transform
A closure that transforms a ScrollGeometry to your type.
action
A closure to run when the transformed data changes.
Discussion
https://developer.apple.com/documentation/swiftui/view/webviewscrollinputbehavior(_:for:)
https://developer.apple.com/documentation/swiftui/view/webviewscrollposition(_:)
#app-main)
- SwiftUI
- View
- webViewScrollPosition(_:)
Instance Method
webViewScrollPosition(_:)
Associates a binding to a scroll position with the web view.
WebKitSwiftUI
nonisolated
Discussion
https://developer.apple.com/documentation/swiftui/view/webviewtextselection(_:)
https://developer.apple.com/documentation/swiftui/view/windowresizeanchor(_:)
https://developer.apple.com/documentation/swiftui/view/workoutpreview(_:ispresented:)
#app-main)
- SwiftUI
- View
- workoutPreview(_:isPresented:)
Instance Method
workoutPreview(_:isPresented:)
Presents a preview of the workout contents as a modal sheet
WorkoutKitSwiftUI
nonisolated func workoutPreview( _ workout: WorkoutPlan,
Parameters
workout
The WorkoutContainer the preview displays
isPresented
A binding to a Boolean value that determines whether to present the preview
Discussion
struct WorkoutPreviewer: View { let workout: WorkoutPlan @State var presented: Bool = false var body: some View { Button { isPresented = true } label: { WorkoutContainerView(workout) } .workoutPreview(workout, isPresented: $presented) } }
See Also
Accessing health data
Asynchronously requests permission to read a data type that requires per-object authorization (such as vision prescriptions).
Requests permission to read the specified HealthKit data types.
Requests permission to save and read the specified HealthKit data types.
https://developer.apple.com/documentation/swiftui/view/writingdirection(strategy:)
#app-main)
- SwiftUI
- View
- writingDirection(strategy:) Beta
Instance Method
writingDirection(strategy:)
A modifier for the default text writing direction strategy in the view hierarchy.
nonisolated
Discussion
To control the writing direction explicitly, choose the layoutBased mode and set the layoutDirection to the appropriate value.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/writingtoolsaffordancevisibility(_:)
https://developer.apple.com/documentation/swiftui/view/writingtoolsbehavior(_:)
https://developer.apple.com/documentation/swiftui/dynamicviewcontent
- SwiftUI
- DynamicViewContent
Protocol
DynamicViewContent
A type of view that generates views from an underlying collection of data.
Topics
Managing the data
var data: Self.Data
The collection of underlying data.
Required
associatedtype Data : Collection
The type of the underlying collection of data.
Responding to updates
Sets the deletion action for the dynamic view. You must delete the corresponding item within action, as it will be called after the row has already been removed from the List.
Sets the insert action for the dynamic view.
Sets the move action for the dynamic view.
Deprecated symbols
Deprecated
Instance Methods
func onInsert(of:perform:)
Relationships
Inherits From
View
Conforming Types
-
ForEachConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable, andContentconforms toView. -
ModifiedContentConforms whenContentconforms toDynamicViewContentandModifierconforms toViewModifier.
See Also
Iterating over dynamic data
struct ForEach
A structure that computes views on demand from an underlying collection of identified data.
struct ForEachSectionCollection
A collection which allows a view to be treated as a collection of its sections in a for each loop.
struct ForEachSubviewCollection
A collection which allows a view to be treated as a collection of its subviews in a for each loop.
https://developer.apple.com/documentation/swiftui/insettableshape
https://developer.apple.com/documentation/swiftui/nsviewcontrollerrepresentable
https://developer.apple.com/documentation/swiftui/nsviewrepresentable
- SwiftUI
- NSViewRepresentable
Protocol
NSViewRepresentable
A wrapper that you use to integrate an AppKit view into your SwiftUI view hierarchy.
@MainActor @preconcurrency protocol NSViewRepresentable : View where Self.Body == Never
Overview
Use an NSViewRepresentable instance to create and manage an NSView object in your SwiftUI interface. Adopt this protocol in one of your app’s custom instances, and use its methods to create, update, and tear down your view. The creation and update processes parallel the behavior of SwiftUI views, and you use them to configure your view with your app’s current state information. Use the teardown process to remove your view cleanly from your SwiftUI. For example, you might use the teardown process to notify other objects that the view is disappearing.
To add your view into your SwiftUI interface, create your NSViewRepresentable instance and add it to your SwiftUI interface. The system calls the methods of your representable instance at appropriate times to create and update the view. The following example shows the inclusion of a custom MyRepresentedCustomView struct in the view hierarchy.
struct ContentView: View { var body: some View { VStack { Text("Global Sales") MyRepresentedCustomView() } } }
The system doesn’t automatically communicate changes occurring within your view controller to other parts of your SwiftUI interface. When you want your view controller to coordinate with other SwiftUI views, you must provide a Coordinator object to facilitate those interactions. For example, you use a coordinator to forward target-action and delegate messages from your view controller to any SwiftUI views.
Topics
Creating and updating the view
Creates the view object and configures its initial state.
Required
func updateNSView(Self.NSViewType, context: Self.Context)
Updates the state of the specified view with new information from SwiftUI.
typealias Context
associatedtype NSViewType : NSView
The type of view to present.
Specifying a size
Given a proposed size, returns the preferred size of the composite view.
Required Default implementation provided.
Cleaning up the view
static func dismantleNSView(Self.NSViewType, coordinator: Self.Coordinator)
Cleans up the presented AppKit view (and coordinator) in anticipation of their removal.
Providing a custom coordinator object
Creates the custom instance that you use to communicate changes from your view to other parts of your SwiftUI interface.
associatedtype Coordinator = Void
A type to coordinate with the view.
Performing layout
typealias LayoutOptions
Relationships
Inherits From
View
See Also
Adding AppKit views to SwiftUI view hierarchies
struct NSViewRepresentableContext
Contextual information about the state of the system that you use to create and update your AppKit view.
protocol NSViewControllerRepresentable
A wrapper that you use to integrate an AppKit view controller into your SwiftUI interface.
struct NSViewControllerRepresentableContext
Contextual information about the state of the system that you use to create and update your AppKit view controller.
https://developer.apple.com/documentation/swiftui/shape
https://developer.apple.com/documentation/swiftui/shapeview
- SwiftUI
- ShapeView
Protocol
ShapeView
A view that provides a shape that you can use for drawing operations.
Overview
Use this type with the drawing methods on Shape to apply multiple fills and/or strokes to a shape. For example, the following code applies a fill and stroke to a capsule shape:
Capsule() .fill(.yellow) .stroke(.blue, lineWidth: 8)
Topics
Getting the shape
var shape: Self.Content
The shape that this type draws and provides for other drawing operations.
Required
associatedtype Content : Shape
The type of shape this can provide.
Modify the shape
Fills this shape with a color or gradient.
Traces the outline of this shape with a color or gradient.
Returns a view that’s the result of insetting this view by half of its style’s line width.
Returns a view that’s the result of filling an inner stroke of this view with the content you supply.
Relationships
Inherits From
View
Conforming Types
FillShapeViewStrokeBorderShapeViewStrokeShapeView
See Also
Defining shape behavior
protocol Shape
A 2D shape that you can use when drawing a view.
struct AnyShape
A type-erased shape value.
enum ShapeRole
Ways of styling a shape.
struct StrokeStyle
The characteristics of a stroke that traces a path.
struct StrokeShapeView
A shape provider that strokes its shape.
struct StrokeBorderShapeView
A shape provider that strokes the border of its shape.
struct FillStyle
A style for rasterizing vector shapes.
struct FillShapeView
A shape provider that fills its shape.
https://developer.apple.com/documentation/swiftui/uiviewcontrollerrepresentable
- SwiftUI
- UIViewControllerRepresentable
Protocol
UIViewControllerRepresentable
A view that represents a UIKit view controller.
@MainActor @preconcurrency protocol UIViewControllerRepresentable : View where Self.Body == Never
Overview
Use a UIViewControllerRepresentable instance to create and manage a UIViewController object in your SwiftUI interface. Adopt this protocol in one of your app’s custom instances, and use its methods to create, update, and tear down your view controller. The creation and update processes parallel the behavior of SwiftUI views, and you use them to configure your view controller with your app’s current state information. Use the teardown process to remove your view controller cleanly from your SwiftUI. For example, you might use the teardown process to notify other objects that the view controller is disappearing.
To add your view controller into your SwiftUI interface, create your UIViewControllerRepresentable instance and add it to your SwiftUI interface. The system calls the methods of your custom instance at appropriate times.
The system doesn’t automatically communicate changes occurring within your view controller to other parts of your SwiftUI interface. When you want your view controller to coordinate with other SwiftUI views, you must provide a Coordinator instance to facilitate those interactions. For example, you use a coordinator to forward target-action and delegate messages from your view controller to any SwiftUI views.
Topics
Creating and updating the view controller
Creates the view controller object and configures its initial state.
Required
func updateUIViewController(Self.UIViewControllerType, context: Self.Context)
Updates the state of the specified view controller with new information from SwiftUI.
typealias Context
associatedtype UIViewControllerType : UIViewController
The type of view controller to present.
Specifying a size
Given a proposed size, returns the preferred size of the composite view.
Required Default implementation provided.
Cleaning up the view controller
static func dismantleUIViewController(Self.UIViewControllerType, coordinator: Self.Coordinator)
Cleans up the presented view controller (and coordinator) in anticipation of their removal.
Providing a custom coordinator object
Creates the custom instance that you use to communicate changes from your view controller to other parts of your SwiftUI interface.
associatedtype Coordinator = Void
A type to coordinate with the view controller.
Performing layout
typealias LayoutOptions
Relationships
Inherits From
View
See Also
Adding UIKit views to SwiftUI view hierarchies
protocol UIViewRepresentable
A wrapper for a UIKit view that you use to integrate that view into your SwiftUI view hierarchy.
struct UIViewRepresentableContext
Contextual information about the state of the system that you use to create and update your UIKit view.
struct UIViewControllerRepresentableContext
Contextual information about the state of the system that you use to create and update your UIKit view controller.
https://developer.apple.com/documentation/swiftui/uiviewrepresentable
- SwiftUI
- UIViewRepresentable
Protocol
UIViewRepresentable
A wrapper for a UIKit view that you use to integrate that view into your SwiftUI view hierarchy.
@MainActor @preconcurrency protocol UIViewRepresentable : View where Self.Body == Never
Overview
Use a UIViewRepresentable instance to create and manage a UIView object in your SwiftUI interface. Adopt this protocol in one of your app’s custom instances, and use its methods to create, update, and tear down your view. The creation and update processes parallel the behavior of SwiftUI views, and you use them to configure your view with your app’s current state information. Use the teardown process to remove your view cleanly from your SwiftUI. For example, you might use the teardown process to notify other objects that the view is disappearing.
To add your view into your SwiftUI interface, create your UIViewRepresentable instance and add it to your SwiftUI interface. The system calls the methods of your representable instance at appropriate times to create and update the view. The following example shows the inclusion of a custom MyRepresentedCustomView structure in the view hierarchy.
struct ContentView: View { var body: some View { VStack { Text("Global Sales") MyRepresentedCustomView() } } }
The system doesn’t automatically communicate changes occurring within your view to other parts of your SwiftUI interface. When you want your view to coordinate with other SwiftUI views, you must provide a Coordinator instance to facilitate those interactions. For example, you use a coordinator to forward target-action and delegate messages from your view to any SwiftUI views.
Topics
Creating and updating the view
Creates the view object and configures its initial state.
Required
func updateUIView(Self.UIViewType, context: Self.Context)
Updates the state of the specified view with new information from SwiftUI.
typealias Context
associatedtype UIViewType : UIView
The type of view to present.
Specifying a size
Given a proposed size, returns the preferred size of the composite view.
Required Default implementation provided.
Cleaning up the view
static func dismantleUIView(Self.UIViewType, coordinator: Self.Coordinator)
Cleans up the presented UIKit view (and coordinator) in anticipation of their removal.
Providing a custom coordinator object
Creates the custom instance that you use to communicate changes from your view to other parts of your SwiftUI interface.
associatedtype Coordinator = Void
A type to coordinate with the view.
Performing layout
typealias LayoutOptions
Relationships
Inherits From
View
See Also
Adding UIKit views to SwiftUI view hierarchies
struct UIViewRepresentableContext
Contextual information about the state of the system that you use to create and update your UIKit view.
protocol UIViewControllerRepresentable
A view that represents a UIKit view controller.
struct UIViewControllerRepresentableContext
Contextual information about the state of the system that you use to create and update your UIKit view controller.
https://developer.apple.com/documentation/swiftui/wkinterfaceobjectrepresentable
- SwiftUI
- WKInterfaceObjectRepresentable
Protocol
WKInterfaceObjectRepresentable
A view that represents a WatchKit interface object.
@MainActor @preconcurrency protocol WKInterfaceObjectRepresentable : View where Self.Body == Never
Overview
Use a WKInterfaceObjectRepresentable instance to create and manage a WKInterfaceObject in your SwiftUI interface. Adopt this protocol in one of your app’s custom instances, and use its methods to create, update, and tear down your interface object. The creation and update processes parallel the behavior of SwiftUI views, and you use them to configure your interface object with your app’s current state information. Use the teardown process to remove your interface object cleanly from your SwiftUI. For example, you might use the teardown process to notify other parts of your app that the interface object is disappearing.
To add your interface object into your SwiftUI interface, create your WKInterfaceObjectRepresentable instance and add it to your SwiftUI interface. The system calls the methods of your representable instance at appropriate times to create and update the interface object.
The system doesn’t automatically communicate changes occurring within your interface object to other parts of your SwiftUI interface. When you want your interface object to coordinate with other SwiftUI views, you must provide a Coordinator instance to facilitate those interactions. For example, you use a coordinator to forward target-action and delegate messages from your interface object to any SwiftUI views.
Topics
Creating and updating the interface object
Creates a WatchKit interface object and configures its initial state.
Required
func updateWKInterfaceObject(Self.WKInterfaceObjectType, context: Self.Context)
Updates the presented WatchKit interface object (and its coordinator) to the latest configuration.
typealias Context
Cleaning up the interface object
static func dismantleWKInterfaceObject(Self.WKInterfaceObjectType, coordinator: Self.Coordinator)
Cleans up the presented WatchKit interface object (and its coordinator) in anticipation of their removal.
Required Default implementation provided.
Providing a custom coordinator object
Creates the custom instance that you use to communicate changes from your interface object to other parts of your SwiftUI interface.
associatedtype Coordinator = Void
A type to coordinate with the WatchKit interface object.
associatedtype WKInterfaceObjectType : WKInterfaceObject
The type of WatchKit interface object to be presented.
Relationships
Inherits From
View
See Also
Adding WatchKit views to SwiftUI view hierarchies
struct WKInterfaceObjectRepresentableContext
Contextual information about the state of the system that you use to create and update your WatchKit interface object.
https://developer.apple.com/documentation/swiftui/angulargradient
https://developer.apple.com/documentation/swiftui/anyshape
- SwiftUI
- AnyShape
Structure
AnyShape
A type-erased shape value.
@frozen struct AnyShape
Overview
You can use this type to dynamically switch between shape types:
struct MyClippedView: View { var isCircular: Bool
var body: some View { OtherView().clipShape(isCircular ? AnyShape(Circle()) : AnyShape(Capsule())) } }
Topics
Creating a shape
Create an any shape instance from a shape.
Relationships
Conforms To
AnimatableSendableSendableMetatypeShapeView
See Also
Defining shape behavior
protocol ShapeView
A view that provides a shape that you can use for drawing operations.
protocol Shape
A 2D shape that you can use when drawing a view.
enum ShapeRole
Ways of styling a shape.
struct StrokeStyle
The characteristics of a stroke that traces a path.
struct StrokeShapeView
A shape provider that strokes its shape.
struct StrokeBorderShapeView
A shape provider that strokes the border of its shape.
struct FillStyle
A style for rasterizing vector shapes.
struct FillShapeView
A shape provider that fills its shape.
https://developer.apple.com/documentation/swiftui/anyview
- SwiftUI
- AnyView
Structure
AnyView
A type-erased view.
@frozen struct AnyView
Overview
An AnyView allows changing the type of view used in a given view hierarchy. Whenever the type of view used with an AnyView changes, the old hierarchy is destroyed and a new hierarchy is created for the new type.
Topics
Creating a view
Create an instance that type-erases view.
Relationships
Conforms To
View
See Also
Supporting view types
struct EmptyView
A view that doesn’t contain any content.
struct EquatableView
A view type that compares itself against its previous value and prevents its child updating if its new value is the same as its old value.
struct SubscriptionView
A view that subscribes to a publisher with an action.
struct TupleView
A View created from a swift tuple of View values.
https://developer.apple.com/documentation/swiftui/asyncimage
- SwiftUI
- AsyncImage
Structure
AsyncImage
A view that asynchronously loads and displays an image.
Overview
This view uses the shared URLSession instance to load an image from the specified URL, and then display it. For example, you can display an icon that’s stored on a server:
AsyncImage(url: URL(string: "https://example.com/icon.png")) .frame(width: 200, height: 200)
Until the image loads, the view displays a standard placeholder that fills the available space. After the load completes successfully, the view updates to display the image. In the example above, the icon is smaller than the frame, and so appears smaller than the placeholder.
You can specify a custom placeholder using init(url:scale:content:placeholder:). With this initializer, you can also use the content parameter to manipulate the loaded image. For example, you can add a modifier to make the loaded image resizable:
AsyncImage(url: URL(string: "https://example.com/icon.png")) { image in image.resizable() } placeholder: { ProgressView() } .frame(width: 50, height: 50)
For this example, SwiftUI shows a ProgressView first, and then the image scaled to fit in the specified frame:
To gain more control over the loading process, use the init(url:scale:transaction:content:) initializer, which takes a content closure that receives an AsyncImagePhase to indicate the state of the loading operation. Return a view that’s appropriate for the current phase:
AsyncImage(url: URL(string: "https://example.com/icon.png")) { phase in if let image = phase.image { image // Displays the loaded image. } else if phase.error != nil { Color.red // Indicates an error. } else { Color.blue // Acts as a placeholder. } }
Topics
Loading an image
init(url: URL?, scale: CGFloat)
Loads and displays an image from the specified URL.
Loads and displays a modifiable image from the specified URL using a custom placeholder until the image loads.
Loading an image in phases
Loads and displays a modifiable image from the specified URL in phases.
Relationships
Conforms To
View
See Also
Loading images asynchronously
enum AsyncImagePhase
The current phase of the asynchronous image loading operation.
https://developer.apple.com/documentation/swiftui/button
https://developer.apple.com/documentation/swiftui/buttonbordershape
- SwiftUI
- ButtonBorderShape
Structure
ButtonBorderShape
A shape used to draw a button’s border.
struct ButtonBorderShape
Overview
Use the buttonBorderShape(_:) view modifier to apply the shape to bordered buttons within a view hierarchy.
Topics
Getting border shapes
static let automatic: ButtonBorderShape
A shape that defers to the system to determine an appropriate shape for the given context and platform.
static let capsule: ButtonBorderShape
A capsule shape.
static let circle: ButtonBorderShape
A circular shape.
static let roundedRectangle: ButtonBorderShape
A rounded rectangle shape.
Relationships
Conforms To
AnimatableCopyableEquatableInsettableShapeSendableSendableMetatypeShapeView
See Also
Creating buttons
struct Button
A control that initiates an action.
func buttonStyle(_:)
Sets the style for buttons within this view to a button style with a custom appearance and standard interaction behavior.
Sets the border shape for buttons in this view.
Sets whether buttons in this view should repeatedly trigger their actions on prolonged interactions.
var buttonRepeatBehavior: ButtonRepeatBehavior
Whether buttons with this associated environment should repeatedly trigger their actions on prolonged interactions.
struct ButtonRole
A value that describes the purpose of a button.
struct ButtonRepeatBehavior
The options for controlling the repeatability of button actions.
struct ButtonSizing Beta
https://developer.apple.com/documentation/swiftui/buttonstyleconfiguration/label-swift.struct
- SwiftUI
- ButtonStyleConfiguration
- ButtonStyleConfiguration.Label
Structure
ButtonStyleConfiguration.Label
A type-erased label of a button.
@MainActor @preconcurrency struct Label
Relationships
Conforms To
View
See Also
Configuring a button’s label
let label: ButtonStyleConfiguration.Label
A view that describes the effect of pressing the button.
https://developer.apple.com/documentation/swiftui/canvas
- SwiftUI
- Canvas
Structure
Canvas
A view type that supports immediate mode drawing.
Overview
Use a canvas to draw rich and dynamic 2D graphics inside a SwiftUI view. The canvas passes a GraphicsContext to the closure that you use to perform immediate mode drawing operations. The canvas also passes a CGSize value that you can use to customize what you draw. For example, you can use the context’s stroke(_:with:lineWidth:) command to draw a Path instance:
Canvas { context, size in context.stroke( Path(ellipseIn: CGRect(origin: .zero, size: size)), with: .color(.green), lineWidth: 4) } .frame(width: 300, height: 200) .border(Color.blue)
The example above draws the outline of an ellipse that exactly inscribes a canvas with a blue border:
In addition to outlined and filled paths, you can draw images, text, and complete SwiftUI views. To draw views, use the init(opaque:colorMode:rendersAsynchronously:renderer:symbols:) method to supply views that you can reference from inside the renderer. You can also add masks, apply filters, perform transforms, control blending, and more. For information about how to draw, see GraphicsContext.
A canvas doesn’t offer interactivity or accessibility for individual elements, including for views that you pass in as symbols. However, it might provide better performance for a complex drawing that involves dynamic data. Use a canvas to improve performance for a drawing that doesn’t primarily involve text or require interactive elements.
Topics
Creating a canvas
Creates and configures a canvas.
Creates and configures a canvas that you supply with renderable child views.
Managing opacity and color
var isOpaque: Bool
A Boolean that indicates whether the canvas is fully opaque.
var colorMode: ColorRenderingMode
The working color space and storage format of the canvas.
Referencing symbols
var symbols: Symbols
A view that provides child views that you can use in the drawing callback.
Rendering
var rendersAsynchronously: Bool
A Boolean that indicates whether the canvas can present its contents to its parent view asynchronously.
The drawing callback that you use to draw into the canvas.
Relationships
Conforms To
CopyableViewConforms whenSymbolsconforms toView.
See Also
Immediate mode drawing
Add Rich Graphics to Your SwiftUI App
Make your apps stand out by adding background materials, vibrancy, custom graphics, and animations.
struct GraphicsContext
An immediate mode drawing destination, and its current state.
https://developer.apple.com/documentation/swiftui/capsule
https://developer.apple.com/documentation/swiftui/circle
https://developer.apple.com/documentation/swiftui/color
- SwiftUI
- Color
Structure
Color
A representation of a color that adapts to a given context.
@frozen struct Color
Mentioned in
Laying out a simple view
Overview
You can create a color in one of several ways:
- Load a color from an Asset Catalog:
let aqua = Color("aqua") // Looks in your app's main bundle by default.
- Specify component values, like red, green, and blue; hue, saturation, and brightness; or white level:
let skyBlue = Color(red: 0.4627, green: 0.8392, blue: 1.0) let lemonYellow = Color(hue: 0.1639, saturation: 1, brightness: 1) let steelGray = Color(white: 0.4745)
- Create a color instance from another color, like a
UIColoror anNSColor:
#if os(iOS) let linkColor = Color(uiColor: .link) #elseif os(macOS) let linkColor = Color(nsColor: .linkColor) #endif
- Use one of a palette of predefined colors, like
black,green, andpurple.
Some view modifiers can take a color as an argument. For example, foregroundStyle(_:) uses the color you provide to set the foreground color for view elements, like text or SF Symbols:
Image(systemName: "leaf.fill") .foregroundStyle(Color.green)
Because SwiftUI treats colors as View instances, you can also directly add them to a view hierarchy. For example, you can layer a rectangle beneath a sun image using colors defined above:
ZStack { skyBlue Image(systemName: "sun.max.fill") .foregroundStyle(lemonYellow) } .frame(width: 200, height: 100)
A color used as a view expands to fill all the space it’s given, as defined by the frame of the enclosing ZStack in the above example:
SwiftUI only resolves a color to a concrete value just before using it in a given environment. This enables a context-dependent appearance for system defined colors, or those that you load from an Asset Catalog. For example, a color can have distinct light and dark variants that the system chooses from at render time.
Topics
Creating a color
init(String, bundle: Bundle?)
Creates a color from a color set that you indicate by name.
init(_:)
Creates a constant color with the values specified by the resolved color.
Evaluates this color to a resolved color given the current context.
Creating a color from component values
init(hue: Double, saturation: Double, brightness: Double, opacity: Double)
Creates a constant color from hue, saturation, and brightness values.
init(Color.RGBColorSpace, white: Double, opacity: Double)
Creates a constant grayscale color.
init(Color.RGBColorSpace, red: Double, green: Double, blue: Double, opacity: Double)
Creates a constant color from red, green, and blue component values.
enum RGBColorSpace
A profile that specifies how to interpret a color value for display.
Creating a color from another color
init(uiColor: UIColor)
Creates a color from a UIKit color.
init(nsColor: NSColor)
Creates a color from an AppKit color.
init(cgColor: CGColor)
Creates a color from a Core Graphics color.
Getting standard colors
static let black: Color
A black color suitable for use in UI elements.
static let blue: Color
A context-dependent blue color suitable for use in UI elements.
static let brown: Color
A context-dependent brown color suitable for use in UI elements.
static let clear: Color
A clear color suitable for use in UI elements.
static let cyan: Color
A context-dependent cyan color suitable for use in UI elements.
static let gray: Color
A context-dependent gray color suitable for use in UI elements.
static let green: Color
A context-dependent green color suitable for use in UI elements.
static let indigo: Color
A context-dependent indigo color suitable for use in UI elements.
static let mint: Color
A context-dependent mint color suitable for use in UI elements.
static let orange: Color
A context-dependent orange color suitable for use in UI elements.
static let pink: Color
A context-dependent pink color suitable for use in UI elements.
static let purple: Color
A context-dependent purple color suitable for use in UI elements.
static let red: Color
A context-dependent red color suitable for use in UI elements.
static let teal: Color
A context-dependent teal color suitable for use in UI elements.
static let white: Color
A white color suitable for use in UI elements.
static let yellow: Color
A context-dependent yellow color suitable for use in UI elements.
Getting semantic colors
static var accentColor: Color
A color that reflects the accent color of the system or app.
static let primary: Color
The color to use for primary content.
static let secondary: Color
The color to use for secondary content.
Modifying a color
Multiplies the opacity of the color by the given amount.
var gradient: AnyGradient
Returns the standard gradient for the color self.
Returns a version of self mixed with rhs by the amount specified by fraction.
Returns a new color with an exposure adjustment applied.
Beta
Creates a new color with specified HDR content headroom.
Working with high dynamic range (HDR) colors
Evaluates this color to a resolved color with content headroom, given a set of environment values. /
struct ResolvedHDR
A concrete color value, including HDR headroom information.
Describing a color
var description: String
A textual representation of the color.
Comparing colors
Indicates whether two colors are equal.
func hash(into: inout Hasher)
Hashes the essential components of the color by feeding them into the given hash function.
Deprecated symbols
var cgColor: CGColor?
A Core Graphics representation of the color, if available.
Deprecated
Relationships
Conforms To
CopyableCustomStringConvertibleEquatableHashableSendableSendableMetatypeShapeStyleTransferableView
See Also
Setting a color
func tint(_:)
Sets the tint color within this view.
https://developer.apple.com/documentation/swiftui/colorpicker
- SwiftUI
- ColorPicker
Structure
ColorPicker
A control used to select a color from the system color picker UI.
Overview
The color picker provides a color well that shows the currently selected color, and displays the larger system color picker that allows users to select a new color.
By default color picker supports colors with opacity; to disable opacity support, set the supportsOpacity parameter to false. In this mode the color picker won’t show controls for adjusting the opacity of the selected color, and strips out opacity from any color set programmatically or selected from the user’s system favorites.
You use ColorPicker by embedding it inside a view hierarchy and initializing it with a title string and a Binding to a Color:
struct FormattingControls: View { @State private var bgColor = Color(.sRGB, red: 0.98, green: 0.9, blue: 0.2)
var body: some View { VStack { ColorPicker("Alignment Guides", selection: $bgColor) } } }
Topics
Creating a color picker
init(_:selection:supportsOpacity:)
Creates a color picker with a text label generated from a title string key.
init(selection:supportsOpacity:label:)
Creates an instance that selects a color.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/containerrelativeshape
- SwiftUI
- ContainerRelativeShape
Structure
ContainerRelativeShape
A shape that is replaced by an inset version of the current container shape. If no container shape was defined, is replaced by a rectangle.
@frozen struct ContainerRelativeShape
Topics
Creating the shape
init()
Relationships
Conforms To
AnimatableBitwiseCopyableCopyableInsettableShapeSendableSendableMetatypeShapeView
See Also
Setting a container shape
Sets the container shape to use for any container relative shape within this view.
protocol InsettableShape
A shape type that is able to inset itself to produce another shape.
https://developer.apple.com/documentation/swiftui/contentunavailableview
- SwiftUI
- ContentUnavailableView
Structure
ContentUnavailableView
An interface, consisting of a label and additional content, that you display when the content of your app is unavailable to users.
Overview
It is recommended to use ContentUnavailableView in situations where a view’s content cannot be displayed. That could be caused by a network error, a list without items, a search that returns no results etc.
You create an ContentUnavailableView in its simplest form, by providing a label and some additional content such as a description or a call to action:
ContentUnavailableView { Label("No Mail", systemImage: "tray.fill") } description: { Text("New mails you receive will appear here.") }
The system provides default ContentUnavailableView s that you can use in specific situations. The example below illustrates the usage of the search view:
struct ContentView: View { @ObservedObject private var viewModel = ContactsViewModel()
var body: some View { NavigationStack { List { ForEach(viewModel.searchResults) { contact in NavigationLink { ContactsView(contact) } label: { Text(contact.name) } } } .navigationTitle("Contacts") .searchable(text: $viewModel.searchText) .overlay { if searchResults.isEmpty { ContentUnavailableView.search } } } } }
Topics
Getting built-in unavailable views
Creates a ContentUnavailableView instance that conveys a search state.
Creating an unavailable view
Creates an interface, consisting of a label and additional content, that you display when the content of your app is unavailable to users.
init(_:image:description:)
Creates an interface, consisting of a title generated from a localized string, an image and additional content, that you display when the content of your app is unavailable to users.
init(_:systemImage:description:)
Creates an interface, consisting of a title generated from a localized string, a system icon image and additional content, that you display when the content of your app is unavailable to users.
Supporting types
struct SearchUnavailableContent
A structure that represents the body of a static placeholder search view.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/controlgroup
- SwiftUI
- ControlGroup
Structure
ControlGroup
A container view that displays semantically-related controls in a visually-appropriate manner for the context
Mentioned in
Populating SwiftUI menus with adaptive controls
Overview
You can provide an optional label to this view that describes its children. This view may be used in different ways depending on the surrounding context. For example, when you place the control group in a toolbar item, SwiftUI uses the label when the group is moved to the toolbar’s overflow menu.
ContentView() .toolbar(id: "items") { ToolbarItem(id: "media") { ControlGroup { MediaButton() ChartButton() GraphButton() } label: { Label("Plus", systemImage: "plus") } } }
Topics
Creating a control group
Creates a new ControlGroup with the specified children
Creates a new control group with the specified content and a label.
init(_:content:)
Creates a new control group with the specified content that generates its label from a string.
Creating a control group with an image
init(_:image:content:)
Creates a new control group with the specified content that generates its label from a string and image name.
init(_:systemImage:content:)
Creating a configured control group
init(ControlGroupStyleConfiguration)
Creates a control group based on a style configuration.
Supporting types
struct LabeledControlGroupContent
A view that represents the body of a control group with a specified label.
Relationships
Conforms To
View
See Also
Presenting a group of controls
Sets the style for control groups within this view.
https://developer.apple.com/documentation/swiftui/controlgroupstyleconfiguration/content-swift.struct
- SwiftUI
- ControlGroupStyleConfiguration
- ControlGroupStyleConfiguration.Content
Structure
ControlGroupStyleConfiguration.Content
A type-erased content of a ControlGroup.
@MainActor @preconcurrency struct Content
Relationships
Conforms To
View
See Also
Configuring the content
let content: ControlGroupStyleConfiguration.Content
A view that represents the content of the ControlGroup.
https://developer.apple.com/documentation/swiftui/controlgroupstyleconfiguration/label-swift.struct
- SwiftUI
- ControlGroupStyleConfiguration
- ControlGroupStyleConfiguration.Label
Structure
ControlGroupStyleConfiguration.Label
A type-erased label of a ControlGroup.
@MainActor @preconcurrency struct Label
Relationships
Conforms To
View
See Also
Configuring the label
let label: ControlGroupStyleConfiguration.Label
A view that provides the optional label of the ControlGroup.
https://developer.apple.com/documentation/swiftui/datepicker
- SwiftUI
- DatePicker
Structure
DatePicker
A control for selecting an absolute date.
Mentioned in
Laying out a simple view
Overview
Use a DatePicker when you want to provide a view that allows the user to select a calendar date, and optionally a time. The view binds to a Date instance.
The following example creates a basic DatePicker, which appears on iOS as text representing the date. This example limits the display to only the calendar date, not the time. When the user taps or clicks the text, a calendar view animates in, from which the user can select a date. When the user dismisses the calendar view, the view updates the bound Date.
@State private var date = Date()
var body: some View { DatePicker( "Start Date", selection: $date, displayedComponents: [.date] ) }
For cases where adding a subtitle to the label is desired, use a view builder that creates multiple Text views where the first text represents the title and the second text represents the subtitle:
var body: some View { DatePicker(selection: $date) { Text("Start Date") Text("Select the starting date for the event") } }
You can limit the DatePicker to specific ranges of dates, allowing selections only before or after a certain date, or between two dates. The following example shows a date-and-time picker that only permits selections within the year 2021 (in the UTC time zone).
let calendar = Calendar.current let startComponents = DateComponents(year: 2021, month: 1, day: 1) let endComponents = DateComponents(year: 2021, month: 12, day: 31, hour: 23, minute: 59, second: 59) return calendar.date(from:startComponents)! ... calendar.date(from:endComponents)! }()
var body: some View { DatePicker( "Start Date", selection: $date, in: dateRange, displayedComponents: [.date, .hourAndMinute] ) }
Styling date pickers
To use a different style of date picker, use the datePickerStyle(_:) view modifier. The following example shows the graphical date picker style.
var body: some View { DatePicker( "Start Date", selection: $date, displayedComponents: [.date] ) .datePickerStyle(.graphical) }
Topics
Creating a date picker for any date
init(_:selection:displayedComponents:)
Creates an instance that selects a Date with an unbounded range.
Creating a date picker for specific dates
init(_:selection:in:displayedComponents:)
Creates an instance that selects a Date in a closed range.
init(selection:in:displayedComponents:label:)
Setting date picker components
typealias Components
struct DatePickerComponents
Relationships
Conforms To
View
See Also
Choosing dates
Sets the style for date pickers within this view.
struct MultiDatePicker
A control for picking multiple dates.
var calendar: Calendar
The current calendar that views should use when handling dates.
var timeZone: TimeZone
The current time zone that views should use when handling dates.
https://developer.apple.com/documentation/swiftui/datepickerstyleconfiguration/label-swift.struct
- SwiftUI
- DatePickerStyleConfiguration
- DatePickerStyleConfiguration.Label
Structure
DatePickerStyleConfiguration.Label
A type-erased label of a DatePicker.
@MainActor @preconcurrency struct Label
Relationships
Conforms To
View
See Also
Labeling the date picker
let label: DatePickerStyleConfiguration.Label
A description of the DatePicker.
var displayedComponents: DatePickerComponents
The date components that the user is able to view and edit.
https://developer.apple.com/documentation/swiftui/debugreplaceableview
- SwiftUI
- DebugReplaceableView Beta
Structure
DebugReplaceableView
Erases view opaque result types in debug builds.
struct DebugReplaceableView
Overview
You don’t use this type directly. Instead SwiftUI creates this type on your behalf when building in debug mode.
When in debug builds, SwiftUI will erase all opaque result types to DebugReplaceableView. This allows developer tools, such as Xcode Previews, to replace the definition of the view without fully rebuilding.
As such, seeing this type in traces and the view debugger is expected when building for debugging. This type erasure can impact performance, especially when dealing with dynamic content (like content generated by a ForEach, or List) so any performance testing should be done in release mode.
This type acts similarly to an AnyView in that it type-erases its content, however it depends on the underlying type of the value not actually changing as it is in place of an opaque result type. As such, it should not be used in app code.
Topics
Initializers
Creates a debug replaceable view erasing the given view.
Deprecated
Relationships
Conforms To
View
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/defaultbuttonlabel
- SwiftUI
- DefaultButtonLabel Beta
Structure
DefaultButtonLabel
The default label to use for a button.
struct DefaultButtonLabel
Overview
You don’t use this type directly. Instead, the system creates it automatically when you construct certain types of Button.
Relationships
Conforms To
View
See Also
Indicating a value
struct Gauge
A view that shows a value within a range.
Sets the style for gauges within this view.
struct ProgressView
A view that shows the progress toward completion of a task.
Sets the style for progress views in this view.
struct DefaultDateProgressLabel
The default type of the current value label when used by a date-relative progress view.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/defaultdateprogresslabel
- SwiftUI
- DefaultDateProgressLabel
Structure
DefaultDateProgressLabel
The default type of the current value label when used by a date-relative progress view.
struct DefaultDateProgressLabel
Relationships
Conforms To
View
See Also
Indicating a value
struct Gauge
A view that shows a value within a range.
Sets the style for gauges within this view.
struct ProgressView
A view that shows the progress toward completion of a task.
Sets the style for progress views in this view.
struct DefaultButtonLabel
The default label to use for a button.
Beta
https://developer.apple.com/documentation/swiftui/defaultsettingslinklabel
- SwiftUI
- DefaultSettingsLinkLabel
Structure
DefaultSettingsLinkLabel
The default label to use for a settings link.
struct DefaultSettingsLinkLabel
Overview
You don’t use this type directly. Instead, the system creates it automatically when you construct a SettingsLink with the default label.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/defaultsharelinklabel
- SwiftUI
- DefaultShareLinkLabel
Structure
DefaultShareLinkLabel
The default label used for a share link.
struct DefaultShareLinkLabel
Overview
You don’t use this type directly. Instead, ShareLink uses it automatically depending on how you create a share link.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/defaulttablabel
- SwiftUI
- DefaultTabLabel
Structure
DefaultTabLabel
The default label to use for a tab or tab section.
struct DefaultTabLabel
Overview
You don’t use this type directly. Instead, the system creates it automatically when you construct a Tab or TabSection.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/defaultwindowvisibilitytogglelabel
https://developer.apple.com/documentation/swiftui/disclosuregroup
- SwiftUI
- DisclosureGroup
Structure
DisclosureGroup
A view that shows or hides another content view, based on the state of a disclosure control.
Mentioned in
Displaying data in lists
Overview
A disclosure group view consists of a label to identify the contents, and a control to show and hide the contents. Showing the contents puts the disclosure group into the “expanded” state, and hiding them makes the disclosure group “collapsed”.
In the following example, a disclosure group contains two toggles and an embedded disclosure group. The top level disclosure group exposes its expanded state with the bound property, topLevelExpanded. By expanding the disclosure group, the user can use the toggles to update the state of the toggleStates structure.
struct ToggleStates { var oneIsOn: Bool = false var twoIsOn: Bool = true } @State private var toggleStates = ToggleStates() @State private var topExpanded: Bool = true
var body: some View { DisclosureGroup("Items", isExpanded: $topExpanded) { Toggle("Toggle 1", isOn: $toggleStates.oneIsOn) Toggle("Toggle 2", isOn: $toggleStates.twoIsOn) DisclosureGroup("Sub-items") { Text("Sub-item 1") } } }
Topics
Creating a disclosure group
init(_:content:)
Creates a disclosure group, using a provided localized string key to create a text view for the label.
Creates a disclosure group with the given label and content views.
init(_:isExpanded:content:)
Creates a disclosure group, using a provided localized string key to create a text view for the label, and a binding to the expansion state (expanded or collapsed).
Creates a disclosure group with the given label and content views, and a binding to the expansion state (expanded or collapsed).
Relationships
Conforms To
View
See Also
Disclosing information progressively
struct OutlineGroup
A structure that computes views and disclosure groups on demand from an underlying collection of tree-structured, identified data.
Sets the style for disclosure groups within this view.
https://developer.apple.com/documentation/swiftui/disclosuregroupstyleconfiguration/content-swift.struct
- SwiftUI
- DisclosureGroupStyleConfiguration
- DisclosureGroupStyleConfiguration.Content
Structure
DisclosureGroupStyleConfiguration.Content
A type-erased content of a disclosure group.
@MainActor @preconcurrency struct Content
Relationships
Conforms To
View
See Also
Configuring the content
let content: DisclosureGroupStyleConfiguration.Content
The content of the disclosure group.
https://developer.apple.com/documentation/swiftui/disclosuregroupstyleconfiguration/label-swift.struct
- SwiftUI
- DisclosureGroupStyleConfiguration
- DisclosureGroupStyleConfiguration.Label
Structure
DisclosureGroupStyleConfiguration.Label
A type-erased label of a disclosure group.
@MainActor @preconcurrency struct Label
Relationships
Conforms To
View
See Also
Configuring the label
let label: DisclosureGroupStyleConfiguration.Label
The label for the disclosure group.
https://developer.apple.com/documentation/swiftui/divider
- SwiftUI
- Divider
Structure
Divider
A visual element that can be used to separate other content.
struct Divider
Mentioned in
Building layouts with stack views
Populating SwiftUI menus with adaptive controls
Overview
When contained in a stack, the divider extends across the minor axis of the stack, or horizontally when not in a stack.
Topics
Creating a divider
init()
Relationships
Conforms To
View
See Also
Separators
struct Spacer
A flexible space that expands along the major axis of its containing stack layout, or on both axes if not contained in a stack.
https://developer.apple.com/documentation/swiftui/editbutton
- SwiftUI
- EditButton
Structure
EditButton
A button that toggles the edit mode environment value.
struct EditButton
Overview
An edit button toggles the environment’s editMode value for content within a container that supports edit mode. In the following example, an edit button placed inside a NavigationView supports editing of a List:
@State private var fruits = [
"Apple",
"Banana",
"Papaya",
"Mango"
]
var body: some View { NavigationView { List { ForEach(fruits, id: .self) { fruit in Text(fruit) } .onDelete { fruits.remove(atOffsets: $0) } .onMove { fruits.move(fromOffsets: $0, toOffset: $1) } } .navigationTitle("Fruits") .toolbar { EditButton() } } }
Because the ForEach in the above example defines behaviors for onDelete(perform:) and onMove(perform:), the editable list displays the delete and move UI when the user taps Edit. Notice that the Edit button displays the title “Done” while edit mode is active:
You can also create custom views that react to changes in the edit mode state, as described in EditMode.
Topics
Creating an edit button
init()
Creates an Edit button instance.
Relationships
Conforms To
View
See Also
Creating special-purpose buttons
struct PasteButton
A system button that reads items from the pasteboard and delivers it to a closure.
struct RenameButton
A button that triggers a standard rename action.
https://developer.apple.com/documentation/swiftui/editablecollectioncontent
- SwiftUI
- EditableCollectionContent
Structure
EditableCollectionContent
An opaque wrapper view that adds editing capabilities to a row in a list.
Overview
You don’t use this type directly. Instead SwiftUI creates this type on your behalf.
Relationships
Conforms To
CopyableViewConforms whenContentconforms toView,Dataconforms toCopyable, andDataconforms toEscapable.
See Also
Editing a list
Adds a condition for whether the view’s view hierarchy is movable.
Adds a condition for whether the view’s view hierarchy is deletable.
An indication of whether the user can edit the contents of a view associated with this environment.
enum EditMode
A mode that indicates whether the user can edit a view’s content.
struct EditActions
A set of edit actions on a collection of data that a view can offer to a user.
struct IndexedIdentifierCollection
A collection wrapper that iterates over the indices and identifiers of a collection together.
https://developer.apple.com/documentation/swiftui/ellipse
- SwiftUI
- Ellipse
Structure
Ellipse
An ellipse aligned inside the frame of the view containing it.
@frozen struct Ellipse
Topics
Creating an ellipse
init()
Creates a new ellipse shape.
Relationships
Conforms To
AnimatableBitwiseCopyableCopyableInsettableShapeSendableSendableMetatypeShapeView
See Also
Creating circular shapes
struct Circle
A circle centered on the frame of the view containing it.
struct Capsule
A capsule shape aligned inside the frame of the view containing it.
https://developer.apple.com/documentation/swiftui/ellipticalgradient
- SwiftUI
- EllipticalGradient
Structure
EllipticalGradient
A radial gradient that draws an ellipse.
@frozen struct EllipticalGradient
Overview
The gradient maps its coordinate space to the unit space square in which its center and radii are defined, then stretches that square to fill its bounding rect, possibly also stretching the circular gradient to have elliptical contours.
For example, an elliptical gradient centered on the view, filling its bounds:
EllipticalGradient(gradient: .init(colors: [.red, .yellow]))
When using an elliptical gradient as a shape style, you can also use ellipticalGradient(_:center:startRadiusFraction:endRadiusFraction:).
Topics
Creating an elliptical gradient
init(gradient: Gradient, center: UnitPoint, startRadiusFraction: CGFloat, endRadiusFraction: CGFloat)
Creates an elliptical gradient.
init(colors: [Color], center: UnitPoint, startRadiusFraction: CGFloat, endRadiusFraction: CGFloat)
Creates an elliptical gradient from a collection of colors.
Creates an elliptical gradient from a collection of color stops.
Relationships
Conforms To
SendableSendableMetatypeShapeStyleView
See Also
Supporting types
struct AngularGradient
An angular gradient.
struct LinearGradient
A linear gradient.
struct RadialGradient
A radial gradient.
struct Material
A background material type.
struct ImagePaint
A shape style that fills a shape by repeating a region of an image.
struct HierarchicalShapeStyle
A shape style that maps to one of the numbered content styles.
struct HierarchicalShapeStyleModifier
Styles that you can apply to hierarchical shapes.
struct ForegroundStyle
The foreground style in the current context.
struct BackgroundStyle
The background style in the current context.
struct SelectionShapeStyle
A style used to visually indicate selection following platform conventional colors and behaviors.
struct SeparatorShapeStyle
A style appropriate for foreground separator or border lines.
struct TintShapeStyle
A style that reflects the current tint color.
struct FillShapeStyle
A shape style that displays one of the overlay fills.
struct LinkShapeStyle
A style appropriate for links.
struct PlaceholderTextShapeStyle
A style appropriate for placeholder text.
https://developer.apple.com/documentation/swiftui/emptyview
https://developer.apple.com/documentation/swiftui/equatableview
- SwiftUI
- EquatableView
Structure
EquatableView
A view type that compares itself against its previous value and prevents its child updating if its new value is the same as its old value.
@frozen
Topics
Creating an equatable view
init(content: Content)
var content: Content
Relationships
Conforms To
View
See Also
Supporting view types
struct AnyView
A type-erased view.
struct EmptyView
A view that doesn’t contain any content.
struct SubscriptionView
A view that subscribes to a publisher with an action.
struct TupleView
A View created from a swift tuple of View values.
https://developer.apple.com/documentation/swiftui/fillshapeview
https://developer.apple.com/documentation/swiftui/foreach
- SwiftUI
- ForEach
Structure
ForEach
A structure that computes views on demand from an underlying collection of identified data.
Mentioned in
Creating performant scrollable stacks
Grouping data with lazy stack views
Displaying data in lists
Picking container views for your content
Overview
Use ForEach to provide views based on a RandomAccessCollection of some data type. Either the collection’s elements must conform to Identifiable or you need to provide an id parameter to the ForEach initializer.
The following example creates a NamedFont type that conforms to Identifiable, and an array of this type called namedFonts. A ForEach instance iterates over the array, producing new Text instances that display examples of each SwiftUI Font style provided in the array.
private struct NamedFont: Identifiable { let name: String let font: Font var id: String { name } }
private let namedFonts: [NamedFont] = [
NamedFont(name: "Large Title", font: .largeTitle),
NamedFont(name: "Title", font: .title),
NamedFont(name: "Headline", font: .headline),
NamedFont(name: "Body", font: .body),
NamedFont(name: "Caption", font: .caption)
]
var body: some View { ForEach(namedFonts) { namedFont in Text(namedFont.name) .font(namedFont.font) } }
Some containers like List or LazyVStack will query the elements within a for each lazily. To obtain maximal performance, ensure that the view created from each element in the collection represents a constant number of views.
For example, the following view uses an if statement which means each element of the collection can represent either 1 or 0 views, a non-constant number.
ForEach(namedFonts) { namedFont in if namedFont.name.count != 2 { Text(namedFont.name) } }
You can make the above view represent a constant number of views by wrapping the condition in a VStack, an HStack, or a ZStack.
ForEach(namedFonts) { namedFont in VStack { if namedFont.name.count != 2 { Text(namedFont.name) } } }
When enabling the following launch argument, SwiftUI will log when it encounters a view that produces a non-constant number of views in these containers:
-LogForEachSlowPath YES
Topics
Creating a collection
init(Data)
Creates an instance that uniquely identifies and creates table rows across updates based on the identity of the underlying data.
init(_:content:)
Creates an instance that uniquely identifies and creates map content across updates based on the identity of the underlying data.
init(_:id:content:)
Creates an instance that uniquely identifies and creates map content across updates based on the provided key path to the underlying data’s identifier.
Creating an editable collection
Creates an instance that uniquely identifies and creates views across updates based on the identity of the underlying data.
Accessing content
A function to create content on demand using the underlying data.
var data: Data
The collection of underlying identified data that SwiftUI uses to create views dynamically.
Initializers
Creates an instance that uniquely identifies and creates views across updates based on the sections of a given view.
Creates an instance that uniquely identifies and creates views across updates based on the subviews of a given view.
Relationships
Conforms To
-
AccessibilityRotorContentConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable, andContentconforms toAccessibilityRotorContent. -
AttachmentContent -
Chart3DContent -
ChartContent -
Copyable -
DynamicMapContent -
DynamicTableRowContentConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable, andContentconforms toTableRowContent. -
DynamicViewContentConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable, andContentconforms toView. -
MapContent -
TabContentConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable, andContentconforms toTabContent. -
TableRowContentConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable, andContentconforms toTableRowContent. -
ViewConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable, andContentconforms toView.
See Also
Iterating over dynamic data
struct ForEachSectionCollection
A collection which allows a view to be treated as a collection of its sections in a for each loop.
struct ForEachSubviewCollection
A collection which allows a view to be treated as a collection of its subviews in a for each loop.
protocol DynamicViewContent
A type of view that generates views from an underlying collection of data.
https://developer.apple.com/documentation/swiftui/form
- SwiftUI
- Form
Structure
Form
A container for grouping controls used for data entry, such as in settings or inspectors.
Mentioned in
Picking container views for your content
Grouping data with lazy stack views
Overview
SwiftUI applies platform-appropriate styling to views contained inside a form, to group them together. Form-specific styling applies to things like buttons, toggles, labels, lists, and more. Keep in mind that these stylings may be platform-specific. For example, forms apppear as grouped lists on iOS, and as aligned vertical stacks on macOS.
The following example shows a simple data entry form on iOS, grouped into two sections. The supporting types ( NotifyMeAboutType and ProfileImageSize) and state variables ( notifyMeAbout, profileImageSize, playNotificationSounds, and sendReadReceipts) are omitted for simplicity.
var body: some View { NavigationView { Form { Section(header: Text("Notifications")) { Picker("Notify Me About", selection: $notifyMeAbout) { Text("Direct Messages").tag(NotifyMeAboutType.directMessages) Text("Mentions").tag(NotifyMeAboutType.mentions) Text("Anything").tag(NotifyMeAboutType.anything) } Toggle("Play notification sounds", isOn: $playNotificationSounds) Toggle("Send read receipts", isOn: $sendReadReceipts) } Section(header: Text("User Profiles")) { Picker("Profile Image Size", selection: $profileImageSize) { Text("Large").tag(ProfileImageSize.large) Text("Medium").tag(ProfileImageSize.medium) Text("Small").tag(ProfileImageSize.small) } Button("Clear Image Cache") {} } } } }
On macOS, a similar form renders as a vertical stack. To adhere to macOS platform conventions, this version doesn’t use sections, and uses colons at the end of its labels. It also sets the picker to use the inline style, which produces radio buttons on macOS.
var body: some View { Spacer() HStack { Spacer() Form { Picker("Notify Me About:", selection: $notifyMeAbout) { Text("Direct Messages").tag(NotifyMeAboutType.directMessages) Text("Mentions").tag(NotifyMeAboutType.mentions) Text("Anything").tag(NotifyMeAboutType.anything) } Toggle("Play notification sounds", isOn: $playNotificationSounds) Toggle("Send read receipts", isOn: $sendReadReceipts)
Picker("Profile Image Size:", selection: $profileImageSize) { Text("Large").tag(ProfileImageSize.large) Text("Medium").tag(ProfileImageSize.medium) Text("Small").tag(ProfileImageSize.small) } .pickerStyle(.inline)
Button("Clear Image Cache") {} } Spacer() } Spacer() }
Topics
Creating a form
Creates a form with the provided content.
Creating a form from a configuration
init(FormStyleConfiguration)
Creates a form based on a form style configuration.
Relationships
Conforms To
View
See Also
Grouping inputs
Sets the style for forms in a view hierarchy.
struct LabeledContent
A container for attaching a label to a value-bearing view.
Sets a style for labeled content.
https://developer.apple.com/documentation/swiftui/formstyleconfiguration/content-swift.struct
- SwiftUI
- FormStyleConfiguration
- FormStyleConfiguration.Content
Structure
FormStyleConfiguration.Content
A type-erased content of a form.
@MainActor @preconcurrency struct Content
Relationships
Conforms To
View
See Also
Getting configuration content
let content: FormStyleConfiguration.Content
A view that is the content of the form.
https://developer.apple.com/documentation/swiftui/gauge
- SwiftUI
- Gauge
Structure
Gauge
A view that shows a value within a range.
Overview
A gauge is a view that shows a current level of a value in relation to a specified finite capacity, very much like a fuel gauge in an automobile. Gauge displays are configurable; they can show any combination of the gauge’s current value, the range the gauge can display, and a label describing the purpose of the gauge itself.
In its most basic form, a gauge displays a single value along the path of the gauge mapped into a range from 0 to 100 percent. The example below sets the gauge’s indicator to a position 40 percent along the gauge’s path:
struct SimpleGauge: View { @State private var batteryLevel = 0.4
var body: some View { Gauge(value: batteryLevel) { Text("Battery Level") } } }
You can make a gauge more descriptive by describing its purpose, showing its current value and its start and end values. This example shows the gauge variant that accepts a range and adds labels using multiple trailing closures describing the current value and the minimum and maximum values of the gauge:
struct LabeledGauge: View { @State private var current = 67.0 @State private var minValue = 0.0 @State private var maxValue = 170.0
var body: some View { Gauge(value: current, in: minValue...maxValue) { Text("BPM") } currentValueLabel: { Text("(Int(current))") } minimumValueLabel: { Text("(Int(minValue))") } maximumValueLabel: { Text("(Int(maxValue))") } } }
As shown above, the default style for gauges is a linear, continuous bar with an indicator showing the current value, and optional labels describing the gauge’s purpose, current, minimum, and maximum values.
To change the style of a gauge, use the gaugeStyle(_:) view modifier and supply an initializer for a specific gauge style. For example, to display the same gauge in a circular style, apply the circular style to the view:
var body: some View { Gauge(value: current, in: minValue...maxValue) { Text("BPM") } currentValueLabel: { Text("(Int(current))") } minimumValueLabel: { Text("(Int(minValue))") } maximumValueLabel: { Text("(Int(maxValue))") } .gaugeStyle(.circular) } }
To style elements of a gauge’s presentation, you apply view modifiers to the elements that you want to change. In the example below, the current value, minimum and maximum value labels have custom colors:
struct StyledGauge: View { @State private var current = 67.0 @State private var minValue = 50.0 @State private var maxValue = 170.0
var body: some View { Gauge(value: current, in: minValue...maxValue) { Image(systemName: "heart.fill") .foregroundColor(.red) } currentValueLabel: { Text("(Int(current))") .foregroundColor(Color.green) } minimumValueLabel: { Text("(Int(minValue))") .foregroundColor(Color.green) } maximumValueLabel: { Text("(Int(maxValue))") .foregroundColor(Color.red) } .gaugeStyle(.circular) } }
You can further style a gauge’s appearance by supplying a tint color or a gradient to the style’s initializer. The following example shows the effect of a gradient in the initialization of a CircularGaugeStyle gauge with a colorful gradient across the length of the gauge:
struct StyledGauge: View { @State private var current = 67.0 @State private var minValue = 50.0 @State private var maxValue = 170.0 let gradient = Gradient(colors: [.green, .yellow, .orange, .red])
var body: some View { Gauge(value: current, in: minValue...maxValue) { Image(systemName: "heart.fill") .foregroundColor(.red) } currentValueLabel: { Text("(Int(current))") .foregroundColor(Color.green) } minimumValueLabel: { Text("(Int(minValue))") .foregroundColor(Color.green) } maximumValueLabel: { Text("(Int(maxValue))") .foregroundColor(Color.red) } .gaugeStyle(CircularGaugeStyle(tint: gradient)) } }
Topics
Creating a gauge
Creates a gauge showing a value within a range and describes the gauge’s purpose and current value.
Creates a gauge showing a value within a range and that describes the gauge’s purpose and current value.
Creates a gauge representing a value within a range.
Creates a gauge showing a value within a range and describes the gauge’s current, minimum, and maximum values.
Relationships
Conforms To
View
See Also
Indicating a value
Sets the style for gauges within this view.
struct ProgressView
A view that shows the progress toward completion of a task.
Sets the style for progress views in this view.
struct DefaultDateProgressLabel
The default type of the current value label when used by a date-relative progress view.
struct DefaultButtonLabel
The default label to use for a button.
Beta
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/currentvaluelabel-swift.struct
- SwiftUI
- GaugeStyleConfiguration
- GaugeStyleConfiguration.CurrentValueLabel
Structure
GaugeStyleConfiguration.CurrentValueLabel
A type-erased value label of a gauge that contains the current value.
@MainActor @preconcurrency struct CurrentValueLabel
Relationships
Conforms To
View
See Also
Setting the value
var value: Double
The current value of the gauge.
var currentValueLabel: GaugeStyleConfiguration.CurrentValueLabel?
A view that describes the current value.
struct MarkedValueLabel
A type-erased label describing a specific value of a gauge.
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/label-swift.struct
- SwiftUI
- GaugeStyleConfiguration
- GaugeStyleConfiguration.Label
Structure
GaugeStyleConfiguration.Label
A type-erased label of a gauge, describing its purpose.
@MainActor @preconcurrency struct Label
Relationships
Conforms To
View
See Also
Describing the purpose of the gauge
var label: GaugeStyleConfiguration.Label
A view that describes the purpose of the gauge.
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/markedvaluelabel
- SwiftUI
- GaugeStyleConfiguration
- GaugeStyleConfiguration.MarkedValueLabel
Structure
GaugeStyleConfiguration.MarkedValueLabel
A type-erased label describing a specific value of a gauge.
@MainActor @preconcurrency struct MarkedValueLabel
Relationships
Conforms To
View
See Also
Setting the value
var value: Double
The current value of the gauge.
var currentValueLabel: GaugeStyleConfiguration.CurrentValueLabel?
A view that describes the current value.
struct CurrentValueLabel
A type-erased value label of a gauge that contains the current value.
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/maximumvaluelabel-swift.struct
- SwiftUI
- GaugeStyleConfiguration
- GaugeStyleConfiguration.MaximumValueLabel
Structure
GaugeStyleConfiguration.MaximumValueLabel
A type-erased value label of a gauge describing the maximum value.
@MainActor @preconcurrency struct MaximumValueLabel
Relationships
Conforms To
View
See Also
Reporting the range
var minimumValueLabel: GaugeStyleConfiguration.MinimumValueLabel?
A view that describes the minimum of the range for the current value.
struct MinimumValueLabel
A type-erased value label of a gauge describing the minimum value.
var maximumValueLabel: GaugeStyleConfiguration.MaximumValueLabel?
A view that describes the maximum of the range for the current value.
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/minimumvaluelabel-swift.struct
- SwiftUI
- GaugeStyleConfiguration
- GaugeStyleConfiguration.MinimumValueLabel
Structure
GaugeStyleConfiguration.MinimumValueLabel
A type-erased value label of a gauge describing the minimum value.
@MainActor @preconcurrency struct MinimumValueLabel
Relationships
Conforms To
View
See Also
Reporting the range
var minimumValueLabel: GaugeStyleConfiguration.MinimumValueLabel?
A view that describes the minimum of the range for the current value.
var maximumValueLabel: GaugeStyleConfiguration.MaximumValueLabel?
A view that describes the maximum of the range for the current value.
struct MaximumValueLabel
A type-erased value label of a gauge describing the maximum value.
https://developer.apple.com/documentation/swiftui/geometryreader
- SwiftUI
- GeometryReader
Structure
GeometryReader
A container view that defines its content as a function of its own size and coordinate space.
@frozen
Overview
This view returns a flexible preferred size to its parent layout.
Topics
Relationships
Conforms To
View
See Also
Measuring a view
struct GeometryReader3D
struct GeometryProxy
A proxy for access to the size and coordinate space (for anchor resolution) of the container view.
struct GeometryProxy3D
A proxy for access to the size and coordinate space of the container view.
Assigns a name to the view’s coordinate space, so other code can operate on dimensions like points and sizes relative to the named space.
enum CoordinateSpace
A resolved coordinate space created by the coordinate space protocol.
protocol CoordinateSpaceProtocol
A frame of reference within the layout system.
struct PhysicalMetric
Provides access to a value in points that corresponds to the specified physical measurement.
struct PhysicalMetricsConverter
A physical metrics converter provides conversion between point values and their extent in 3D space, in the form of physical length measurements.
https://developer.apple.com/documentation/swiftui/geometryreader3d
- SwiftUI
- GeometryReader3D
Structure
GeometryReader3D
A container view that defines its content as a function of its own size and coordinate space.
@frozen
Overview
This view returns a flexible preferred size to its own container view.
This container differs from GeometryReader in that it also reads available depth, and thus also returns a flexible preferred depth to its parent layout. Use the 3D version only in situations where you need to read depth, because it affects depth layout when used in a container like a ZStack.
Topics
Relationships
Conforms To
View
See Also
Measuring a view
struct GeometryReader
struct GeometryProxy
A proxy for access to the size and coordinate space (for anchor resolution) of the container view.
struct GeometryProxy3D
A proxy for access to the size and coordinate space of the container view.
Assigns a name to the view’s coordinate space, so other code can operate on dimensions like points and sizes relative to the named space.
enum CoordinateSpace
A resolved coordinate space created by the coordinate space protocol.
protocol CoordinateSpaceProtocol
A frame of reference within the layout system.
struct PhysicalMetric
Provides access to a value in points that corresponds to the specified physical measurement.
struct PhysicalMetricsConverter
A physical metrics converter provides conversion between point values and their extent in 3D space, in the form of physical length measurements.
https://developer.apple.com/documentation/swiftui/glassbackgroundeffectconfiguration/content-swift.struct
- SwiftUI
- GlassBackgroundEffectConfiguration
- GlassBackgroundEffectConfiguration.Content
Structure
GlassBackgroundEffectConfiguration.Content
A type-erased content of a glass background.
@MainActor @preconcurrency struct Content
Relationships
Conforms To
SendableSendableMetatypeView
https://developer.apple.com/documentation/swiftui/grid
- SwiftUI
- Grid
Structure
Grid
A container view that arranges other views in a two dimensional layout.
@frozen
Overview
Create a two dimensional layout by initializing a Grid with a collection of GridRow structures. The first view in each grid row appears in the grid’s first column, the second view in the second column, and so on. The following example creates a grid with two rows and two columns:
Grid { GridRow { Text("Hello") Image(systemName: "globe") } GridRow { Image(systemName: "hand.wave") Text("World") } }
A grid and its rows behave something like a collection of HStack instances wrapped in a VStack. However, the grid handles row and column creation as a single operation, which applies alignment and spacing to cells, rather than first to rows and then to a column of unrelated rows. The grid produced by the example above demonstrates this:
Multicolumn cells
If you provide a view rather than a GridRow as an element in the grid’s content, the grid uses the view to create a row that spans all of the grid’s columns. For example, you can add a Divider between the rows of the previous example:
Grid { GridRow { Text("Hello") Image(systemName: "globe") } Divider() GridRow { Image(systemName: "hand.wave") Text("World") } }
Because a divider takes as much horizontal space as its parent offers, the entire grid widens to fill the width offered by its parent view.
To prevent a flexible view from taking more space on a given axis than the other cells in a row or column require, add the gridCellUnsizedAxes(_:) view modifier to the view:
Divider() .gridCellUnsizedAxes(.horizontal)
This restores the grid to the width that the text and images require:
To make a cell span a specific number of columns rather than the whole grid, use the gridCellColumns(_:) modifier on a view that’s contained inside a GridRow.
Column count
The grid’s column count grows to handle the row with the largest number of columns. If you create rows with different numbers of columns, the grid adds empty cells to the trailing edge of rows that have fewer columns. The example below creates three rows with different column counts:
Grid { GridRow { Text("Row 1") ForEach(0..<2) { _ in Color.red } } GridRow { Text("Row 2") ForEach(0..<5) { _ in Color.green } } GridRow { Text("Row 3") ForEach(0..<4) { _ in Color.blue } } }
The resulting grid has as many columns as the widest row, adding empty cells to rows that don’t specify enough views:
The grid sets the width of all the cells in a column to match the needs of column’s widest cell. In the example above, the width of the first column depends on the width of the widest Text view that the column contains. The other columns, which contain flexible Color views, share the remaining horizontal space offered by the grid’s parent view equally.
Similarly, the tallest cell in a row sets the height of the entire row. The cells in the first column of the grid above need only the height required for each string, but the Color cells expand to equally share the total height available to the grid. As a result, the color cells determine the row heights.
Cell spacing and alignment
You can control the spacing between cells in both the horizontal and vertical dimensions and set a default alignment for the content in all the grid cells when you initialize the grid using the init(alignment:horizontalSpacing:verticalSpacing:content:) initializer. Consider a modified version of the previous example:
Grid(alignment: .bottom, horizontalSpacing: 1, verticalSpacing: 1) { // ... }
This configuration causes all of the cells to use bottom alignment — which only affects the text cells because the colors fill their cells completely — and it reduces the spacing between cells:
You can override the alignment of specific cells or groups of cells. For example, you can change the horizontal alignment of the cells in a column by adding the gridColumnAlignment(_:) modifier, or the vertical alignment of the cells in a row by configuring the row’s init(alignment:content:) initializer. You can also align a single cell with the gridCellAnchor(_:) modifier.
Performance considerations
A grid can size its rows and columns correctly because it renders all of its child views immediately. If your app exhibits poor performance when it first displays a large grid that appears inside a ScrollView, consider switching to a LazyVGrid or LazyHGrid instead.
Lazy grids render their cells when SwiftUI needs to display them, rather than all at once. This reduces the initial cost of displaying a large scrollable grid that’s never fully visible, but also reduces the grid’s ability to optimally lay out cells. Switch to a lazy grid only if profiling your code shows a worthwhile performance improvement.
Topics
Creating a grid
Creates a grid with the specified spacing, alignment, and child views.
Relationships
Conforms To
CopyableViewConforms whenContentconforms toView.
See Also
Statically arranging views in two dimensions
struct GridRow
A horizontal row in a two dimensional grid container.
Tells a view that acts as a cell in a grid to span the specified number of columns.
Specifies a custom alignment anchor for a view that acts as a grid cell.
Asks grid layouts not to offer the view extra size in the specified axes.
Overrides the default horizontal alignment of the grid column that the view appears in.
https://developer.apple.com/documentation/swiftui/gridrow
- SwiftUI
- GridRow
Structure
GridRow
A horizontal row in a two dimensional grid container.
@frozen
Overview
Use one or more GridRow instances to define the rows of a Grid container. The child views inside the row define successive grid cells. You can add rows to the grid explicitly, or use the ForEach structure to generate multiple rows. Similarly, you can add cells to the row explicitly or you can use ForEach to generate multiple cells inside the row. The following example mixes these strategies:
Grid { GridRow { Color.clear .gridCellUnsizedAxes([.horizontal, .vertical]) ForEach(1..<4) { column in Text("C(column)") } } ForEach(1..<4) { row in GridRow { Text("R(row)") ForEach(1..<4) { _ in Circle().foregroundStyle(.mint) } } } }
The grid in the example above has an explicit first row and three generated rows. Similarly, each row has an explicit first cell and three generated cells:
To create an empty cell, use something invisible, like the clear color that appears in the first column of the first row in the example above. However, if you use a flexible view like a Color or a Spacer, you might also need to add the gridCellUnsizedAxes(_:) modifier to prevent the view from taking up more space than the other cells in the row or column need.
By default, the cells in the row use the Alignment that you define when you initialize the Grid. However, you can override the vertical alignment for the cells in a row by providing a VerticalAlignment value to the row’s init(alignment:content:) initializer.
If you apply a view modifier to a row, the row applies the modifier to all of the cells, similar to how a Group behaves. For example, if you apply the border(_:width:) modifier to a row, SwiftUI draws a border on each cell in the row rather than around the row.
Topics
Creating a grid row
Creates a horizontal row of child views in a grid.
Relationships
Conforms To
CopyableViewConforms whenContentconforms toView.
See Also
Statically arranging views in two dimensions
struct Grid
A container view that arranges other views in a two dimensional layout.
Tells a view that acts as a cell in a grid to span the specified number of columns.
Specifies a custom alignment anchor for a view that acts as a grid cell.
Asks grid layouts not to offer the view extra size in the specified axes.
Overrides the default horizontal alignment of the grid column that the view appears in.
https://developer.apple.com/documentation/swiftui/group
- SwiftUI
- Group
Structure
Group
A type that collects multiple instances of a content type — like views, scenes, or commands — into a single unit.
@frozen
Overview
Use a group to collect multiple views into a single instance, without affecting the layout of those views, like an HStack, VStack, or Section would. After creating a group, any modifier you apply to the group affects all of that group’s members. For example, the following code applies the headline font to three views in a group.
Group { Text("SwiftUI") Text("Combine") Text("Swift System") } .font(.headline)
Because you create a group of views with a ViewBuilder, you can use the group’s initializer to produce different kinds of views from a conditional, and then optionally apply modifiers to them. The following example uses a Group to add a navigation bar title, regardless of the type of view the conditional produces:
Group { if isLoggedIn { WelcomeView() } else { LoginView() } } .navigationBarTitle("Start")
The modifier applies to all members of the group — and not to the group itself. For example, if you apply onAppear(perform:) to the above group, it applies to all of the views produced by the if isLoggedIn conditional, and it executes every time isLoggedIn changes.
Because a group of views itself is a view, you can compose a group within other view builders, including nesting within other groups. This allows you to add large numbers of views to different view builder containers. The following example uses a Group to collect 10 Text instances, meaning that the vertical stack’s view builder returns only two views — the group, plus an additional Text:
var body: some View { VStack { Group { Text("1") Text("2") Text("3") Text("4") Text("5") Text("6") Text("7") Text("8") Text("9") Text("10") } Text("11") } }
You can initialize groups with several types other than View, such as Scene and ToolbarContent. The closure you provide to the group initializer uses the corresponding builder type ( SceneBuilder, ToolbarContentBuilder, and so on), and the capabilities of these builders vary between types. For example, you can use groups to return large numbers of scenes or toolbar content instances, but not to return different scenes or toolbar content based on conditionals.
Topics
Creating a group
init(content:)
Creates an instance that generates Rotor content by combining, in order, all the Rotor content specified in the passed-in result builder.
Initializers
Constructs a group from the sections of the given view.
Constructs a group from the subviews of the given view.
Relationships
Conforms To
-
AccessibilityRotorContentConforms whenContentconforms toAccessibilityRotorContent. -
CommandsConforms whenContentconforms toCommands. -
Copyable -
CustomizableToolbarContentConforms whenContentconforms toCustomizableToolbarContent. -
MapContent -
SceneConforms whenContentconforms toScene. -
TabContentConforms whenContentconforms toTabContent. -
TableColumnContentConforms whenContentconforms toTableColumnContent. -
TableRowContentConforms whenContentconforms toTableRowContent. -
ToolbarContentConforms whenContentconforms toToolbarContent. -
ViewConforms whenContentconforms toView.
See Also
Grouping views into a container
Creating custom container views
Access individual subviews to compose flexible container views.
struct GroupElementsOfContent
Transforms the subviews of a given view into a resulting content view.
struct GroupSectionsOfContent
Transforms the sections of a given view into a resulting content view.
https://developer.apple.com/documentation/swiftui/groupbox
- SwiftUI
- GroupBox
Structure
GroupBox
A stylized view, with an optional label, that visually collects a logical grouping of content.
Overview
Use a group box when you want to visually distinguish a portion of your user interface with an optional title for the boxed content.
The following example sets up a GroupBox with the label “End-User Agreement”, and a long agreementText string in a Text view wrapped by a ScrollView. The box also contains a Toggle for the user to interact with after reading the text.
var body: some View { GroupBox(label: Label("End-User Agreement", systemImage: "building.columns") ) { ScrollView(.vertical, showsIndicators: true) { Text(agreementText) .font(.footnote) } .frame(height: 100) Toggle(isOn: $userAgreed) { Text("I agree to the above terms") } } }
Topics
Creating a group box
Creates an unlabeled group box with the provided view content.
Creates a group box with the provided label and view content.
init(_:content:)
Creates a group box with the provided view content and title.
Creating a group box from a configuration
init(GroupBoxStyleConfiguration)
Creates a group box based on a style configuration.
Relationships
Conforms To
View
See Also
Grouping views into a box
Sets the style for group boxes within this view.
https://developer.apple.com/documentation/swiftui/groupboxstyleconfiguration/content-swift.struct
- SwiftUI
- GroupBoxStyleConfiguration
- GroupBoxStyleConfiguration.Content
Structure
GroupBoxStyleConfiguration.Content
A type-erased content of a group box.
@MainActor @preconcurrency struct Content
Relationships
Conforms To
View
See Also
Configuring the content
let content: GroupBoxStyleConfiguration.Content
A view that represents the content of the group box.
https://developer.apple.com/documentation/swiftui/groupboxstyleconfiguration/label-swift.struct
https://developer.apple.com/documentation/swiftui/groupelementsofcontent
- SwiftUI
- GroupElementsOfContent
Structure
GroupElementsOfContent
Transforms the subviews of a given view into a resulting content view.
Overview
You don’t use this type directly. Instead SwiftUI creates this type on your behalf.
Relationships
Conforms To
View
See Also
Grouping views into a container
Creating custom container views
Access individual subviews to compose flexible container views.
struct Group
A type that collects multiple instances of a content type — like views, scenes, or commands — into a single unit.
struct GroupSectionsOfContent
Transforms the sections of a given view into a resulting content view.
https://developer.apple.com/documentation/swiftui/groupsectionsofcontent
- SwiftUI
- GroupSectionsOfContent
Structure
GroupSectionsOfContent
Transforms the sections of a given view into a resulting content view.
Overview
You don’t use this type directly. Instead SwiftUI creates this type on your behalf.
Relationships
Conforms To
View
See Also
Grouping views into a container
Creating custom container views
Access individual subviews to compose flexible container views.
struct Group
A type that collects multiple instances of a content type — like views, scenes, or commands — into a single unit.
struct GroupElementsOfContent
Transforms the subviews of a given view into a resulting content view.
https://developer.apple.com/documentation/swiftui/hstack
- SwiftUI
- HStack
Structure
HStack
A view that arranges its subviews in a horizontal line.
@frozen
Mentioned in
Laying out a simple view
Building layouts with stack views
Creating performant scrollable stacks
Aligning views within a stack
Aligning views across stacks
Overview
Unlike LazyHStack, which only renders the views when your app needs to display them onscreen, an HStack renders the views all at once, regardless of whether they are on- or offscreen. Use the regular HStack when you have a small number of subviews or don’t want the delayed rendering behavior of the “lazy” version.
The following example shows a simple horizontal stack of five text views:
var body: some View { HStack( alignment: .top, spacing: 10 ) { ForEach( 1...5, id: .self ) { Text("Item ($0)") } } }
Topics
Creating a stack
Creates a horizontal stack with the given spacing and vertical alignment.
Relationships
Conforms To
View
See Also
Statically arranging views in one dimension
Compose complex layouts from primitive container views.
struct VStack
A view that arranges its subviews in a vertical line.
https://developer.apple.com/documentation/swiftui/helplink
- SwiftUI
- HelpLink
Structure
HelpLink
A button with a standard appearance that opens app-specific help documentation.
struct HelpLink
Overview
A help link opens documentation relevant to the context where they are used. Typically this is by opening to an anchor in an Apple Help book, but can also perform an arbitrary action such as opening a URL or opening a window.
HelpLink(anchor: "accountSetupHelp")
HelpLink { openURL(onlineHelpURL) }
Help links have a standard appearance, as well as conventional placement within a view. When used within an alert or confirmation dialog’s actions, the help link will automatically be placed in the top trailing corner. Or when used in a sheet toolbar, the help link is automatically placed in the lower leading corner.
struct SheetContentView: View { var body: some View { Form { ... } .toolbar { ToolbarItem(.confirmationAction) { Button("Save") { ... } } ToolbarItem(.cancellationAction) { Button("Cancel") { ... } } ToolbarItem { HelpLink(anchor: "sheetHelp") } } } }
Topics
Creating a help link
Constructs a new help link with the specified action.
init(destination: URL)
Constructs a new help link that opens the specified destination URL.
init(anchor: NSHelpManager.AnchorName)
Constructs a new help link with the specified anchor in the main app bundle’s book.
init(anchor: NSHelpManager.AnchorName, book: NSHelpManager.BookName)
Constructs a new help link with the specified anchor and book.
Relationships
Conforms To
View
See Also
Linking to other content
struct Link
A control for navigating to a URL.
struct ShareLink
A view that controls a sharing presentation.
struct SharePreview
A representation of a type to display in a share preview.
struct TextFieldLink
A control that requests text input from the user when pressed.
https://developer.apple.com/documentation/swiftui/keyframeanimator
- SwiftUI
- KeyframeAnimator
Structure
KeyframeAnimator
A container that animates its content with keyframes.
Overview
The content closure updates every frame while animating, so avoid performing any expensive operations directly within content.
Topics
Creating a phase animator
Loops the given keyframes continuously, updating the view using the modifiers you apply in body.
Plays the given keyframes when the given trigger value changes, updating the view using the modifiers you apply in body.
Relationships
Conforms To
View
See Also
Creating keyframe-based animation
protocol Keyframes
A type that defines changes to a value over time.
struct KeyframeTimeline
A description of how a value changes over time, modeled using keyframes.
struct KeyframeTrack
A sequence of keyframes animating a single property of a root type.
struct KeyframeTrackContentBuilder
The builder that creates keyframe track content from the keyframes that you define within a closure.
struct KeyframesBuilder
A builder that combines keyframe content values into a single value.
protocol KeyframeTrackContent
A group of keyframes that define an interpolation curve of an animatable value.
struct CubicKeyframe
A keyframe that uses a cubic curve to smoothly interpolate between values.
struct LinearKeyframe
A keyframe that uses simple linear interpolation.
struct MoveKeyframe
A keyframe that immediately moves to the given value without interpolating.
struct SpringKeyframe
A keyframe that uses a spring function to interpolate to the given value.
https://developer.apple.com/documentation/swiftui/label
- SwiftUI
- Label
Structure
Label
A standard label for user interface items, consisting of an icon with a title.
Mentioned in
Performing a search operation
Preparing views for localization
Populating SwiftUI menus with adaptive controls
Overview
One of the most common and recognizable user interface components is the combination of an icon and a label. This idiom appears across many kinds of apps and shows up in collections, lists, menus of action items, and disclosable lists, just to name a few.
You create a label, in its simplest form, by providing a title and the name of an image, such as an icon from the SF Symbols collection:
Label("Lightning", systemImage: "bolt.fill")
You can also apply styles to labels in several ways. In the case of dynamic changes to the view after device rotation or change to a window size you might want to show only the text portion of the label using the titleOnly label style:
Label("Lightning", systemImage: "bolt.fill") .labelStyle(.titleOnly)
Conversely, there’s also an icon-only label style:
Label("Lightning", systemImage: "bolt.fill") .labelStyle(.iconOnly)
Some containers might apply a different default label style, such as only showing icons within toolbars on macOS and iOS. To opt in to showing both the title and the icon, you can apply the titleAndIcon label style:
Label("Lightning", systemImage: "bolt.fill") .labelStyle(.titleAndIcon)
You can also create a customized label style by modifying an existing style; this example adds a red border to the default label style:
struct RedBorderedLabelStyle: LabelStyle {
Label(configuration) .border(Color.red) } }
For more extensive customization or to create a completely new label style, you’ll need to adopt the LabelStyle protocol and implement a LabelStyleConfiguration for the new style.
To apply a common label style to a group of labels, apply the style to the view hierarchy that contains the labels:
VStack { Label("Rain", systemImage: "cloud.rain") Label("Snow", systemImage: "snow") Label("Sun", systemImage: "sun.max") } .labelStyle(.iconOnly)
It’s also possible to make labels using views to compose the label’s icon programmatically, rather than using a pre-made image. In this example, the icon portion of the label uses a filled Circle overlaid with the user’s initials:
Label { Text(person.fullName) .font(.body) .foregroundColor(.primary) Text(person.title) .font(.subheadline) .foregroundColor(.secondary) } icon: { Circle() .fill(person.profileColor) .frame(width: 44, height: 44, alignment: .center) .overlay(Text(person.initials)) }
Topics
Creating a label
init(_:image:)
Creates a label with an icon image and a title generated from a localized string.
init(_:systemImage:)
Creates a label with a system icon image and a title generated from a localized string.
Creates a label with a custom title and icon.
init(_:)
Creates a label representing a family activity application.
Relationships
Conforms To
View
See Also
Displaying text
struct Text
A view that displays one or more lines of read-only text.
Sets the style for labels within this view.
https://developer.apple.com/documentation/swiftui/labelstyleconfiguration/icon-swift.struct
- SwiftUI
- LabelStyleConfiguration
- LabelStyleConfiguration.Icon
Structure
LabelStyleConfiguration.Icon
A type-erased icon view of a label.
@MainActor @preconcurrency struct Icon
Relationships
Conforms To
CopyableView
See Also
Setting the icon
var icon: LabelStyleConfiguration.Icon
A symbolic representation of the labeled item.
https://developer.apple.com/documentation/swiftui/labelstyleconfiguration/title-swift.struct
- SwiftUI
- LabelStyleConfiguration
- LabelStyleConfiguration.Title
Structure
LabelStyleConfiguration.Title
A type-erased title view of a label.
@MainActor @preconcurrency struct Title
Relationships
Conforms To
CopyableView
See Also
Setting the title
var title: LabelStyleConfiguration.Title
A description of the labeled item.
https://developer.apple.com/documentation/swiftui/labeledcontent
https://developer.apple.com/documentation/swiftui/labeledcontentstyleconfiguration/content-swift.struct
- SwiftUI
- LabeledContentStyleConfiguration
- LabeledContentStyleConfiguration.Content
Structure
LabeledContentStyleConfiguration.Content
A type-erased content of a labeled content instance.
@MainActor @preconcurrency struct Content
Relationships
Conforms To
View
See Also
Configuring the content
let content: LabeledContentStyleConfiguration.Content
The content of the labeled content instance.
https://developer.apple.com/documentation/swiftui/labeledcontentstyleconfiguration/label-swift.struct
- SwiftUI
- LabeledContentStyleConfiguration
- LabeledContentStyleConfiguration.Label
Structure
LabeledContentStyleConfiguration.Label
A type-erased label of a labeled content instance.
@MainActor @preconcurrency struct Label
Relationships
Conforms To
View
See Also
Configuring the label
let label: LabeledContentStyleConfiguration.Label
The label of the labeled content instance.
https://developer.apple.com/documentation/swiftui/labeledcontrolgroupcontent
- SwiftUI
- LabeledControlGroupContent
Structure
LabeledControlGroupContent
A view that represents the body of a control group with a specified label.
Overview
You don’t create this type directly. SwiftUI creates it when you build a ControlGroup.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/labeledtoolbaritemgroupcontent
- SwiftUI
- LabeledToolbarItemGroupContent
Structure
LabeledToolbarItemGroupContent
A view that represents the view of a toolbar item group with a specified label.
Overview
You don’t create this type directly. SwiftUI creates it when you build a ToolbarItemGroup.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/lazyhgrid
- SwiftUI
- LazyHGrid
Structure
LazyHGrid
A container view that arranges its child views in a grid that grows horizontally, creating items only as needed.
Mentioned in
Picking container views for your content
Overview
Use a lazy horizontal grid when you want to display a large, horizontally scrollable collection of views arranged in a two dimensional layout. The first view that you provide to the grid’s content closure appears in the top row of the column that’s on the grid’s leading edge. Additional views occupy successive cells in the grid, filling the first column from top to bottom, then the second column, and so on. The number of columns can grow unbounded, but you specify the number of rows by providing a corresponding number of GridItem instances to the grid’s initializer.
The grid in the following example defines two rows and uses a ForEach structure to repeatedly generate a pair of Text views for the rows in each column:
struct HorizontalSmileys: View { let rows = [GridItem(.fixed(30)), GridItem(.fixed(30))]
var body: some View { ScrollView(.horizontal) { LazyHGrid(rows: rows) { ForEach(0x1f600...0x1f679, id: .self) { value in Text(String(format: "%x", value)) Text(emoji(value)) .font(.largeTitle) } } } }
guard let scalar = UnicodeScalar(value) else { return "?" } return String(Character(scalar)) } }
For each column in the grid, the top row shows a Unicode code point from the “Smileys” group, and the bottom shows its corresponding emoji:
You can achieve a similar layout using a Grid container. Unlike a lazy grid, which creates child views only when SwiftUI needs to display them, a regular grid creates all of its child views right away. This enables the grid to provide better support for cell spacing and alignment. Only use a lazy grid if profiling your app shows that a Grid view performs poorly because it tries to load too many views at once.
Topics
Creating a horizontal grid
Creates a grid that grows horizontally.
Relationships
Conforms To
View
See Also
Dynamically arranging views in two dimensions
struct LazyVGrid
A container view that arranges its child views in a grid that grows vertically, creating items only as needed.
struct GridItem
A description of a row or a column in a lazy grid.
https://developer.apple.com/documentation/swiftui/lazyhstack
- SwiftUI
- LazyHStack
Structure
LazyHStack
A view that arranges its children in a line that grows horizontally, creating items only as needed.
Mentioned in
Picking container views for your content
Grouping data with lazy stack views
Creating performant scrollable stacks
Overview
The stack is “lazy,” in that the stack view doesn’t create items until it needs to render them onscreen.
In the following example, a ScrollView contains a LazyHStack that consists of a horizontal row of text views. The stack aligns to the top of the scroll view and uses 10-point spacing between each text view.
ScrollView(.horizontal) { LazyHStack(alignment: .top, spacing: 10) { ForEach(1...100, id: .self) { Text("Column ($0)") } } }
Topics
Creating a lazy-loading horizontal stack
Creates a lazy horizontal stack view with the given spacing, vertical alignment, pinning behavior, and content.
Relationships
Conforms To
View
See Also
Dynamically arranging views in one dimension
Split content into logical sections inside lazy stack views.
Display large numbers of repeated views efficiently with scroll views, stack views, and lazy stacks.
struct LazyVStack
A view that arranges its children in a line that grows vertically, creating items only as needed.
struct PinnedScrollableViews
A set of view types that may be pinned to the bounds of a scroll view.
https://developer.apple.com/documentation/swiftui/lazyvgrid
- SwiftUI
- LazyVGrid
Structure
LazyVGrid
A container view that arranges its child views in a grid that grows vertically, creating items only as needed.
Mentioned in
Picking container views for your content
Overview
Use a lazy vertical grid when you want to display a large, vertically scrollable collection of views arranged in a two dimensional layout. The first view that you provide to the grid’s content closure appears in the top row of the column that’s on the grid’s leading edge. Additional views occupy successive cells in the grid, filling the first row from leading to trailing edges, then the second row, and so on. The number of rows can grow unbounded, but you specify the number of columns by providing a corresponding number of GridItem instances to the grid’s initializer.
The grid in the following example defines two columns and uses a ForEach structure to repeatedly generate a pair of Text views for the columns in each row:
struct VerticalSmileys: View { let columns = [GridItem(.flexible()), GridItem(.flexible())]
var body: some View { ScrollView { LazyVGrid(columns: columns) { ForEach(0x1f600...0x1f679, id: .self) { value in Text(String(format: "%x", value)) Text(emoji(value)) .font(.largeTitle) } } } }
guard let scalar = UnicodeScalar(value) else { return "?" } return String(Character(scalar)) } }
For each row in the grid, the first column shows a Unicode code point from the “Smileys” group, and the second shows its corresponding emoji:
You can achieve a similar layout using a Grid container. Unlike a lazy grid, which creates child views only when SwiftUI needs to display them, a regular grid creates all of its child views right away. This enables the grid to provide better support for cell spacing and alignment. Only use a lazy grid if profiling your app shows that a Grid view performs poorly because it tries to load too many views at once.
Topics
Creating a vertical grid
Creates a grid that grows vertically.
Relationships
Conforms To
View
See Also
Dynamically arranging views in two dimensions
struct LazyHGrid
A container view that arranges its child views in a grid that grows horizontally, creating items only as needed.
struct GridItem
A description of a row or a column in a lazy grid.
https://developer.apple.com/documentation/swiftui/lazyvstack
- SwiftUI
- LazyVStack
Structure
LazyVStack
A view that arranges its children in a line that grows vertically, creating items only as needed.
Mentioned in
Grouping data with lazy stack views
Picking container views for your content
Displaying data in lists
Creating performant scrollable stacks
Overview
The stack is “lazy,” in that the stack view doesn’t create items until it needs to render them onscreen.
In the following example, a ScrollView contains a LazyVStack that consists of a vertical row of text views. The stack aligns to the leading edge of the scroll view, and uses default spacing between the text views.
ScrollView { LazyVStack(alignment: .leading) { ForEach(1...100, id: .self) { Text("Row ($0)") } } }
Topics
Creating a lazy-loading vertical stack
Creates a lazy vertical stack view with the given spacing, vertical alignment, pinning behavior, and content.
Relationships
Conforms To
View
See Also
Dynamically arranging views in one dimension
Split content into logical sections inside lazy stack views.
Display large numbers of repeated views efficiently with scroll views, stack views, and lazy stacks.
struct LazyHStack
A view that arranges its children in a line that grows horizontally, creating items only as needed.
struct PinnedScrollableViews
A set of view types that may be pinned to the bounds of a scroll view.
https://developer.apple.com/documentation/swiftui/lineargradient
https://developer.apple.com/documentation/swiftui/link
- SwiftUI
- Link
Structure
Link
A control for navigating to a URL.
@MainActor @preconcurrency
Overview
Create a link by providing a destination URL and a title. The title tells the user the purpose of the link, and can be a string, a title key that produces a localized string, or a view that acts as a label. The example below creates a link to example.com and displays the title string as a link-styled view:
Link("View Our ", destination: URL(string: "https://www.example.com/TOS.html")!)
When a user taps or clicks a Link, the default behavior depends on the contents of the URL. For example, SwiftUI opens a Universal Link in the associated app if possible, or in the user’s default web browser if not. Alternatively, you can override the default behavior by setting the openURL environment value with a custom OpenURLAction:
Link("Visit Our Site", destination: URL(string: "https://www.example.com")!) .environment(.openURL, OpenURLAction { url in print("Open (url)") return .handled })
As with other views, you can style links using standard view modifiers depending on the view type of the link’s label. For example, a Text label could be modified with a custom font(_:) or foregroundColor(_:) to customize the appearance of the link in your app’s UI.
Topics
Creating a link
init(_:destination:)
Creates a control, consisting of a URL and a title key, used to navigate to a URL.
Creates a control, consisting of a URL and a label, used to navigate to the given URL.
Relationships
Conforms To
View
See Also
Linking to other content
struct ShareLink
A view that controls a sharing presentation.
struct SharePreview
A representation of a type to display in a share preview.
struct TextFieldLink
A control that requests text input from the user when pressed.
struct HelpLink
A button with a standard appearance that opens app-specific help documentation.
https://developer.apple.com/documentation/swiftui/list
- SwiftUI
- List
Structure
List
A container that presents rows of data arranged in a single column, optionally providing the ability to select one or more members.
@MainActor @preconcurrency
Mentioned in
Picking container views for your content
Displaying data in lists
Grouping data with lazy stack views
Migrating to new navigation types
Making a view into a drag source
Overview
In its simplest form, a List creates its contents statically, as shown in the following example:
var body: some View { List { Text("A List Item") Text("A Second List Item") Text("A Third List Item") } }
More commonly, you create lists dynamically from an underlying collection of data. The following example shows how to create a simple list from an array of an Ocean type which conforms to Identifiable:
struct Ocean: Identifiable { let name: String let id = UUID() }
private var oceans = [
Ocean(name: "Pacific"),
Ocean(name: "Atlantic"),
Ocean(name: "Indian"),
Ocean(name: "Southern"),
Ocean(name: "Arctic")
]
var body: some View { List(oceans) { Text($0.name) } }
Supporting selection in lists
To make members of a list selectable, provide a binding to a selection variable. Binding to a single instance of the list data’s Identifiable.ID type creates a single-selection list. Binding to a Set creates a list that supports multiple selections. The following example shows how to add multiselect to the previous example:
struct Ocean: Identifiable, Hashable { let name: String let id = UUID() }
var body: some View { NavigationView { List(oceans, selection: $multiSelection) { Text($0.name) } .navigationTitle("Oceans") .toolbar { EditButton() } } Text("(multiSelection.count) selections") }
When people make a single selection by tapping or clicking, the selected cell changes its appearance to indicate the selection. To enable multiple selections with tap gestures, put the list into edit mode by either modifying the editMode value, or adding an EditButton to your app’s interface. When you put the list into edit mode, the list shows a circle next to each list item. The circle contains a checkmark when the user selects the associated item. The example above uses an Edit button, which changes its title to Done while in edit mode:
People can make multiple selections without needing to enter edit mode on devices that have a keyboard and mouse or trackpad, like Mac and iPad.
Refreshing the list content
To make the content of the list refreshable using the standard refresh control, use the refreshable(action:) modifier.
The following example shows how to add a standard refresh control to a list. When the user drags the top of the list downward, SwiftUI reveals the refresh control and executes the specified action. Use an await expression inside the action closure to refresh your data. The refresh indicator remains visible for the duration of the awaited operation.
struct Ocean: Identifiable, Hashable { let name: String let id = UUID() let stats: [String: String] }
class OceanStore: ObservableObject { @Published var oceans = Ocean func loadStats() async {} }
@EnvironmentObject var store: OceanStore
var body: some View { NavigationView { List(store.oceans) { ocean in HStack { Text(ocean.name) StatsSummary(stats: ocean.stats) // A custom view for showing statistics. } } .refreshable { await store.loadStats() } .navigationTitle("Oceans") } }
Supporting multidimensional lists
To create two-dimensional lists, group items inside Section instances. The following example creates sections named after the world’s oceans, each of which has Text views named for major seas attached to those oceans. The example also allows for selection of a single list item, identified by the id of the example’s Sea type.
struct ContentView: View { struct Sea: Hashable, Identifiable { let name: String let id = UUID() }
struct OceanRegion: Identifiable { let name: String let seas: [Sea] let id = UUID() }
private let oceanRegions: [OceanRegion] = [
OceanRegion(name: "Pacific",
seas: [Sea(name: "Australasian Mediterranean"),
Sea(name: "Philippine"),
Sea(name: "Coral"),
Sea(name: "South China")]),
OceanRegion(name: "Atlantic",
seas: [Sea(name: "American Mediterranean"),
Sea(name: "Sargasso"),
Sea(name: "Caribbean")]),
OceanRegion(name: "Indian",
seas: [Sea(name: "Bay of Bengal")]),
OceanRegion(name: "Southern",
seas: [Sea(name: "Weddell")]),
OceanRegion(name: "Arctic",
seas: [Sea(name: "Greenland")])
]
@State private var singleSelection: UUID?
var body: some View { NavigationView { List(selection: $singleSelection) { ForEach(oceanRegions) { region in Section(header: Text("Major (region.name) Ocean Seas")) { ForEach(region.seas) { sea in Text(sea.name) } } } } .navigationTitle("Oceans and Seas") } } }
Because this example uses single selection, people can make selections outside of edit mode on all platforms.
Creating hierarchical lists
You can also create a hierarchical list of arbitrary depth by providing tree-structured data and a children parameter that provides a key path to get the child nodes at any level. The following example uses a deeply-nested collection of a custom FileItem type to simulate the contents of a file system. The list created from this data uses collapsing cells to allow the user to navigate the tree structure.
struct ContentView: View {
struct FileItem: Hashable, Identifiable, CustomStringConvertible {
var id: Self { self }
var name: String
var children: [FileItem]? = nil
var description: String {
switch children {
case nil:
return "📄 (name)"
case .some(let children):
return children.isEmpty ? "📂 (name)" : "📁 (name)"
}
}
}
let fileHierarchyData: [FileItem] = [
FileItem(name: "users", children:
[FileItem(name: "user1234", children:
[FileItem(name: "Photos", children:
[FileItem(name: "photo001.jpg"),
FileItem(name: "photo002.jpg")]),
FileItem(name: "Movies", children:
[FileItem(name: "movie001.mp4")]),
FileItem(name: "Documents", children: [])
]),
FileItem(name: "newuser", children:
[FileItem(name: "Documents", children: [])
])
]),
FileItem(name: "private", children: nil)
]
var body: some View {
List(fileHierarchyData, children: .children) { item in
Text(item.description)
}
}
}
Styling lists
SwiftUI chooses a display style for a list based on the platform and the view type in which it appears. Use the listStyle(_:) modifier to apply a different ListStyle to all lists within a view. For example, adding .listStyle(.plain) to the example shown in the “Creating Multidimensional Lists” topic applies the plain style, the following screenshot shows:
Topics
Creating a list from a set of views
Creates a list with the given content.
init(selection:content:)
Creates a list with the given content that supports selecting a single row that cannot be deselcted.
Creating a list from enumerated data
init(_:rowContent:)
Creates a list that computes its rows on demand from an underlying collection of identifiable data.
init(_:selection:rowContent:)
Creates a list that computes its rows on demand from an underlying collection of identifiable data, optionally allowing users to select a single row.
init(_:id:rowContent:)
Creates a list that identifies its rows based on a key path to the identifier of the underlying data.
init(_:id:selection:rowContent:)
Creates a list that identifies its rows based on a key path to the identifier of the underlying data, optionally allowing users to select a single row.
Creating a list from hierarchical data
init(_:children:rowContent:)
Creates a hierarchical list that computes its rows on demand from a binding to an underlying collection of identifiable data.
init(_:children:selection:rowContent:)
Creates a hierarchical list that computes its rows on demand from a binding to an underlying collection of identifiable data and allowing users to have exactly one row always selected.
init(_:id:children:rowContent:)
Creates a hierarchical list that identifies its rows based on a key path to the identifier of the underlying data.
init(_:id:children:selection:rowContent:)
Creates a hierarchical list that identifies its rows based on a key path to the identifier of the underlying data and allowing users to have exactly one row always selected.
Creating a list from editable data
Creates a list that computes its rows on demand from an underlying collection of identifiable data and allows to edit the collection.
init(_:editActions:selection:rowContent:)
Creates a list that computes its rows on demand from an underlying collection of identifiable data, allows to edit the collection, and requires a selection of a single row.
init(_:id:editActions:selection:rowContent:)
Creates a list that computes its rows on demand from an underlying collection of identifiable, allows to edit the collection, and requires a selection of a single row.
Supporting types
var body: some View
The content of the list.
Relationships
Conforms To
View
See Also
Creating a list
Visualize collections of data with platform-appropriate appearance.
Sets the style for lists within this view.
https://developer.apple.com/documentation/swiftui/menu
- SwiftUI
- Menu
Structure
Menu
A control for presenting a menu of actions.
Mentioned in
Populating SwiftUI menus with adaptive controls
Building and customizing the menu bar with SwiftUI
Overview
The following example presents a menu of three buttons and a submenu, which contains three buttons of its own.
Menu("Actions") { Button("Duplicate", action: duplicate) Button("Rename", action: rename) Button("Delete…", action: delete) Menu("Copy") { Button("Copy", action: copy) Button("Copy Formatted", action: copyFormatted) Button("Copy Library Path", action: copyPath) } }
You can create the menu’s title with a LocalizedStringKey, as seen in the previous example, or with a view builder that creates multiple views, such as an image and a text view:
Menu { Button("Open in Preview", action: openInPreview) Button("Save as PDF", action: saveAsPDF) } label: { Label("PDF", systemImage: "doc.fill") }
To support subtitles on menu items, initialize your Button with a view builder that creates multiple Text views where the first text represents the title and the second text represents the subtitle. The same approach applies to other controls such as Toggle:
Menu { Button(action: openInPreview) { Text("Open in Preview") Text("View the document in Preview") } Button(action: saveAsPDF) { Text("Save as PDF") Text("Export the document as a PDF file") } } label: { Label("PDF", systemImage: "doc.fill") }
Primary action
Menus can be created with a custom primary action. The primary action will be performed when the user taps or clicks on the body of the control, and the menu presentation will happen on a secondary gesture, such as on long press or on click of the menu indicator. The following example creates a menu that adds bookmarks, with advanced options that are presented in a menu.
Menu { Button(action: addCurrentTabToReadingList) { Label("Add to Reading List", systemImage: "eyeglasses") } Button(action: bookmarkAll) { Label("Add Bookmarks for All Tabs", systemImage: "book") } Button(action: show) { Label("Show All Bookmarks", systemImage: "books.vertical") } } label: { Label("Add Bookmark", systemImage: "book") } primaryAction: { addBookmark() }
Styling menus
Use the menuStyle(_:) modifier to change the style of all menus in a view. The following example shows how to apply a custom style:
Menu("Editing") { Button("Set In Point", action: setInPoint) Button("Set Out Point", action: setOutPoint) } .menuStyle(EditingControlsMenuStyle())
Topics
Creating a menu from content
init(_:content:)
Creates a menu that generates its label from a localized string key.
Creates a menu with a custom label.
init(_:image:content:)
Creates a menu that generates its label from a localized string key and image resource.
init(_:systemImage:content:)
Creates a menu that generates its label from a localized string key and system image.
Creating a menu with a primary action
init(_:content:primaryAction:)
Creates a menu with a custom primary action that generates its label from a localized string key.
Creates a menu with a custom primary action and custom label.
init(_:image:content:primaryAction:)
init(_:systemImage:content:primaryAction:)
Creates a menu with a custom primary action that generates its label from a localized string key and system image.
Creating a menu from a configuration
init(MenuStyleConfiguration)
Creates a menu based on a style configuration.
Relationships
Conforms To
View
See Also
Creating a menu
Improve your app by populating menus with controls and organizing your content intuitively.
Sets the style for menus within this view.
https://developer.apple.com/documentation/swiftui/menubutton
- SwiftUI
- MenuButton Deprecated
Structure
MenuButton
A button that displays a menu containing a list of choices when pressed.
macOS 10.15–26.0Deprecated
Topics
Creating a menu button
init(_:content:)
Creates a menu button with the specified localized title and content.
Creates a menu button with the specified label and content.
Styling a menu button
Sets the style for menu buttons within this view.
protocol MenuButtonStyle
A custom specification for the appearance and interaction of a menu button.
Relationships
Conforms To
View
See Also
Deprecated types
typealias PullDownButton Deprecated
struct ContextMenu
A container for views that you present as menu items in a context menu.
Deprecated
https://developer.apple.com/documentation/swiftui/menustyleconfiguration/content
https://developer.apple.com/documentation/swiftui/menustyleconfiguration/label
- SwiftUI
- MenuStyleConfiguration
- MenuStyleConfiguration.Label
Structure
MenuStyleConfiguration.Label
A type-erased label of a menu.
@MainActor @preconcurrency struct Label
Relationships
Conforms To
View
See Also
Setting the label and content
struct Content
A type-erased content of a menu.
https://developer.apple.com/documentation/swiftui/meshgradient
- SwiftUI
- MeshGradient
Structure
MeshGradient
A two-dimensional gradient defined by a 2D grid of positioned colors.
struct MeshGradient
Overview
Each vertex has a position, a color and four surrounding Bezier control points (leading, top, trailing, bottom) that define the tangents connecting the vertex with its four neighboring vertices. (Vertices on the corners or edges of the mesh have less than four neighbors, they ignore their extra control points.) Control points may either be specified explicitly or implicitly.
When rendering, a tessellated sequence of Bezier patches are created, and vertex colors are interpolated across each patch, either linearly, or via another set of cubic curves derived from how the colors change between neighbors – the latter typically gives smoother color transitions.
MeshGradient(width: 3, height: 3, points: [
.init(0, 0), .init(0.5, 0), .init(1, 0),
.init(0, 0.5), .init(0.5, 0.5), .init(1, 0.5),
.init(0, 1), .init(0.5, 1), .init(1, 1)
], colors: [
.red, .purple, .indigo,
.orange, .white, .blue,
.yellow, .green, .mint
])
Topics
Structures
struct BezierPoint
One location in a gradient mesh, along with the four Bezier control points surrounding it.
Initializers
Creates a new gradient mesh specified as a 2D grid of colored points, specifying the Bezier control points explicitly.
Creates a new gradient mesh specified as a 2D grid of colored points, specifying the Bezier control points explicitly, with already-resolved sRGB colors.
init(width: Int, height: Int, locations: MeshGradient.Locations, colors: MeshGradient.Colors, background: Color, smoothsColors: Bool, colorSpace: Gradient.ColorSpace)
Creates a new gradient mesh specified as a 2D grid of colored vertices.
Creates a new gradient mesh specified as a 2D grid of colored points.
Creates a new gradient mesh specified as a 2D grid of colored points, with already-resolved sRGB colors.
Instance Properties
var background: Color
The background color, this fills any points outside the defined vertex mesh.
var colorSpace: Gradient.ColorSpace
The color space in which to interpolate vertex colors.
var colors: MeshGradient.Colors
The array of colors. Must contain width x height elements.
var height: Int
The height of the mesh, i.e. the number of vertices per column.
var locations: MeshGradient.Locations
The array of locations. Must contain width x height elements.
var smoothsColors: Bool
Whether cubic (smooth) interpolation should be used for the colors in the mesh (rather than only for the shape of the mesh).
var width: Int
The width of the mesh, i.e. the number of vertices per row.
Enumerations
enum Colors
An array of colors.
enum Locations
An array of 2D locations and their control points.
Relationships
Conforms To
CopyableEquatableSendableSendableMetatypeShapeStyleView
See Also
Styling content
Adds a border to this view with the specified style and width.
Sets a view’s foreground elements to use a given style.
Sets the primary and secondary levels of the foreground style in the child view.
Sets the primary, secondary, and tertiary levels of the foreground style.
Sets the specified style to render backgrounds within the view.
var backgroundStyle: AnyShapeStyle?
An optional style that overrides the default system background style when set.
protocol ShapeStyle
A color or pattern to use when rendering a shape.
struct AnyShapeStyle
A type-erased ShapeStyle value.
struct Gradient
A color gradient represented as an array of color stops, each having a parametric location value.
struct AnyGradient
A color gradient.
struct ShadowStyle
A style to use when rendering shadows.
struct Glass
A structure that defines the configuration of the Liquid Glass material.
Beta
https://developer.apple.com/documentation/swiftui/modifiedcontent
- SwiftUI
- ModifiedContent
Structure
ModifiedContent
A value with a modifier applied to it.
@frozen
Topics
Creating a modified content view
init(content: Content, modifier: Modifier)
A structure that defines the content and modifier needed to produce a new view or view modifier.
var content: Content
The content that the modifier transforms into a new view or new view modifier.
var modifier: Modifier
The view modifier.
Instance Methods
func accessibility(activationPoint:)
Specifies the point where activations occur in the view.
Deprecated
Adds the given traits to the view.
Specifies whether to hide this view from system accessibility features.
Communicates to the user what happens after performing the view’s action.
Uses the specified string to identify the view.
Sets alternate input labels with which users identify a view.
Adds a label to the view that describes its contents.
Removes the given traits from this view.
Sets a selection identifier for this view’s accessibility element.
Sets the sort priority order for this view’s accessibility element, relative to other elements at the same level.
Adds a textual description of the value that the view contains.
Adds an accessibility action to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action.
Adds an accessibility action representing actionKind to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action. When the action is performed, the intent will be invoked.
func accessibilityAction(named:_:)
func accessibilityAction(named:intent:)
Adds an accessibility action labeled name to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action. When the action is performed, the intent will be invoked.
func accessibilityActivationPoint(_:)
The activation point for an element is the location assistive technologies use to initiate gestures.
func accessibilityActivationPoint(_:isEnabled:)
Adds an accessibility adjustable action to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action.
func accessibilityCustomContent(_:_:importance:)
Add additional accessibility information to the view.
Explicitly set whether this accessibility element is a direct touch area. Direct touch areas passthrough touch events to the app rather than being handled through an assistive technology, such as VoiceOver. The modifier accepts an optional AccessibilityDirectTouchOptions option set to customize the functionality of the direct touch area.
func accessibilityDragPoint(_:description:)
The point an assistive technology should use to begin a drag interaction.
func accessibilityDragPoint(_:description:isEnabled:)
func accessibilityDropPoint(_:description:)
The point an assistive technology should use to end a drag interaction.
func accessibilityDropPoint(_:description:isEnabled:)
Set the level of this heading.
func accessibilityHint(_:)
func accessibilityHint(_:isEnabled:)
Uses the string you specify to identify the view.
func accessibilityInputLabels(_:)
func accessibilityInputLabels(_:isEnabled:)
func accessibilityLabel(_:)
func accessibilityLabel(_:isEnabled:)
Explicitly set whether this Accessibility element responds to user interaction and would thus be interacted with by technologies such as Switch Control, Voice Control or Full Keyboard Access.
Adds an accessibility scroll action to the view. Actions allow assistive technologies, such as the VoiceOver, to interact with the view by invoking the action.
func accessibilityScrollStatus(_:isEnabled:)
Changes the announcement provided by accessibility technologies when a user scrolls a scroll view within this view.
Beta
Sets an accessibility text content type.
func accessibilityValue(_:)
func accessibilityValue(_:isEnabled:)
Adds an accessibility zoom action to the view. Actions allow assistive technologies, such as VoiceOver, to interact with the view by invoking the action.
Relationships
Conforms To
-
AnimatableConforms whenContentconforms toAnimatableandModifierconforms toAnimatable. -
Chart3DContent -
Copyable -
CustomHoverEffectConforms whenContentconforms toCustomHoverEffectandModifierconforms toCustomHoverEffect. -
DynamicMapContent -
DynamicTableRowContentConforms whenContentconforms toDynamicTableRowContentandModifierconforms to_TableRowContentModifier. -
DynamicViewContentConforms whenContentconforms toDynamicViewContentandModifierconforms toViewModifier. -
Equatable -
HoverEffectContentConforms whenContentconforms toHoverEffectContentandModifierconforms toHoverEffectContent. -
MapContent -
SceneConforms whenContentconforms toSceneandModifierconforms to_SceneModifier. -
Sendable -
SendableMetatype -
TableRowContentConforms whenContentconforms toTableRowContentandModifierconforms to_TableRowContentModifier. -
ViewConforms whenContentconforms toViewandModifierconforms toViewModifier. -
ViewModifierConforms whenContentconforms toViewModifierandModifierconforms toViewModifier. -
VisualEffectConforms whenContentconforms toVisualEffectandModifierconforms toVisualEffect.
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
https://developer.apple.com/documentation/swiftui/multidatepicker
- SwiftUI
- MultiDatePicker
Structure
MultiDatePicker
A control for picking multiple dates.
Overview
Use a MultiDatePicker when you want to provide a view that allows the user to select multiple dates.
The following example creates a basic MultiDatePicker, which appears as a calendar view representing the selected dates:
var body: some View { MultiDatePicker("Dates Available", selection: $dates) }
You can limit the MultiDatePicker to specific ranges of dates allowing selections only before or after a certain date or between two dates. The following example shows a multi-date picker that only permits selections within the 6th and (excluding) the 16th of December 2021 (in the UTC time zone):
@Environment(.calendar) var calendar @Environment(.timeZone) var timeZone
let start = calendar.date(from: DateComponents( timeZone: timeZone, year: 2022, month: 6, day: 6))! let end = calendar.date(from: DateComponents( timeZone: timeZone, year: 2022, month: 6, day: 16))! return start ..< end }
var body: some View { MultiDatePicker("Dates Available", selection: $dates, in: bounds) }
You can also specify an alternative locale, calendar and time zone through environment values. This can be useful when using a PreviewProvider to see how your multi-date picker behaves in environments that differ from your own.
The following example shows a multi-date picker with a custom locale, calendar and time zone:
struct ContentView_Previews: PreviewProvider { static var previews: some View { MultiDatePicker("Dates Available", selection: .constant([])) .environment(.locale, Locale.init(identifier: "zh")) .environment( .calendar, Calendar.init(identifier: .chinese)) .environment(.timeZone, TimeZone(abbreviation: "HKT")!) } }
Topics
Picking dates
init(_:selection:)
Creates an instance that selects multiple dates with an unbounded range.
init(selection: Binding<Set<DateComponents>>, label: () -> Label)
Picking dates in a range
init(_:selection:in:)
Creates an instance that selects multiple dates on or after some start date.
init(selection:in:label:)
Relationships
Conforms To
View
See Also
Choosing dates
struct DatePicker
A control for selecting an absolute date.
Sets the style for date pickers within this view.
var calendar: Calendar
The current calendar that views should use when handling dates.
var timeZone: TimeZone
The current time zone that views should use when handling dates.
https://developer.apple.com/documentation/swiftui/offsetshape
- SwiftUI
- OffsetShape
Structure
OffsetShape
A shape with a translation offset transform applied to it.
@frozen
Topics
Creating an offset shape
init(shape: Content, offset: CGSize)
Getting the shape’s characteristics
var offset: CGSize
var shape: Content
Supporting types
The data to animate.
Relationships
Conforms To
-
Animatable -
Copyable -
InsettableShapeConforms whenContentconforms toInsettableShape. -
Sendable -
SendableMetatype -
Shape -
View
See Also
Transforming a shape
struct ScaledShape
A shape with a scale transform applied to it.
struct RotatedShape
A shape with a rotation transform applied to it.
struct TransformedShape
A shape with an affine transform applied to it.
https://developer.apple.com/documentation/swiftui/outlinegroup
- SwiftUI
- OutlineGroup
Structure
OutlineGroup
A structure that computes views and disclosure groups on demand from an underlying collection of tree-structured, identified data.
Mentioned in
Displaying data in lists
Overview
Use an outline group when you need a view that can represent a hierarchy of data by using disclosure views. This allows the user to navigate the tree structure by using the disclosure views to expand and collapse branches.
In the following example, a tree structure of FileItem data offers a simplified view of a file system. Passing the root of this tree and the key path of its children allows you to quickly create a visual representation of the file system.
struct FileItem: Hashable, Identifiable, CustomStringConvertible { var id: Self { self } var name: String var children: [FileItem]? = nil var description: String { switch children { case nil: return "📄 (name)" case .some(let children): return children.isEmpty ? "📂 (name)" : "📁 (name)" } } }
let data =
FileItem(name: "users", children:
[FileItem(name: "user1234", children:
[FileItem(name: "Photos", children:
[FileItem(name: "photo001.jpg"),
FileItem(name: "photo002.jpg")]),
FileItem(name: "Movies", children:
[FileItem(name: "movie001.mp4")]),
FileItem(name: "Documents", children: [])
]),
FileItem(name: "newuser", children:
[FileItem(name: "Documents", children: [])
])
])
OutlineGroup(data, children: .children) { item in Text("(item.description)") }
Type parameters
Five generic type constraints define a specific OutlineGroup instance:
-
Data: The type of a collection containing the children of an element in the tree-shaped data. -
ID: The type of the identifier for an element. -
Parent: The type of the visual representation of an element whose children property is non-nil -
Leaf: The type of the visual representation of an element whose children property isnil. -
Subgroup: A type of a view that groups a parent view and a view representing its children, typically with some mechanism for showing and hiding the children
Topics
Creating an outline group
init(_:children:)
Creates an outline group from a collection of root data elements and a key path to element’s children.
init(_:children:content:)
Creates an outline group from a binding to a collection of root data elements and a key path to its children.
init(_:id:children:content:)
Creates an outline group from a binding to a collection of root data elements, the key path to a data element’s identifier, and a key path to its children.
Supporting types
struct OutlineSubgroupChildren
A type-erased view representing the children in an outline subgroup.
Relationships
Conforms To
-
Copyable -
TableRowContentConforms whenDataconforms toRandomAccessCollection,IDisData.Element.ID,Parentconforms toTableRowContent,ParentisLeaf,LeafisSubgroup, andData.ElementisParent.TableRowValue. -
ViewConforms whenDataconforms toRandomAccessCollection,IDconforms toHashable,Parentconforms toView,Leafconforms toView, andSubgroupconforms toView.
See Also
Disclosing information progressively
struct DisclosureGroup
A view that shows or hides another content view, based on the state of a disclosure control.
Sets the style for disclosure groups within this view.
https://developer.apple.com/documentation/swiftui/outlinesubgroupchildren
- SwiftUI
- OutlineSubgroupChildren
Structure
OutlineSubgroupChildren
A type-erased view representing the children in an outline subgroup.
struct OutlineSubgroupChildren
Overview
OutlineGroup uses this type as a generic constraint for the Content of the DisclosureGroup instances it creates.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/pastebutton
https://developer.apple.com/documentation/swiftui/path
- SwiftUI
- Path
Structure
Path
The outline of a 2D shape.
@frozen struct Path
Topics
Creating a path
init()
Creates an empty path.
init(_:)
Creates an empty path, then executes a closure to add its initial elements.
init(ellipseIn: CGRect)
Creates a path as an ellipse within the given rectangle.
init(roundedRect: CGRect, cornerRadius: CGFloat, style: RoundedCornerStyle)
Creates a path containing a rounded rectangle.
init(roundedRect: CGRect, cornerSize: CGSize, style: RoundedCornerStyle)
init(roundedRect: CGRect, cornerRadii: RectangleCornerRadii, style: RoundedCornerStyle)
Creates a path as the given rounded rectangle, which may have uneven corner radii.
Getting the path’s characteristics
var boundingRect: CGRect
A rectangle containing all path segments.
var cgPath: CGPath
An immutable path representing the elements in the path.
Returns true if the path contains a specified point.
var currentPoint: CGPoint?
Returns the last point in the path, or nil if the path contains no points.
var description: String
A description of the path that may be used to recreate the path via init?(_:).
var isEmpty: Bool
A Boolean value indicating whether the path contains zero elements.
Drawing a path
func move(to: CGPoint)
Begins a new subpath at the specified point.
func addArc(center: CGPoint, radius: CGFloat, startAngle: Angle, endAngle: Angle, clockwise: Bool, transform: CGAffineTransform)
Adds an arc of a circle to the path, specified with a radius and angles.
func addArc(tangent1End: CGPoint, tangent2End: CGPoint, radius: CGFloat, transform: CGAffineTransform)
Adds an arc of a circle to the path, specified with a radius and two tangent lines.
func addCurve(to: CGPoint, control1: CGPoint, control2: CGPoint)
Adds a cubic Bézier curve to the path, with the specified end point and control points.
func addEllipse(in: CGRect, transform: CGAffineTransform)
Adds an ellipse that fits inside the specified rectangle to the path.
func addLine(to: CGPoint)
Appends a straight line segment from the current point to the specified point.
Adds a sequence of connected straight-line segments to the path.
func addPath(Path, transform: CGAffineTransform)
Appends another path value to this path.
func addQuadCurve(to: CGPoint, control: CGPoint)
Adds a quadratic Bézier curve to the path, with the specified end point and control point.
func addRect(CGRect, transform: CGAffineTransform)
Adds a rectangular subpath to the path.
func addRects([CGRect], transform: CGAffineTransform)
Adds a set of rectangular subpaths to the path.
func addRelativeArc(center: CGPoint, radius: CGFloat, startAngle: Angle, delta: Angle, transform: CGAffineTransform)
Adds an arc of a circle to the path, specified with a radius and a difference in angle.
func addRoundedRect(in: CGRect, cornerSize: CGSize, style: RoundedCornerStyle, transform: CGAffineTransform)
Adds a rounded rectangle to the path.
func closeSubpath()
Closes and completes the current subpath.
Transforming the path
Returns a path constructed by applying the transform to all points of the path.
Returns a path constructed by translating all its points.
Returns a partial copy of the path.
Performing operations on the path
Returns a new path with filled regions common to both paths.
Returns a new path with a line from this path that overlaps the filled regions of the given path.
Returns a new path with a line from this path that does not overlap the filled region of the given path.
Returns a new weakly-simple copy of this path.
Returns a new path with filled regions from this path that are not in the given path.
Returns a new path with filled regions either from this path or the given path, but not in both.
Returns a new path with filled regions in either this path or the given path.
Operating over path elements
Calls body with each element in the path.
enum Element
An element of a path.
Applying a style
Returns a stroked copy of the path using style to define how the stroked outline is created.
Instance Methods
func addRoundedRect(in: CGRect, cornerRadii: RectangleCornerRadii, style: RoundedCornerStyle, transform: CGAffineTransform)
Adds a rounded rectangle with uneven corners to the path.
Relationships
Conforms To
AnimatableCopyableCustomStringConvertibleEquatableLosslessStringConvertibleSendableSendableMetatypeShapeView
https://developer.apple.com/documentation/swiftui/phaseanimator
https://developer.apple.com/documentation/swiftui/picker
- SwiftUI
- Picker
Structure
Picker
A control for selecting from a set of mutually exclusive values.
Mentioned in
Picking container views for your content
Performing a search operation
Scoping a search operation
Populating SwiftUI menus with adaptive controls
Overview
You create a picker by providing a selection binding, a label, and the content for the picker to display. Set the selection parameter to a bound property that provides the value to display as the current selection. Set the label to a view that visually describes the purpose of selecting content in the picker, and then provide the content for the picker to display.
For example, consider an enumeration of ice cream flavors and a State variable to hold the selected flavor:
enum Flavor: String, CaseIterable, Identifiable { case chocolate, vanilla, strawberry var id: Self { self } }
@State private var selectedFlavor: Flavor = .chocolate
You can create a picker to select among the values by providing a label, a binding to the current selection, and a collection of views for the picker’s content. Append a tag to each of these content views using the View/tag(_:) view modifier so that the type of each selection matches the type of the bound state variable:
List { Picker("Flavor", selection: $selectedFlavor) { Text("Chocolate").tag(Flavor.chocolate) Text("Vanilla").tag(Flavor.vanilla) Text("Strawberry").tag(Flavor.strawberry) } }
If you provide a string label for the picker, as the example above does, the picker uses it to initialize a Text view as a label. Alternatively, you can use the init(selection:content:label:) initializer to compose the label from other views. The exact appearance of the picker depends on the context. If you use a picker in a List in iOS, it appears in a row with the label and selected value, and a chevron to indicate that you can tap the row to select a new value:
For cases where adding a subtitle to the label is desired, use a view builder that creates multiple Text views where the first text represents the title and the second text represents the subtitle:
List { Picker(selection: $selectedFlavor) { Text("Chocolate").tag(Flavor.chocolate) Text("Vanilla").tag(Flavor.vanilla) Text("Strawberry").tag(Flavor.strawberry) } label: { Text("Flavor") Text("Choose your favorite flavor") } }
Iterating over a picker’s options
To provide selection values for the Picker without explicitly listing each option, you can create the picker with a ForEach:
Picker("Flavor", selection: $selectedFlavor) { ForEach(Flavor.allCases) { flavor in Text(flavor.rawValue.capitalized) } }
ForEach automatically assigns a tag to the selection views using each option’s id. This is possible because Flavor conforms to the Identifiable protocol.
The example above relies on the fact that Flavor defines the type of its id parameter to exactly match the selection type. If that’s not the case, you need to override the tag. For example, consider a Topping type and a suggested topping for each flavor:
enum Topping: String, CaseIterable, Identifiable { case nuts, cookies, blueberries var id: Self { self } }
extension Flavor { var suggestedTopping: Topping { switch self { case .chocolate: return .nuts case .vanilla: return .cookies case .strawberry: return .blueberries } } }
@State private var suggestedTopping: Topping = .nuts
The following example shows a picker that’s bound to a Topping type, while the options are all Flavor instances. Each option uses the tag modifier to associate the suggested topping with the flavor it displays:
List { Picker("Flavor", selection: $suggestedTopping) { ForEach(Flavor.allCases) { flavor in Text(flavor.rawValue.capitalized) .tag(flavor.suggestedTopping) } } HStack { Text("Suggested Topping") Spacer() Text(suggestedTopping.rawValue.capitalized) .foregroundStyle(.secondary) } }
When the user selects chocolate, the picker sets suggestedTopping to the value in the associated tag:
Another example of when the views in a picker’s ForEach need an explicit tag modifier is when you select over the cases of an enumeration that conforms to the Identifiable protocol by using anything besides Self as the id parameter type. For example, a string enumeration might use the case’s rawValue string as the id. That identifier type doesn’t match the selection type, which is the type of the enumeration itself.
Styling pickers
You can customize the appearance and interaction of pickers using styles that conform to the PickerStyle protocol, like segmented or menu. To set a specific style for all picker instances within a view, use the pickerStyle(_:) modifier. The following example applies the segmented style to two pickers that independently select a flavor and a topping:
VStack { Picker("Flavor", selection: $selectedFlavor) { ForEach(Flavor.allCases) { flavor in Text(flavor.rawValue.capitalized) } } Picker("Topping", selection: $selectedTopping) { ForEach(Topping.allCases) { topping in Text(topping.rawValue.capitalized) } } } .pickerStyle(.segmented)
Topics
Creating a picker
init(_:selection:content:)
Creates a picker that generates its label from a localized string key.
Creates a picker that displays a custom label.
Creating a picker for a collection
init(_:sources:selection:content:)
Creates a picker bound to a collection of bindings that generates its label from a string.
init<C>(sources: C, selection: KeyPath<C.Element, Binding<SelectionValue>>, content: () -> Content, label: () -> Label)
Creating a picker with an image label
init(_:image:selection:content:)
Creates a picker that generates its label from a localized string key and image resource
init(_:image:sources:selection:content:)
Creates a picker bound to a collection of bindings that generates its label from a string and image resource.
init(_:systemImage:selection:content:)
Creates a picker that generates its label from a localized string key and system image.
init(_:systemImage:sources:selection:content:)
Deprecated initializers
Deprecated
Initializers
init(_:image:selection:content:currentValueLabel:)
Creates a picker that accepts a custom current value label and generates its label from a localized string key and image resource
init(_:image:sources:selection:content:currentValueLabel:)
Creates a picker bound to a collection of bindings that accepts a custom current value label and generates its label from a string and image resource.
init(_:selection:content:currentValueLabel:)
Creates a picker that generates its label from a localized string key and accepts a custom current value label.
init(_:sources:selection:content:currentValueLabel:)
Creates a picker bound to a collection of bindings that generates its label from a string and accepts a custom current value label.
init(_:systemImage:selection:content:currentValueLabel:)
Creates a picker that accepts a custom current value label and generates its label from a localized string key and system image.
init(_:systemImage:sources:selection:content:currentValueLabel:)
Creates a picker bound to a collection of bindings that accepts a custom current value label and generates its label from a string.
Creates a picker that displays a custom label and a custom value label where applicable.
init<C>(sources: C, selection: KeyPath<C.Element, Binding<SelectionValue>>, content: () -> Content, label: () -> Label, currentValueLabel: () -> some View)
Creates a picker that displays a custom label and current value label where applicable.
Relationships
Conforms To
View
See Also
Choosing from a set of options
Sets the style for pickers within this view.
Sets the style for radio group style pickers within this view to be horizontally positioned with the radio buttons inside the layout.
Sets the default wheel-style picker item height.
var defaultWheelPickerItemHeight: CGFloat
The default height of an item in a wheel-style picker, such as a date picker.
Specifies the selection effect to apply to a palette item.
struct PaletteSelectionEffect
The selection effect to apply to a palette item.
https://developer.apple.com/documentation/swiftui/placeholdercontentview
https://developer.apple.com/documentation/swiftui/presentedwindowcontent
- SwiftUI
- PresentedWindowContent
Structure
PresentedWindowContent
A view that represents the content of a presented window.
Overview
You don’t create this type directly. WindowGroup creates values for you.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/previewmodifiercontent
- SwiftUI
- PreviewModifierContent
Structure
PreviewModifierContent
The type-erased content of a preview.
struct PreviewModifierContent
Relationships
Conforms To
View
See Also
Defining a preview
macro Previewable()
Tag allowing a dynamic property to appear inline in a preview.
protocol PreviewProvider
A type that produces view previews in Xcode.
enum PreviewPlatform
Platforms that can run the preview.
Sets a user visible name to show in the canvas for a preview.
protocol PreviewModifier
A type that defines an environment in which previews can appear.
https://developer.apple.com/documentation/swiftui/primitivebuttonstyleconfiguration/label-swift.struct
- SwiftUI
- PrimitiveButtonStyleConfiguration
- PrimitiveButtonStyleConfiguration.Label
Structure
PrimitiveButtonStyleConfiguration.Label
A type-erased label of a button.
@MainActor @preconcurrency struct Label
Relationships
Conforms To
View
See Also
Configuring a button’s label
let label: PrimitiveButtonStyleConfiguration.Label
A view that describes the effect of calling the button’s action.
https://developer.apple.com/documentation/swiftui/progressview
- SwiftUI
- ProgressView
Structure
ProgressView
A view that shows the progress toward completion of a task.
Mentioned in
Declaring a custom view
Overview
Use a progress view to show that a task is incomplete but advancing toward completion. A progress view can show both determinate (percentage complete) and indeterminate (progressing or not) types of progress.
Create a determinate progress view by initializing a ProgressView with a binding to a numeric value that indicates the progress, and a total value that represents completion of the task. By default, the progress is 0.0 and the total is 1.0.
The example below uses the state property progress to show progress in a determinate ProgressView. The progress view uses its default total of 1.0, and because progress starts with an initial value of 0.5, the progress view begins half-complete. A “More” button below the progress view allows people to increment the progress in increments of five percent:
struct LinearProgressDemoView: View { @State private var progress = 0.5
var body: some View { VStack { ProgressView(value: progress) Button("More") { progress += 0.05 } } } }
To create an indeterminate progress view, use an initializer that doesn’t take a progress value:
var body: some View { ProgressView() }
You can also create a progress view that covers a closed range of Date values. As long as the current date is within the range, the progress view automatically updates, filling or depleting the progress view as it nears the end of the range. The following example shows a five-minute timer whose start time is that of the progress view’s initialization:
struct DateRelativeProgressDemoView: View { let workoutDateRange = Date()...Date().addingTimeInterval(5*60)
var body: some View { ProgressView(timerInterval: workoutDateRange) { Text("Workout") } } }
Styling progress views
You can customize the appearance and interaction of progress views by creating styles that conform to the ProgressViewStyle protocol. To set a specific style for all progress view instances within a view, use the progressViewStyle(_:) modifier. In the following example, a custom style adds a rounded pink border to all progress views within the enclosing VStack:
struct BorderedProgressViews: View { var body: some View { VStack { ProgressView(value: 0.25) { Text("25% progress") } ProgressView(value: 0.75) { Text("75% progress") } } .progressViewStyle(PinkBorderedProgressViewStyle()) } }
struct PinkBorderedProgressViewStyle: ProgressViewStyle {
ProgressView(configuration) .padding(4) .border(.pink, width: 3) .cornerRadius(4) } }
SwiftUI provides two built-in progress view styles, linear and circular, as well as an automatic style that defaults to the most appropriate style in the current context. The following example shows a circular progress view that starts at 60 percent completed.
struct CircularProgressDemoView: View { @State private var progress = 0.6
var body: some View { VStack { ProgressView(value: progress) .progressViewStyle(.circular) } } }
On platforms other than macOS, the circular style may appear as an indeterminate indicator instead.
Topics
Creating an indeterminate progress view
init()
Creates a progress view for showing indeterminate progress, without a label.
Creates a progress view for showing indeterminate progress that displays a custom label.
init(LocalizedStringKey)
Creates a progress view for showing indeterminate progress that generates its label from a localized string.
Creates a progress view for showing indeterminate progress that generates its label from a string.
Creating a determinate progress view
init(Progress)
Creates a progress view for visualizing the given progress instance.
Creates a progress view for showing determinate progress.
init(_:value:total:)
Creates a progress view for showing determinate progress that generates its label from a string.
Creates a progress view for showing determinate progress, with a custom label.
Create a progress view spanning a date range
Creates a progress view for showing continuous progress as time passes.
Creates a progress view for showing continuous progress as time passes, with a descriptive label.
Creates a progress view for showing continuous progress as time passes, with descriptive and current progress labels.
Initializers
init(_:)
Creates a progress view based on a style configuration.
Relationships
Conforms To
View
See Also
Indicating a value
struct Gauge
A view that shows a value within a range.
Sets the style for gauges within this view.
Sets the style for progress views in this view.
struct DefaultDateProgressLabel
The default type of the current value label when used by a date-relative progress view.
struct DefaultButtonLabel
The default label to use for a button.
Beta
https://developer.apple.com/documentation/swiftui/progressviewstyleconfiguration/currentvaluelabel-swift.struct
- SwiftUI
- ProgressViewStyleConfiguration
- ProgressViewStyleConfiguration.CurrentValueLabel
Structure
ProgressViewStyleConfiguration.CurrentValueLabel
A type-erased label that describes the current value of a progress view.
@MainActor @preconcurrency struct CurrentValueLabel
Relationships
Conforms To
View
See Also
Configuring the current value label
var currentValueLabel: ProgressViewStyleConfiguration.CurrentValueLabel?
A view that describes the current value of a progress view.
https://developer.apple.com/documentation/swiftui/progressviewstyleconfiguration/label-swift.struct
- SwiftUI
- ProgressViewStyleConfiguration
- ProgressViewStyleConfiguration.Label
Structure
ProgressViewStyleConfiguration.Label
A type-erased label describing the task represented by the progress view.
@MainActor @preconcurrency struct Label
Relationships
Conforms To
View
See Also
Configuring the label
var label: ProgressViewStyleConfiguration.Label?
A view that describes the task represented by the progress view.
https://developer.apple.com/documentation/swiftui/radialgradient
- SwiftUI
- RadialGradient
Structure
RadialGradient
A radial gradient.
@frozen struct RadialGradient
Overview
The gradient applies the color function as the distance from a center point, scaled to fit within the defined start and end radii. The gradient maps the unit space center point into the bounding rectangle of each shape filled with the gradient.
When using a radial gradient as a shape style, you can also use radialGradient(_:center:startRadius:endRadius:).
Topics
Creating a radial gradient
init(gradient: Gradient, center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat)
Creates a radial gradient from a base gradient.
init(colors: [Color], center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat)
Creates a radial gradient from a collection of colors.
init(stops: [Gradient.Stop], center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat)
Creates a radial gradient from a collection of color stops.
Relationships
Conforms To
SendableSendableMetatypeShapeStyleView
See Also
Supporting types
struct AngularGradient
An angular gradient.
struct EllipticalGradient
A radial gradient that draws an ellipse.
struct LinearGradient
A linear gradient.
struct Material
A background material type.
struct ImagePaint
A shape style that fills a shape by repeating a region of an image.
struct HierarchicalShapeStyle
A shape style that maps to one of the numbered content styles.
struct HierarchicalShapeStyleModifier
Styles that you can apply to hierarchical shapes.
struct ForegroundStyle
The foreground style in the current context.
struct BackgroundStyle
The background style in the current context.
struct SelectionShapeStyle
A style used to visually indicate selection following platform conventional colors and behaviors.
struct SeparatorShapeStyle
A style appropriate for foreground separator or border lines.
struct TintShapeStyle
A style that reflects the current tint color.
struct FillShapeStyle
A shape style that displays one of the overlay fills.
struct LinkShapeStyle
A style appropriate for links.
struct PlaceholderTextShapeStyle
A style appropriate for placeholder text.
https://developer.apple.com/documentation/swiftui/rectangle
- SwiftUI
- Rectangle
Structure
Rectangle
A rectangular shape aligned inside the frame of the view containing it.
@frozen struct Rectangle
Topics
Creating a rectangle
init()
Creates a new rectangle shape.
Relationships
Conforms To
AnimatableBitwiseCopyableCopyableInsettableShapeSendableSendableMetatypeShapeView
See Also
Creating rectangular shapes
struct RoundedRectangle
A rectangular shape with rounded corners, aligned inside the frame of the view containing it.
enum RoundedCornerStyle
Defines the shape of a rounded rectangle’s corners.
struct UnevenRoundedRectangle
A rectangular shape with rounded corners with different values, aligned inside the frame of the view containing it.
struct RectangleCornerRadii
Describes the corner radius values of a rounded rectangle with uneven corners.
https://developer.apple.com/documentation/swiftui/rotatedshape
- SwiftUI
- RotatedShape
Structure
RotatedShape
A shape with a rotation transform applied to it.
@frozen
Topics
Creating a rotated shape
init(shape: Content, angle: Angle, anchor: UnitPoint)
Getting the shape’s characteristics
var anchor: UnitPoint
var angle: Angle
var shape: Content
Supporting types
The data to animate.
Relationships
Conforms To
-
Animatable -
Copyable -
InsettableShapeConforms whenContentconforms toInsettableShape. -
Sendable -
SendableMetatype -
Shape -
View
See Also
Transforming a shape
struct ScaledShape
A shape with a scale transform applied to it.
struct OffsetShape
A shape with a translation offset transform applied to it.
struct TransformedShape
A shape with an affine transform applied to it.
https://developer.apple.com/documentation/swiftui/roundedrectangle
- SwiftUI
- RoundedRectangle
Structure
RoundedRectangle
A rectangular shape with rounded corners, aligned inside the frame of the view containing it.
@frozen struct RoundedRectangle
Topics
Creating a rounded rectangle
init(cornerRadius: CGFloat, style: RoundedCornerStyle)
Creates a new rounded rectangle shape.
init(cornerSize: CGSize, style: RoundedCornerStyle)
Getting the shape’s characteristics
var cornerSize: CGSize
The width and height of the rounded rectangle’s corners.
var style: RoundedCornerStyle
The style of corners drawn by the rounded rectangle.
Supporting types
var animatableData: CGSize.AnimatableData
The data to animate.
Relationships
Conforms To
AnimatableCopyableInsettableShapeSendableSendableMetatypeShapeView
See Also
Creating rectangular shapes
struct Rectangle
A rectangular shape aligned inside the frame of the view containing it.
enum RoundedCornerStyle
Defines the shape of a rounded rectangle’s corners.
struct UnevenRoundedRectangle
A rectangular shape with rounded corners with different values, aligned inside the frame of the view containing it.
struct RectangleCornerRadii
Describes the corner radius values of a rounded rectangle with uneven corners.
https://developer.apple.com/documentation/swiftui/scaledshape
- SwiftUI
- ScaledShape
Structure
ScaledShape
A shape with a scale transform applied to it.
@frozen
Topics
Creating a scaled shape
init(shape: Content, scale: CGSize, anchor: UnitPoint)
Getting the shape’s characteristics
var anchor: UnitPoint
var scale: CGSize
var shape: Content
Supporting types
The data to animate.
Relationships
Conforms To
AnimatableSendableSendableMetatypeShapeView
See Also
Transforming a shape
struct RotatedShape
A shape with a rotation transform applied to it.
struct OffsetShape
A shape with a translation offset transform applied to it.
struct TransformedShape
A shape with an affine transform applied to it.
https://developer.apple.com/documentation/swiftui/scrollview
- SwiftUI
- ScrollView
Structure
ScrollView
A scrollable view.
Mentioned in
Picking container views for your content
Creating performant scrollable stacks
Grouping data with lazy stack views
Overview
The scroll view displays its content within the scrollable content region. As the user performs platform-appropriate scroll gestures, the scroll view adjusts what portion of the underlying content is visible. ScrollView can scroll horizontally, vertically, or both, but does not provide zooming functionality.
In the following example, a ScrollView allows the user to scroll through a VStack containing 100 Text views. The image after the listing shows the scroll view’s temporarily visible scrollbar at the right; you can disable it with the showsIndicators parameter of the ScrollView initializer.
var body: some View { ScrollView { VStack(alignment: .leading) { ForEach(0..<100) { Text("Row ($0)") } } } }
Controlling Scroll Position
You can influence where a scroll view is initially scrolled by using the defaultScrollAnchor(_:) view modifier.
Provide a value of `UnitPoint/center`` to have the scroll view start in the center of its content when a scroll view is scrollable in both axes.
ScrollView([.horizontal, .vertical]) { // initially centered content } .defaultScrollAnchor(.center)
Or provide an alignment of `UnitPoint/bottom`` to have the scroll view start at the bottom of its content when a scroll view is scrollable in its vertical axes.
ScrollView { // initially bottom aligned content } .defaultScrollAnchor(.bottom)
After the scroll view initially renders, the user may scroll the content of the scroll view.
To perform programmatic scrolling, wrap one or more scroll views with a ScrollViewReader.
Topics
Creating a scroll view
Creates a new instance that’s scrollable in the direction of the given axis and can show indicators while scrolling.
Deprecated
Configuring a scroll view
var content: Content
The scroll view’s content.
var axes: Axis.Set
The scrollable axes of the scroll view.
var showsIndicators: Bool
A value that indicates whether the scroll view displays the scrollable component of the content offset, in a way that’s suitable for the platform.
Supporting types
var body: some View
The content and behavior of the scroll view.
Relationships
Conforms To
View
See Also
Creating a scroll view
struct ScrollViewReader
A view that provides programmatic scrolling, by working with a proxy to scroll to known child views.
struct ScrollViewProxy
A proxy value that supports programmatic scrolling of the scrollable views within a view hierarchy.
https://developer.apple.com/documentation/swiftui/scrollviewreader
- SwiftUI
- ScrollViewReader
Structure
ScrollViewReader
A view that provides programmatic scrolling, by working with a proxy to scroll to known child views.
@frozen
Overview
The scroll view reader’s content view builder receives a ScrollViewProxy instance; you use the proxy’s scrollTo(_:anchor:) to perform scrolling.
The following example creates a ScrollView containing 100 views that together display a color gradient. It also contains two buttons, one each at the top and bottom. The top button tells the ScrollViewProxy to scroll to the bottom button, and vice versa.
@Namespace var topID @Namespace var bottomID
var body: some View { ScrollViewReader { proxy in ScrollView { Button("Scroll to Bottom") { withAnimation { proxy.scrollTo(bottomID) } } .id(topID)
VStack(spacing: 0) { ForEach(0..<100) { i in color(fraction: Double(i) / 100) .frame(height: 32) } }
Button("Top") { withAnimation { proxy.scrollTo(topID) } } .id(bottomID) } } }
Color(red: fraction, green: 1 - fraction, blue: 0.5) }
Topics
Creating a scroll view reader
Creates an instance that can perform programmatic scrolling of its child scroll views.
Configuring a scroll view reader
The view builder that creates the reader’s content.
Relationships
Conforms To
View
See Also
Creating a scroll view
struct ScrollView
A scrollable view.
struct ScrollViewProxy
A proxy value that supports programmatic scrolling of the scrollable views within a view hierarchy.
https://developer.apple.com/documentation/swiftui/searchunavailablecontent/actions
- SwiftUI
- SearchUnavailableContent
- SearchUnavailableContent.Actions
Structure
SearchUnavailableContent.Actions
A view that represents the actions of a static ContentUnavailableView.search view.
@MainActor @preconcurrency struct Actions
Overview
You don’t create this type directly. SwiftUI creates it when you build a search ContentUnavailableView.
Relationships
Conforms To
View
See Also
Getting content types
struct Description
A view that represents the description of a static ContentUnavailableView.search view.
struct Label
A view that represents the label of a static placeholder search view.
https://developer.apple.com/documentation/swiftui/searchunavailablecontent/description
- SwiftUI
- SearchUnavailableContent
- SearchUnavailableContent.Description
Structure
SearchUnavailableContent.Description
A view that represents the description of a static ContentUnavailableView.search view.
@MainActor @preconcurrency struct Description
Overview
You don’t create this type directly. SwiftUI creates it when you build a search``ContentUnavailableView`.
Relationships
Conforms To
View
See Also
Getting content types
struct Actions
A view that represents the actions of a static ContentUnavailableView.search view.
struct Label
A view that represents the label of a static placeholder search view.
https://developer.apple.com/documentation/swiftui/searchunavailablecontent/label
- SwiftUI
- SearchUnavailableContent
- SearchUnavailableContent.Label
Structure
SearchUnavailableContent.Label
A view that represents the label of a static placeholder search view.
@MainActor @preconcurrency struct Label
Overview
You don’t create this type directly. SwiftUI creates it when you build a search ContentUnavailableView.
Relationships
Conforms To
View
See Also
Getting content types
struct Actions
A view that represents the actions of a static ContentUnavailableView.search view.
struct Description
A view that represents the description of a static ContentUnavailableView.search view.
https://developer.apple.com/documentation/swiftui/section
- SwiftUI
- Section
Structure
Section
A container view that you can use to add hierarchy within certain views.
Mentioned in
Grouping data with lazy stack views
Populating SwiftUI menus with adaptive controls
Suggesting search terms
Displaying data in lists
Overview
Use Section instances in views like List, Picker, and Form to organize content into separate sections. Each section has custom content that you provide on a per-instance basis. You can also provide headers and footers for each section.
Collapsible sections
Create sections that expand and collapse by using an initializer that accepts an isExpanded binding. A collapsible section in a List that uses the sidebar style shows a disclosure indicator next to the section’s header. Tapping on the disclosure indicator toggles the appearance of the section’s content.
Topics
Creating a section
init(content:)
Creates a section with the provided section content.
init(_:content:)
Adding headers and footers
init(content:header:)
Creates a section with a header and the provided section content.
Creates a section with a footer and the provided section content.
Creates a section with a header, footer, and the provided section content.
Controlling collapsibility
init(_:isExpanded:content:)
init(isExpanded:content:header:)
Creates a section with a header, the provided section content, and a binding representing the section’s expansion state.
Deprecated symbols
Deprecated
Sets whether a section can be collapsed by the user.
Relationships
Conforms To
-
Copyable -
TableRowContentConforms whenParentconforms toTableRowContent,Contentconforms toTableRowContent, andFooterconforms toTableRowContent. -
ViewConforms whenParentconforms toView,Contentconforms toView, andFooterconforms toView.
See Also
Organizing views into sections
struct SectionCollection
An opaque collection representing the sections of view.
struct SectionConfiguration
Specifies the contents of a section.
https://developer.apple.com/documentation/swiftui/sectionconfiguration/actions-swift.struct
- SwiftUI
- SectionConfiguration
- SectionConfiguration.Actions
Structure
SectionConfiguration.Actions
The type-erased actions of a section.
@MainActor @preconcurrency struct Actions
Relationships
Conforms To
SendableSendableMetatypeView
https://developer.apple.com/documentation/swiftui/securefield
- SwiftUI
- SecureField
Structure
SecureField
A control into which people securely enter private text.
Overview
Use a secure field when you want the behavior of a TextField, but you want to hide the field’s text. Typically, you use this for entering passwords and other sensitive information, as the second field in the following screenshot demonstrates:
The field:
-
Displays one dot for each character someone types.
-
Hides the dots when someone takes a screenshot in iOS.
-
Prevents anyone from cutting or copying the field’s contents.
-
Displays an indicator when Caps Lock is enabled.
Bind to a string
A secure field binds to a string value and updates the string on every keystroke or other edit, so you can read its value at any time from elsewhere in your code. The following code shows how to create the above interface, with the secure field bound to a password string:
@State private var username: String = "" @State private var password: String = ""
var body: some View { VStack { TextField("Username", text: $username) .autocorrectionDisabled(true) #if !os(macOS) .textInputAutocapitalization(.never) #endif
SecureField("Password", text: $password) .onSubmit { handleLogin(username: username, password: password) } } .textFieldStyle(.roundedBorder) }
The field in the above example has an onSubmit(of:_:) modifier that sends the username and password strings to a custom handleLogin(username:password:) method if someone presses the Return key while the secure field has focus. You can alternatively provide another mechanism — like a button — to do the same thing.
Guide people with a prompt
In addition to the string or view that you provide as a label, you can also provide a Text view prompt to help guide someone who uses the field, as the following Form does:
Form { TextField(text: $username, prompt: Text("Required")) { Text("Username") } .autocorrectionDisabled(true) #if !os(macOS) #endif
SecureField(text: $password, prompt: Text("Required")) { Text("Password") } }
The system uses the label and prompt in different ways depending on the context. For example, a form in macOS places the label against the leading edge of the field and uses the prompt as placeholder text inside the field. The same form in iOS also uses the prompt as placeholder text, but doesn’t display the label:
If you remove the prompt from the previous example, the field keeps the label on the leading edge and omits the placeholder text in macOS, but displays the label as a placeholder in iOS:
Topics
Creating a secure text field
init(_:text:)
Creates a secure field with a prompt generated from a Text.
init(_:text:prompt:)
Deprecated initializers
init(_:text:onCommit:)
Creates an instance.
Deprecated
Relationships
Conforms To
View
See Also
Getting text input
Building rich SwiftUI text experiences
Build an editor for formatted text using SwiftUI text editor views and attributed strings.
struct TextField
A control that displays an editable text interface.
Sets the style for text fields within this view.
struct TextEditor
A view that can display and edit long-form text.
https://developer.apple.com/documentation/swiftui/sharelink
- SwiftUI
- ShareLink
Structure
ShareLink
A view that controls a sharing presentation.
Overview
People tap or click on a share link to present a share interface. The link typically uses a system-standard appearance; you only need to supply the content to share:
ShareLink(item: URL(string: "https://developer.apple.com/xcode/swiftui/")!)
You can control the appearance of the link by providing view content. For example, you can use a Label to display a link with a custom icon:
ShareLink(item: URL(string: "https://developer.apple.com/xcode/swiftui/")!) { Label("Share", image: "MyCustomShareIcon") }
If you only wish to customize the link’s title, you can use one of the convenience initializers that takes a string and creates a Label for you:
ShareLink("Share URL", item: URL(string: "https://developer.apple.com/xcode/swiftui/")!)
The link can share any content that is Transferable. Many framework types, like URL, already conform to this protocol. You can also make your own types transferable.
For example, you can use ProxyRepresentation to resolve your own type to a framework type:
struct Photo: Transferable { static var transferRepresentation: some TransferRepresentation { ProxyRepresentation(.image) }
public var image: Image public var caption: String }
struct PhotoView: View { let photo: Photo
var body: View { photo.image .toolbar { ShareLink( item: photo, preview: SharePreview( photo.caption, image: photo.image)) } } }
Sometimes the content that your app shares isn’t immediately available. You can use FileRepresentation or DataRepresentation when you need an asynchronous operation, like a network request, to retrieve and prepare the content.
A Transferable type also lets you provide multiple content types for a single shareable item. The share interface shows relevant sharing services based on the types that you provide.
The previous example also shows how you provide a preview of your content to show in the share interface.
A preview isn’t required when sharing URLs or non-attributed strings. When sharing these types of content, the system can automatically determine a preview.
You can provide a preview even when it’s optional. For instance, when sharing URLs, the automatic preview first shows a placeholder link icon alongside the base URL while fetching the link’s metadata over the network. The preview updates once the link’s icon and title become available. If you provide a preview instead, the preview appears immediately without fetching data over the network.
Some share activities support subject and message fields. You can pre-populate these fields with the subject and message parameters:
ShareLink( item: photo, subject: Text("Cool Photo"), message: Text("Check it out!") preview: SharePreview( photo.caption, image: photo.image))
Topics
Sharing an item
init(item:subject:message:)
Creates an instance that presents the share interface.
init(_:item:subject:message:)
Creates an instance, with a custom label, that presents the share interface.
init(item:subject:message:label:)
Sharing an item with a preview
init(_:item:subject:message:preview:)
Sharing items
init(items:subject:message:)
init(_:items:subject:message:)
init(items:subject:message:label:)
Sharing items with a preview
init(_:items:subject:message:preview:)
Supporting types
struct DefaultShareLinkLabel
The default label used for a share link.
Relationships
Conforms To
View
See Also
Linking to other content
struct Link
A control for navigating to a URL.
struct SharePreview
A representation of a type to display in a share preview.
struct TextFieldLink
A control that requests text input from the user when pressed.
struct HelpLink
A button with a standard appearance that opens app-specific help documentation.
https://developer.apple.com/documentation/swiftui/slider
- SwiftUI
- Slider
Structure
Slider
A control for selecting a value from a bounded linear range of values.
Mentioned in
Populating SwiftUI menus with adaptive controls
Overview
A slider consists of a “thumb” image that the user moves between two extremes of a linear “track”. The ends of the track represent the minimum and maximum possible values. As the user moves the thumb, the slider updates its bound value.
The following example shows a slider bound to the value speed. As the slider updates this value, a bound Text view shows the value updating. The onEditingChanged closure passed to the slider receives callbacks when the user drags the slider. The example uses this to change the color of the value text.
@State private var speed = 50.0 @State private var isEditing = false
var body: some View { VStack { Slider( value: $speed, in: 0...100, onEditingChanged: { editing in isEditing = editing } ) Text("(speed)") .foregroundColor(isEditing ? .red : .blue) } }
You can also use a step parameter to provide incremental steps along the path of the slider. For example, if you have a slider with a range of 0 to 100, and you set the step value to 5, the slider’s increments would be 0, 5, 10, and so on. The following example shows this approach, and also adds optional minimum and maximum value labels.
var body: some View { Slider( value: $speed, in: 0...100, step: 5 ) { Text("Speed") } minimumValueLabel: { Text("0") } maximumValueLabel: { Text("100") } onEditingChanged: { editing in isEditing = editing } Text("(speed)") .foregroundColor(isEditing ? .red : .blue) }
The slider also uses the step to increase or decrease the value when a VoiceOver user adjusts the slider with voice commands.
Topics
Creating a slider
Creates a slider to select a value from a given range.
Creates a slider to select a value from a given range, subject to a step increment.
Creating a slider with labels
Creates a slider to select a value from a given range, which displays the provided label.
Creates a slider to select a value from a given range, subject to a step increment, which displays the provided label.
Creates a slider to select a value from a given range, which displays the provided labels.
Creates a slider to select a value from a given range, subject to a step increment, which displays the provided labels.
Deprecated initializers
Deprecated
Relationships
Conforms To
View
See Also
Getting numeric inputs
struct Stepper
A control that performs increment and decrement actions.
struct Toggle
A control that toggles between on and off states.
Sets the style for toggles in a view hierarchy.
https://developer.apple.com/documentation/swiftui/spacer
- SwiftUI
- Spacer
Structure
Spacer
A flexible space that expands along the major axis of its containing stack layout, or on both axes if not contained in a stack.
@frozen struct Spacer
Mentioned in
Building layouts with stack views
Adding a background to your view
Picking container views for your content
Overview
A spacer creates an adaptive view with no content that expands as much as it can. For example, when placed within an HStack, a spacer expands horizontally as much as the stack allows, moving sibling views out of the way, within the limits of the stack’s size. SwiftUI sizes a stack that doesn’t contain a spacer up to the combined ideal widths of the content of the stack’s child views.
The following example provides a simple checklist row to illustrate how you can use a spacer:
struct ChecklistRow: View { let name: String
var body: some View { HStack { Image(systemName: "checkmark") Text(name) } .border(Color.blue) } }
Adding a spacer before the image creates an adaptive view with no content that expands to push the image and text to the right side of the stack. The stack also now expands to take as much space as the parent view allows, shown by the blue border that indicates the boundary of the stack:
var body: some View { HStack { Spacer() Image(systemName: "checkmark") Text(name) } .border(Color.blue) } }
Moving the spacer between the image and the name pushes those elements to the left and right sides of the HStack, respectively. Because the stack contains the spacer, it expands to take as much horizontal space as the parent view allows; the blue border indicates its size:
var body: some View { HStack { Image(systemName: "checkmark") Spacer() Text(name) } .border(Color.blue) } }
Adding two spacer views on the outside of the stack leaves the image and text together, while the stack expands to take as much horizontal space as the parent view allows:
var body: some View { HStack { Spacer() Image(systemName: "checkmark") Text(name) Spacer() } .border(Color.blue) } }
Topics
Creating a spacer
init(minLength: CGFloat?)
var minLength: CGFloat?
The minimum length this spacer can be shrunk to, along the axis or axes of expansion.
Relationships
Conforms To
BitwiseCopyableCopyableSendableSendableMetatypeView
See Also
Separators
struct Divider
A visual element that can be used to separate other content.
https://developer.apple.com/documentation/swiftui/stepper
- SwiftUI
- Stepper
Structure
Stepper
A control that performs increment and decrement actions.
Overview
Use a stepper control when you want the user to have granular control while incrementing or decrementing a value. For example, you can use a stepper to:
-
Change a value up or down by
1. -
Operate strictly over a prescribed range.
-
Step by specific amounts over a stepper’s range of possible values.
The example below uses an array that holds a number of Color values, a local state variable, value, to set the control’s background color, and title label. When the user clicks or taps the stepper’s increment or decrement buttons, SwiftUI executes the relevant closure that updates value, wrapping the value to prevent overflow. SwiftUI then re-renders the view, updating the text and background color to match the current index:
struct StepperView: View {
@State private var value = 0
let colors: [Color] = [.orange, .red, .gray, .blue,
.green, .purple, .pink]
func incrementStep() { value += 1
}
func decrementStep() { value -= 1 if value < 0 { value = colors.count - 1 } }
var body: some View { Stepper { Text("Value: (value) Color: (colors[value].description)") } onIncrement: { incrementStep() } onDecrement: { decrementStep() } .padding(5) .background(colors[value]) } }
The following example shows a stepper that displays the effect of incrementing or decrementing a value with the step size of step with the bounds defined by range:
struct StepperView: View { @State private var value = 0 let step = 5 let range = 1...50
var body: some View { Stepper( value: $value, in: range, step: step ) { Text("Current: (value) in (range.description) " + "stepping by (step)") } .padding(10) } }
Topics
Creating a stepper
Creates a stepper configured to increment or decrement a binding to a value using a step value you provide.
Creates a stepper configured to increment or decrement a binding to a value using a step value you provide, displaying its value with an applied format style.
init(_:value:step:onEditingChanged:)
Creates a stepper with a title and configured to increment and decrement a binding to a value and step amount you provide.
init(_:value:step:format:onEditingChanged:)
Creates a stepper with a title key and configured to increment and decrement a binding to a value and step amount you provide, displaying its value with an applied format style.
Creating a stepper over a range
Creates a stepper configured to increment or decrement a binding to a value using a step value and within a range of values you provide.
Creates a stepper configured to increment or decrement a binding to a value using a step value and within a range of values you provide, displaying its value with an applied format style.
init(_:value:in:step:onEditingChanged:)
Creates a stepper instance that increments and decrements a binding to a value, by a step size and within a closed range that you provide.
init(_:value:in:step:format:onEditingChanged:)
Creates a stepper instance that increments and decrements a binding to a value, by a step size and within a closed range that you provide, displaying its value with an applied format style.
Creating a stepper with change behavior
Creates a stepper instance that performs the closures you provide when the user increments or decrements the stepper.
init(_:onIncrement:onDecrement:onEditingChanged:)
Creates a stepper that uses a title key and executes the closures you provide when the user clicks or taps the stepper’s increment and decrement buttons.
Deprecated initializers
Deprecated
Relationships
Conforms To
View
See Also
Getting numeric inputs
struct Slider
A control for selecting a value from a bounded linear range of values.
struct Toggle
A control that toggles between on and off states.
Sets the style for toggles in a view hierarchy.
https://developer.apple.com/documentation/swiftui/strokebordershapeview
- SwiftUI
- StrokeBorderShapeView
Structure
StrokeBorderShapeView
A shape provider that strokes the border of its shape.
@frozen
Overview
You don’t create this type directly; it’s the return type of Shape.strokeBorder.
Topics
Creating a stroke border shape view
init(shape: Content, style: Style, strokeStyle: StrokeStyle, isAntialiased: Bool, background: Background)
Create a stroke border shape.
Getting shape view properties
var background: Background
The background shown beneath this view.
var isAntialiased: Bool
Whether this shape should be drawn antialiased.
var shape: Content
The shape that this type draws and provides for other drawing operations.
var strokeStyle: StrokeStyle
The stroke style used when stroking this view’s shape.
var style: Style
The style that strokes the border of this view’s shape.
Relationships
Conforms To
ShapeViewView
See Also
Defining shape behavior
protocol ShapeView
A view that provides a shape that you can use for drawing operations.
protocol Shape
A 2D shape that you can use when drawing a view.
struct AnyShape
A type-erased shape value.
enum ShapeRole
Ways of styling a shape.
struct StrokeStyle
The characteristics of a stroke that traces a path.
struct StrokeShapeView
A shape provider that strokes its shape.
struct FillStyle
A style for rasterizing vector shapes.
struct FillShapeView
A shape provider that fills its shape.
https://developer.apple.com/documentation/swiftui/strokeshapeview
- SwiftUI
- StrokeShapeView
Structure
StrokeShapeView
A shape provider that strokes its shape.
@frozen
Overview
You don’t create this type directly; it’s the return type of Shape.stroke.
Topics
Creating a stroke shape view
init(shape: Content, style: Style, strokeStyle: StrokeStyle, isAntialiased: Bool, background: Background)
Create a StrokeShapeView.
Getting shape view properties
var background: Background
The background shown beneath this view.
var isAntialiased: Bool
Whether this shape should be drawn antialiased.
var shape: Content
The shape that this type draws and provides for other drawing operations.
var strokeStyle: StrokeStyle
The stroke style used when stroking this view’s shape.
var style: Style
The style that strokes this view’s shape.
Relationships
Conforms To
ShapeViewView
See Also
Defining shape behavior
protocol ShapeView
A view that provides a shape that you can use for drawing operations.
protocol Shape
A 2D shape that you can use when drawing a view.
struct AnyShape
A type-erased shape value.
enum ShapeRole
Ways of styling a shape.
struct StrokeStyle
The characteristics of a stroke that traces a path.
struct StrokeBorderShapeView
A shape provider that strokes the border of its shape.
struct FillStyle
A style for rasterizing vector shapes.
struct FillShapeView
A shape provider that fills its shape.
https://developer.apple.com/documentation/swiftui/subscriptionview
- SwiftUI
- SubscriptionView
Structure
SubscriptionView
A view that subscribes to a publisher with an action.
@frozen
Topics
Managing the subscription
var publisher: PublisherType
The Publisher that is being subscribed.
The Action executed when publisher emits an event.
var content: Content
The content view.
Relationships
Conforms To
View
See Also
Supporting view types
struct AnyView
A type-erased view.
struct EmptyView
A view that doesn’t contain any content.
struct EquatableView
A view type that compares itself against its previous value and prevents its child updating if its new value is the same as its old value.
struct TupleView
A View created from a swift tuple of View values.
https://developer.apple.com/documentation/swiftui/subview
- SwiftUI
- Subview
Structure
Subview
An opaque value representing a subview of another view.
struct Subview
Overview
Access to a Subview can be obtained by using ForEach(subviews:) or Group(subviews:).
Subviews are proxies to the resolved view they represent, meaning that modifiers applied to the original view will be applied before modifiers applied to the subview, and the view is resolved using the environment of its container, not the environment of the its subview proxy. Additionally, because subviews must represent a single leaf view, or container, a subview may represent a view after the application of styles. As such, attempting to apply a style to it may have no affect.
Topics
Structures
struct ID
A unique identifier for a subview.
Instance Properties
var containerValues: ContainerValues
The container values associated with the given subview.
var id: Subview.ID
The unique identifier of the view.
Enumerations
enum ContainerSizingOptions
Options on how all subviews should be sized when in a container.
Beta
Relationships
Conforms To
IdentifiableView
See Also
Accessing a container’s subviews
struct SubviewsCollection
An opaque collection representing the subviews of view.
struct SubviewsCollectionSlice
A slice of a SubviewsCollection.
Sets a particular container value of a view.
struct ContainerValues
A collection of container values associated with a given view.
protocol ContainerValueKey
A key for accessing container values.
https://developer.apple.com/documentation/swiftui/subviewscollection
- SwiftUI
- SubviewsCollection
Structure
SubviewsCollection
An opaque collection representing the subviews of view.
struct SubviewsCollection
Overview
Subviews collection constructs subviews on demand, so only access the part of the collection you need to create the resulting content.
You can get access to a view’s subview collection by using the Group/init(sectionsOf:transform:) initializer.
The collection’s elements are the pieces that make up the given view, and the collection as a whole acts as a proxy for the original view.
Relationships
Conforms To
BidirectionalCollectionCollectionCopyableRandomAccessCollectionSequenceView
See Also
Accessing a container’s subviews
struct Subview
An opaque value representing a subview of another view.
struct SubviewsCollectionSlice
A slice of a SubviewsCollection.
Sets a particular container value of a view.
struct ContainerValues
A collection of container values associated with a given view.
protocol ContainerValueKey
A key for accessing container values.
https://developer.apple.com/documentation/swiftui/subviewscollectionslice
- SwiftUI
- SubviewsCollectionSlice
Structure
SubviewsCollectionSlice
A slice of a SubviewsCollection.
struct SubviewsCollectionSlice
Relationships
Conforms To
BidirectionalCollectionCollectionCopyableRandomAccessCollectionSequenceView
See Also
Accessing a container’s subviews
struct Subview
An opaque value representing a subview of another view.
struct SubviewsCollection
An opaque collection representing the subviews of view.
Sets a particular container value of a view.
struct ContainerValues
A collection of container values associated with a given view.
protocol ContainerValueKey
A key for accessing container values.
https://developer.apple.com/documentation/swiftui/tabcontentbuilder/content
- SwiftUI
- TabContentBuilder
- TabContentBuilder.Content
Structure
TabContentBuilder.Content
A view representation of the content of a builder-based tab view with selection.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/table
- SwiftUI
- Table
Structure
Table
A container that presents rows of data arranged in one or more columns, optionally providing the ability to select one or more members.
Overview
You commonly create tables from collections of data. The following example shows how to create a simple, three-column table from an array of Person instances that conform to the Identifiable protocol:
struct Person: Identifiable { let givenName: String let familyName: String let emailAddress: String let id = UUID()
var fullName: String { givenName + " " + familyName } }
@State private var people = [
Person(givenName: "Juan", familyName: "Chavez", emailAddress: "juanchavez@icloud.com"),
Person(givenName: "Mei", familyName: "Chen", emailAddress: "meichen@icloud.com"),
Person(givenName: "Tom", familyName: "Clark", emailAddress: "tomclark@icloud.com"),
Person(givenName: "Gita", familyName: "Kumar", emailAddress: "gitakumar@icloud.com")
]
struct PeopleTable: View { var body: some View { Table(people) { TableColumn("Given Name", value: .givenName) TableColumn("Family Name", value: .familyName) TableColumn("E-Mail Address", value: .emailAddress) } } }
If there are more rows than can fit in the available space, Table provides vertical scrolling automatically. On macOS, the table also provides horizontal scrolling if there are more columns than can fit in the width of the view. Scroll bars appear as needed on iOS; on macOS, the Table shows or hides scroll bars based on the “Show scroll bars” system preference.
Supporting selection in tables
To make rows of a table selectable, provide a binding to a selection variable. Binding to a single instance of the table data’s id type creates a single-selection table. Binding to a Set creates a table that supports multiple selections. The following example shows how to add multi-select to the previous example. A Text view below the table shows the number of items currently selected.
struct SelectableTable: View {
var body: some View { Table(people, selection: $selectedPeople) { TableColumn("Given Name", value: .givenName) TableColumn("Family Name", value: .familyName) TableColumn("E-Mail Address", value: .emailAddress) } Text("(selectedPeople.count) people selected") } }
Supporting sorting in tables
To make the columns of a table sortable, provide a binding to an array of SortComparator instances. The table reflects the sorted state through its column headers, allowing sorting for any columns with key paths.
When the table sort descriptors update, re-sort the data collection that underlies the table; the table itself doesn’t perform a sort operation. You can watch for changes in the sort descriptors by using a onChange(of:perform:) modifier, and then sort the data in the modifier’s perform closure.
The following example shows how to add sorting capability to the previous example:
struct SortableTable: View { @State private var sortOrder = [KeyPathComparator(\Person.givenName)]
var body: some View { Table(people, sortOrder: $sortOrder) { TableColumn("Given Name", value: .givenName) TableColumn("Family Name", value: .familyName) TableColumn("E-Mail address", value: .emailAddress) } .onChange(of: sortOrder) { _, sortOrder in people.sort(using: sortOrder) } } }
Building tables with static rows
To create a table from static rows, rather than the contents of a collection of data, you provide both the columns and the rows.
The following example shows a table that calculates prices from applying varying gratuities (“tips”) to a fixed set of prices. It creates the table with the init(of:columns:rows:) initializer, with the rows parameter providing the base price that each row uses for its calculations. Each column receives each price and performs its calculation, producing a Text to display the formatted result.
struct Purchase: Identifiable { let price: Decimal let id = UUID() }
struct TipTable: View { let currencyStyle = Decimal.FormatStyle.Currency(code: "USD")
var body: some View { Table(of: Purchase.self) { TableColumn("Base price") { purchase in Text(purchase.price, format: currencyStyle) } TableColumn("With 15% tip") { purchase in Text(purchase.price * 1.15, format: currencyStyle) } TableColumn("With 20% tip") { purchase in Text(purchase.price * 1.2, format: currencyStyle) } TableColumn("With 25% tip") { purchase in Text(purchase.price * 1.25, format: currencyStyle) } } rows: { TableRow(Purchase(price: 20)) TableRow(Purchase(price: 50)) TableRow(Purchase(price: 75)) } } }
Styling tables
Use the tableStyle(_:) modifier to set a TableStyle for all tables within a view. SwiftUI provides several table styles, such as InsetTableStyle and, on macOS, BorderedTableStyle. The default style is AutomaticTableStyle, which is available on all platforms that support Table.
Using tables on different platforms
You can define a single table for use on macOS, iOS, and iPadOS. However, on iPhone or in a compact horizontal size class environment — typical on on iPad in certain modes, like Slide Over — the table has limited space to display its columns. To conserve space, the table automatically hides headers and all columns after the first when it detects this condition.
To provide a good user experience in a space-constrained environment, you can customize the first column to show more information when you detect that the horizontalSizeClass environment value becomes UserInterfaceSizeClass.compact. For example, you can modify the sortable table from above to conditionally show all the information in the first column:
struct CompactableTable: View { #if os(iOS) @Environment(.horizontalSizeClass) private var horizontalSizeClass private var isCompact: Bool { horizontalSizeClass == .compact } #else private let isCompact = false #endif
@State private var sortOrder = [KeyPathComparator(\Person.givenName)]
var body: some View { Table(people, sortOrder: $sortOrder) { TableColumn("Given Name", value: .givenName) { person in VStack(alignment: .leading) { Text(isCompact ? person.fullName : person.givenName) if isCompact { Text(person.emailAddress) .foregroundStyle(.secondary) } } } TableColumn("Family Name", value: .familyName) TableColumn("E-Mail Address", value: .emailAddress) } .onChange(of: sortOrder) { _, sortOrder in people.sort(using: sortOrder) } } }
By making this change, you provide a list-like appearance for narrower displays, while displaying the full table on wider ones. Because you use the same table instance in both cases, you get a seamless transition when the size class changes, like when someone moves your app into or out of Slide Over.
Topics
Creating a table from columns
Creates a table that computes its rows based on a collection of identifiable data.
init(_:selection:columns:)
Creates a table that computes its rows based on a collection of identifiable data, and that supports selecting multiple rows.
Creating a sortable table from columns
Creates a sortable table that computes its rows based on a collection of identifiable data.
init(_:selection:sortOrder:columns:)
Creates a sortable table that computes its rows based on a collection of identifiable data, and supports selecting multiple rows.
Creating a table from columns and rows
Creates a table with the given columns and rows that generates its contents using values of the given type.
init(of:selection:columns:rows:)
Creates a table with the given columns and rows that supports selecting multiple rows that generates its data using values of the given type.
Creating a sortable table from columns and rows
Creates a sortable table with the given columns and rows.
init(of:selection:sortOrder:columns:rows:)
Creates a sortable table with the given columns and rows that supports selecting multiple rows.
init(selection:sortOrder:columns:rows:)
Creating a table with customizable columns
init<Data>(Data, columnCustomization: Binding<TableColumnCustomization<Value>>, columns: () -> Columns)
Creates a table that computes its rows based on a collection of identifiable data and has dynamically customizable columns.
init(_:selection:columnCustomization:columns:)
Creates a table that computes its rows based on a collection of identifiable data, that supports selecting multiple rows, and that has dynamically customizable columns.
init(_:selection:sortOrder:columnCustomization:columns:)
Creates a sortable table that computes its rows based on a collection of identifiable data, supports selecting multiple rows, and has dynamically customizable columns.
Creates a sortable table that computes its rows based on a collection of identifiable data and has dynamically customizable columns.
Creating a table with dynamically customizable columns
init(of: Value.Type, columnCustomization: Binding<TableColumnCustomization<Value>>, columns: () -> Columns, rows: () -> Rows)
Creates a table with the given columns and rows that generates its contents using values of the given type and has dynamically customizable columns.
init(of:selection:columnCustomization:columns:rows:)
Creates a table with the given columns and rows that supports selecting multiple rows that generates its data using values of the given type and has dynamically customizable columns.
init(of:selection:sortOrder:columnCustomization:columns:rows:)
Creates a sortable table with the given columns and rows that supports selecting multiple rows and dynamically customizable columns.
Creates a sortable table with the given columns and rows and has dynamically customizable columns.
Creating a hierarchical table
init<Data>(Data, children: KeyPath<Value, Data?>, columnCustomization: Binding<TableColumnCustomization<Value>>?, columns: () -> Columns)
Creates a hierarchical table that computes its rows based on a collection of identifiable data and key path to the children of that data.
init(_:children:selection:columnCustomization:columns:)
Creates a hierarchical table that computes its rows based on a collection of identifiable data and key path to the children of that data, and supports selecting multiple rows.
init(_:children:selection:sortOrder:columnCustomization:columns:)
Creates a sortable, hierarchical table that computes its rows based on a collection of identifiable data and key path to the children of that data, and supports selecting multiple rows.
Creates a sortable, hierarchical table that computes its rows based on a collection of identifiable data and key path to the children of that data.
Relationships
Conforms To
View
See Also
Creating a table
Building a Great Mac App with SwiftUI
Create engaging SwiftUI Mac apps by incorporating side bars, tables, toolbars, and several other popular user interface elements.
Sets the style for tables within this view.
https://developer.apple.com/documentation/swiftui/texteditor
- SwiftUI
- TextEditor
Structure
TextEditor
A view that can display and edit long-form text.
struct TextEditor
Overview
A text editor view allows you to display and edit multiline, scrollable text in your app’s user interface. By default, the text editor view styles the text using characteristics inherited from the environment, like font(_:), foregroundColor(_:), and multilineTextAlignment(_:).
You create a text editor by adding a TextEditor instance to the body of your view, and initialize it by passing in a Binding to a string variable in your app:
struct TextEditingView: View { @State private var fullText: String = "This is some editable text..."
var body: some View { TextEditor(text: $fullText) } }
To style the text, use the standard view modifiers to configure a system font, set a custom font, or change the color of the view’s text.
In this example, the view renders the editor’s text in gray with a custom font:
var body: some View { TextEditor(text: $fullText) .foregroundColor(Color.gray) .font(.custom("HelveticaNeue", size: 13)) } }
If you want to change the spacing or font scaling aspects of the text, you can use modifiers like lineLimit(_:), lineSpacing(_:), and minimumScaleFactor(_:) to configure how the view displays text depending on the space constraints. For example, here the lineSpacing(_:) modifier sets the spacing between lines to 5 points:
var body: some View { TextEditor(text: $fullText) .foregroundColor(Color.gray) .font(.custom("HelveticaNeue", size: 13)) .lineSpacing(5) } }
Topics
Creating a text editor
Creates a plain text editor.
Initializers
init(text:selection:)
Creates a styled text editor.
Relationships
Conforms To
View
See Also
Getting text input
Building rich SwiftUI text experiences
Build an editor for formatted text using SwiftUI text editor views and attributed strings.
struct TextField
A control that displays an editable text interface.
Sets the style for text fields within this view.
struct SecureField
A control into which people securely enter private text.
https://developer.apple.com/documentation/swiftui/textfield
- SwiftUI
- TextField
Structure
TextField
A control that displays an editable text interface.
Overview
You create a text field with a label and a binding to a value. If the value is a string, the text field updates this value continuously as the user types or otherwise edits the text in the field. For non-string types, it updates the value when the user commits their edits, such as by pressing the Return key.
The following example shows a text field to accept a username, and a Text view below it that shadows the continuously updated value of username. The Text view changes color as the user begins and ends editing. When the user submits their completed entry to the text field, the onSubmit(of:_:) modifier calls an internal validate(name:) method.
@State private var username: String = "" @FocusState private var emailFieldIsFocused: Bool = false
var body: some View { TextField( "User name (email address)", text: $username ) .focused($emailFieldIsFocused) .onSubmit { validate(name: username) } .textInputAutocapitalization(.never) .disableAutocorrection(true) .border(.secondary)
Text(username) .foregroundColor(emailFieldIsFocused ? .red : .blue) }
The bound value doesn’t have to be a string. By using a FormatStyle, you can bind the text field to a nonstring type, using the format style to convert the typed text into an instance of the bound type. The following example uses a PersonNameComponents.FormatStyle to convert the name typed in the text field to a PersonNameComponents instance. A Text view below the text field shows the debug description string of this instance.
@State private var nameComponents = PersonNameComponents()
var body: some View { TextField( "Proper name", value: $nameComponents, format: .name(style: .medium) ) .onSubmit { validate(components: nameComponents) } .disableAutocorrection(true) .border(.secondary) Text(nameComponents.debugDescription) }
Text field prompts
You can set an explicit prompt on the text field to guide users on what text they should provide. Each text field style determines where and when the text field uses a prompt and label. For example, a form on macOS always places the label at the leading edge of the field and uses a prompt, when available, as placeholder text within the field itself. In the same context on iOS, the text field uses either the prompt or label as placeholder text, depending on whether the initializer provided a prompt.
The following example shows a Form with two text fields, each of which provides a prompt to indicate that the field is required, and a view builder to provide a label:
Form { TextField(text: $username, prompt: Text("Required")) { Text("Username") } SecureField(text: $password, prompt: Text("Required")) { Text("Password") } }
Styling text fields
SwiftUI provides a default text field style that reflects an appearance and behavior appropriate to the platform. The default style also takes the current context into consideration, like whether the text field is in a container that presents text fields with a special style. Beyond this, you can customize the appearance and interaction of text fields using the textFieldStyle(_:) modifier, passing in an instance of TextFieldStyle. The following example applies the roundedBorder style to both text fields within a VStack.
@State private var givenName: String = "" @State private var familyName: String = ""
var body: some View { VStack { TextField( "Given Name", text: $givenName ) .disableAutocorrection(true) TextField( "Family Name", text: $familyName ) .disableAutocorrection(true) } .textFieldStyle(.roundedBorder) }
Topics
Creating a text field with a string
init(_:text:)
Creates a text field with a text label generated from a localized title string.
init(_:text:prompt:)
Creates a text field with a prompt generated from a Text.
Creating a scrollable text field
init(_:text:axis:)
Creates a text field with a preferred axis and a text label generated from a localized title string.
init(_:text:prompt:axis:)
Creates a text field with a preferred axis and a prompt generated from a Text.
Creating a text field with a value
Use these initializers to create a text field that binds to a value of an arbitrary type.
init(_:value:format:prompt:)
Creates a text field that applies a format style to a bound value, with a label generated from a localized title string.
init(value:format:prompt:label:)
Creates a text field that applies a format style to a bound value, with a label generated from a view builder.
init(_:value:formatter:)
Create an instance which binds over an arbitrary type, V.
init(_:value:formatter:prompt:)
Creates a text field that applies a formatter to a bound value, with a label generated from a title string.
Creates a text field that applies a formatter to a bound optional value, with a label generated from a view builder.
Deprecated initializers
Review deprecated text field initializers.
Initializers
init(_:text:selection:prompt:axis:)
Creates a text field with a binding to the current selection and a text label generated from a localized title string.
Relationships
Conforms To
View
See Also
Getting text input
Building rich SwiftUI text experiences
Build an editor for formatted text using SwiftUI text editor views and attributed strings.
Sets the style for text fields within this view.
struct SecureField
A control into which people securely enter private text.
struct TextEditor
A view that can display and edit long-form text.
https://developer.apple.com/documentation/swiftui/textfieldlink
- SwiftUI
- TextFieldLink
Structure
TextFieldLink
A control that requests text input from the user when pressed.
Overview
A TextFieldLink should be used to request text input from the user through a button interface.
Topics
Creating a text field link
init(_:prompt:onSubmit:)
Creates a TextFieldLink which when pressed will request text input from the user.
Relationships
Conforms To
View
See Also
Linking to other content
struct Link
A control for navigating to a URL.
struct ShareLink
A view that controls a sharing presentation.
struct SharePreview
A representation of a type to display in a share preview.
struct HelpLink
A button with a standard appearance that opens app-specific help documentation.
https://developer.apple.com/documentation/swiftui/timelineview
- SwiftUI
- TimelineView
Structure
TimelineView
A view that updates according to a schedule that you provide.
Overview
A timeline view acts as a container with no appearance of its own. Instead, it redraws the content it contains at scheduled points in time. For example, you can update the face of an analog timer once per second:
TimelineView(.periodic(from: startDate, by: 1)) { context in AnalogTimerView(date: context.date) }
The closure that creates the content receives an input of type TimelineView.Context that you can use to customize the content’s appearance. The context includes the date that triggered the update. In the example above, the timeline view sends that date to an analog timer that you create so the timer view knows how to draw the hands on its face.
The context also includes a cadence property that you can use to hide unnecessary detail. For example, you can use the cadence to decide when it’s appropriate to display the timer’s second hand:
TimelineView(.periodic(from: startDate, by: 1.0)) { context in AnalogTimerView( date: context.date, showSeconds: context.cadence <= .seconds) }
The system might use a cadence that’s slower than the schedule’s update rate. For example, a view on watchOS might remain visible when the user lowers their wrist, but update less frequently, and thus require less detail.
You can define a custom schedule by creating a type that conforms to the TimelineSchedule protocol, or use one of the built-in schedule types:
-
Use an
everyMinuteschedule to update at the beginning of each minute. -
Use a
periodic(from:by:)schedule to update periodically with a custom start time and interval between updates. -
Use an
explicit(_:)schedule when you need a finite number, or irregular set of updates.
For a schedule containing only dates in the past, the timeline view shows the last date in the schedule. For a schedule containing only dates in the future, the timeline draws its content using the current date until the first scheduled date arrives.
Topics
Creating a timeline
Creates a new timeline view that uses the given schedule.
struct Context
Information passed to a timeline view’s content callback.
Deprecated symbols
Deprecated
Initializers
init(_:content:)
Relationships
Conforms To
CopyableViewConforms whenScheduleconforms toTimelineScheduleandContentconforms toView.
See Also
Updating a view on a schedule
Updating watchOS apps with timelines
Seamlessly schedule updates to your user interface, even while it’s inactive.
protocol TimelineSchedule
A type that provides a sequence of dates for use as a schedule.
typealias TimelineViewDefaultContext
https://developer.apple.com/documentation/swiftui/toggle
- SwiftUI
- Toggle
Structure
Toggle
A control that toggles between on and off states.
Mentioned in
Building and customizing the menu bar with SwiftUI
Declaring a custom view
Laying out a simple view
Populating SwiftUI menus with adaptive controls
Overview
You create a toggle by providing an isOn binding and a label. Bind isOn to a Boolean property that determines whether the toggle is on or off. Set the label to a view that visually describes the purpose of switching between toggle states. For example:
@State private var vibrateOnRing = false
var body: some View { Toggle(isOn: $vibrateOnRing) { Text("Vibrate on Ring") } }
For the common case of Label based labels, you can use the convenience initializer that takes a title string (or localized string key) and the name of a system image:
@State private var vibrateOnRing = true
var body: some View { Toggle( "Vibrate on Ring", systemImage: "dot.radiowaves.left.and.right", isOn: $vibrateOnRing ) }
For text-only labels, you can use the convenience initializer that takes a title string (or localized string key) as its first parameter, instead of a trailing closure:
var body: some View { Toggle("Vibrate on Ring", isOn: $vibrateOnRing) }
For cases where adding a subtitle to the label is desired, use a view builder that creates multiple Text views where the first text represents the title and the second text represents the subtitle:
var body: some View { Toggle(isOn: $vibrateOnRing) { Text("Vibrate on Ring") Text("Enable vibration when the phone rings") } }
Styling toggles
Toggles use a default style that varies based on both the platform and the context. For more information, read about the automatic toggle style.
You can customize the appearance and interaction of toggles by applying styles using the toggleStyle(_:) modifier. You can apply built-in styles, like switch, to either a toggle, or to a view hierarchy that contains toggles:
VStack { Toggle("Vibrate on Ring", isOn: $vibrateOnRing) Toggle("Vibrate on Silent", isOn: $vibrateOnSilent) } .toggleStyle(.switch)
You can also define custom styles by creating a type that conforms to the ToggleStyle protocol.
Topics
Creating a toggle
init(_:isOn:)
Creates a toggle that generates its label from a localized string key.
Creates a toggle that displays a custom label.
init(_:image:isOn:)
Creates a toggle that generates its label from a localized string key and image resource.
init(_:systemImage:isOn:)
Creates a toggle that generates its label from a localized string key and system image.
Creating a toggle for a collection
init(_:sources:isOn:)
Creates a toggle representing a collection of values that generates its label from a localized string key.
init<C>(sources: C, isOn: KeyPath<C.Element, Binding<Bool>>, label: () -> Label)
Creates a toggle representing a collection of values with a custom label.
init(_:image:sources:isOn:)
Creates a toggle representing a collection of values that generates its label from a localized string key and image resource.
init(_:systemImage:sources:isOn:)
Creates a toggle representing a collection of values that generates its label from a localized string key and system image.
Creating a toggle from a configuration
init(ToggleStyleConfiguration)
Creates a toggle based on a toggle style configuration.
Creating a toggle for an App Intent
Creates a toggle performing an AppIntent.
init(_:isOn:intent:)
Creates a toggle performing an AppIntent and generates its label from a localized string key.
Relationships
Conforms To
View
See Also
Getting numeric inputs
struct Slider
A control for selecting a value from a bounded linear range of values.
struct Stepper
A control that performs increment and decrement actions.
Sets the style for toggles in a view hierarchy.
https://developer.apple.com/documentation/swiftui/togglestyleconfiguration/label-swift.struct
- SwiftUI
- ToggleStyleConfiguration
- ToggleStyleConfiguration.Label
Structure
ToggleStyleConfiguration.Label
A type-erased label of a toggle.
@MainActor @preconcurrency struct Label
Overview
SwiftUI provides a value of this type — which is a View type — as the label to your custom toggle style implementation. Use the label to help define the appearance of the toggle.
Relationships
Conforms To
View
See Also
Getting the label view
let label: ToggleStyleConfiguration.Label
A view that describes the effect of switching the toggle between states.
https://developer.apple.com/documentation/swiftui/transformedshape
- SwiftUI
- TransformedShape
Structure
TransformedShape
A shape with an affine transform applied to it.
@frozen
Topics
Creating a transformed shape
init(shape: Content, transform: CGAffineTransform)
Getting the shape’s characteristics
var shape: Content
var transform: CGAffineTransform
Relationships
Conforms To
AnimatableSendableSendableMetatypeShapeView
See Also
Transforming a shape
struct ScaledShape
A shape with a scale transform applied to it.
struct RotatedShape
A shape with a rotation transform applied to it.
struct OffsetShape
A shape with a translation offset transform applied to it.
https://developer.apple.com/documentation/swiftui/tupleview
- SwiftUI
- TupleView
Structure
TupleView
A View created from a swift tuple of View values.
@frozen
Topics
Creating a tuple view
init(T)
var value: T
Relationships
Conforms To
View
See Also
Supporting view types
struct AnyView
A type-erased view.
struct EmptyView
A view that doesn’t contain any content.
struct EquatableView
A view type that compares itself against its previous value and prevents its child updating if its new value is the same as its old value.
struct SubscriptionView
A view that subscribes to a publisher with an action.
https://developer.apple.com/documentation/swiftui/unevenroundedrectangle
- SwiftUI
- UnevenRoundedRectangle
Structure
UnevenRoundedRectangle
A rectangular shape with rounded corners with different values, aligned inside the frame of the view containing it.
@frozen struct UnevenRoundedRectangle
Topics
Creating an uneven rounded rectangle
init(cornerRadii: RectangleCornerRadii, style: RoundedCornerStyle)
Creates a new rounded rectangle shape with uneven corners.
init(topLeadingRadius: CGFloat, bottomLeadingRadius: CGFloat, bottomTrailingRadius: CGFloat, topTrailingRadius: CGFloat, style: RoundedCornerStyle)
Getting the shape’s characteristics
var cornerRadii: RectangleCornerRadii
The radii of each corner of the rounded rectangle.
var style: RoundedCornerStyle
The style of corners drawn by the rounded rectangle.
Supporting types
var animatableData: RectangleCornerRadii.AnimatableData
The data to animate.
Relationships
Conforms To
AnimatableCopyableInsettableShapeSendableSendableMetatypeShapeView
See Also
Creating rectangular shapes
struct Rectangle
A rectangular shape aligned inside the frame of the view containing it.
struct RoundedRectangle
A rectangular shape with rounded corners, aligned inside the frame of the view containing it.
enum RoundedCornerStyle
Defines the shape of a rounded rectangle’s corners.
struct RectangleCornerRadii
Describes the corner radius values of a rounded rectangle with uneven corners.
https://developer.apple.com/documentation/swiftui/vstack
- SwiftUI
- VStack
Structure
VStack
A view that arranges its subviews in a vertical line.
@frozen
Mentioned in
Building layouts with stack views
Creating performant scrollable stacks
Picking container views for your content
Adding a background to your view
Inspecting view layout
Overview
Unlike LazyVStack, which only renders the views when your app needs to display them, a VStack renders the views all at once, regardless of whether they are on- or offscreen. Use the regular VStack when you have a small number of subviews or don’t want the delayed rendering behavior of the “lazy” version.
The following example shows a simple vertical stack of 10 text views:
var body: some View { VStack( alignment: .leading, spacing: 10 ) { ForEach( 1...10, id: .self ) { Text("Item ($0)") } } }
Topics
Creating a stack
Creates an instance with the given spacing and horizontal alignment.
Relationships
Conforms To
View
See Also
Statically arranging views in one dimension
Compose complex layouts from primitive container views.
struct HStack
A view that arranges its subviews in a horizontal line.
https://developer.apple.com/documentation/swiftui/viewthatfits
- SwiftUI
- ViewThatFits
Structure
ViewThatFits
A view that adapts to the available space by providing the first child view that fits.
@frozen
Overview
ViewThatFits evaluates its child views in the order you provide them to the initializer. It selects the first child whose ideal size on the constrained axes fits within the proposed size. This means that you provide views in order of preference. Usually this order is largest to smallest, but since a view might fit along one constrained axis but not the other, this isn’t always the case. By default, ViewThatFits constrains in both the horizontal and vertical axes.
The following example shows an UploadProgressView that uses ViewThatFits to display the upload progress in one of three ways. In order, it attempts to display:
-
An
HStackthat contains aTextview and aProgressView. -
Only the
ProgressView. -
Only the
Textview.
The progress views are fixed to a 100-point width.
struct UploadProgressView: View { var uploadProgress: Double
var body: some View { ViewThatFits(in: .horizontal) { HStack { Text("(uploadProgress.formatted(.percent))") ProgressView(value: uploadProgress) .frame(width: 100) } ProgressView(value: uploadProgress) .frame(width: 100) Text("(uploadProgress.formatted(.percent))") } } }
This use of ViewThatFits evaluates sizes only on the horizontal axis. The following code fits the UploadProgressView to several fixed widths:
VStack { UploadProgressView(uploadProgress: 0.75) .frame(maxWidth: 200) UploadProgressView(uploadProgress: 0.75) .frame(maxWidth: 100) UploadProgressView(uploadProgress: 0.75) .frame(maxWidth: 50) }
Topics
Creating a view that fits
Produces a view constrained in the given axes from one of several alternatives provided by a view builder.
Relationships
Conforms To
View
https://developer.apple.com/documentation/swiftui/zstack
- SwiftUI
- ZStack
Structure
ZStack
A view that overlays its subviews, aligning them in both axes.
@frozen
Mentioned in
Building layouts with stack views
Laying out a simple view
Adding a background to your view
Aligning views within a stack
Creating performant scrollable stacks
Overview
The ZStack assigns each successive subview a higher z-axis value than the one before it, meaning later subviews appear “on top” of earlier ones.
The following example creates a ZStack of 100 x 100 point Rectangle views filled with one of six colors, offsetting each successive subview by 10 points so they don’t completely overlap:
let colors: [Color] = [.red, .orange, .yellow, .green, .blue, .purple]
var body: some View { ZStack { ForEach(0..<colors.count) { Rectangle() .fill(colors[$0]) .frame(width: 100, height: 100) .offset(x: CGFloat($0) * 10.0, y: CGFloat($0) * 10.0) } } }
The ZStack uses an Alignment to set the x- and y-axis coordinates of each subview, defaulting to a center alignment. In the following example, the ZStack uses a bottomLeading alignment to lay out two subviews, a red 100 x 50 point rectangle below, and a blue 50 x 100 point rectangle on top. Because of the alignment value, both rectangles share a bottom-left corner with the ZStack (in locales where left is the leading side).
var body: some View { ZStack(alignment: .bottomLeading) { Rectangle() .fill(Color.red) .frame(width: 100, height: 50) Rectangle() .fill(Color.blue) .frame(width:50, height: 100) } .border(Color.green, width: 1) }
Topics
Creating a stack
Creates an instance with the given alignment.
Supporting symbols
struct ZStackContent3D
A type that adds spacing to a ZStack.
Initializers
Creates an instance with the given spacing and alignment.
Relationships
Conforms To
View
See Also
Layering views
Compose a background behind your view and extend it beyond the safe area insets.
Controls the display order of overlapping views.
Layers the views that you specify behind this view.
Sets the view’s background to a style.
Sets the view’s background to the default background style.
func background(_:in:fillStyle:)
Sets the view’s background to an insettable shape filled with a style.
func background(in:fillStyle:)
Sets the view’s background to an insettable shape filled with the default background style.
Layers the views that you specify in front of this view.
Layers the specified style in front of this view.
Layers a shape that you specify in front of this view.
var backgroundMaterial: Material?
The material underneath the current view.
Sets the container background of the enclosing container using a view.
struct ContainerBackgroundPlacement
The placement of a container background.
https://developer.apple.com/documentation/swiftui/zstackcontent3d
- SwiftUI
- ZStackContent3D
Structure
ZStackContent3D
A type that adds spacing to a ZStack.
@frozen
Overview
You don’t create this type directly. SwiftUI creates it for you when you use the ZStack(alignment:spacing:content) initializer.
Topics
Initializers
init(spacing: CGFloat?, content: Content)
Instance Properties
var content: Content
var spacing: CGFloat?
Relationships
Conforms To
CopyableViewConforms whenContentconforms toView.
https://developer.apple.com/documentation/swiftui/viewbuilder
- SwiftUI
- ViewBuilder
Structure
ViewBuilder
A custom parameter attribute that constructs views from closures.
@resultBuilder struct ViewBuilder
Mentioned in
Populating SwiftUI menus with adaptive controls
Declaring a custom view
Overview
You typically use ViewBuilder as a parameter attribute for child view-producing closure parameters, allowing those closures to provide multiple child views. For example, the following contextMenu function accepts a closure that produces one or more views via the view builder.
Clients of this function can use multiple-statement closures to provide several child views, as shown in the following example:
myView.contextMenu { Text("Cut") Text("Copy") Text("Paste") if isSymbol { Text("Jump to Definition") } }
Topics
Building content
Builds an empty view from a block containing no statements.
static buildBlock(_:)
Passes a single view written as a child view through unmodified.
Builds an expression within the builder.
Conditionally building content
Produces content for a conditional statement in a multi-statement closure when the condition is true.
Produces content for a conditional statement in a multi-statement closure when the condition is false.
Produces an optional view for conditional statements in multi-statement closures that’s only visible when the condition evaluates to true.
Processes view content for a conditional compiler-control statement that performs an availability check.
See Also
Creating a view
Define views and assemble them into a view hierarchy.
protocol View
A type that represents part of your app’s user interface and provides modifiers that you use to configure views.
https://developer.apple.com/documentation/swiftui/declaring-a-custom-view)
https://developer.apple.com/documentation/swiftui/configuring-views)
https://developer.apple.com/documentation/swiftui/reducing-view-modifier-maintenance)
https://developer.apple.com/documentation/swiftui/displaying-data-in-lists)
https://developer.apple.com/documentation/swiftui/view/body-8kl5o)
https://developer.apple.com/documentation/swiftui/text)
https://developer.apple.com/documentation/swiftui/declaring-a-custom-view).
https://developer.apple.com/documentation/swiftui/configuring-views).
https://developer.apple.com/documentation/swiftui/view/opacity(_:))
https://developer.apple.com/documentation/swiftui/view-layout),
https://developer.apple.com/documentation/swiftui/view-accessibility)
https://developer.apple.com/documentation/swiftui/view-input-and-events).
https://developer.apple.com/documentation/swiftui/view/body-swift.associatedtype)
https://developer.apple.com/documentation/swiftui/view/modifier(_:))
https://developer.apple.com/documentation/swiftui/view-appearance)
https://developer.apple.com/documentation/swiftui/view-text-and-symbols)
https://developer.apple.com/documentation/swiftui/view-auxiliary-views)
https://developer.apple.com/documentation/swiftui/view-chart-view)
https://developer.apple.com/documentation/swiftui/view-style-modifiers)
https://developer.apple.com/documentation/swiftui/view-layout)
https://developer.apple.com/documentation/swiftui/view-graphics-and-rendering)
https://developer.apple.com/documentation/swiftui/view-input-and-events)
https://developer.apple.com/documentation/swiftui/view-search)
https://developer.apple.com/documentation/swiftui/view-presentation)
https://developer.apple.com/documentation/swiftui/view-state)
https://developer.apple.com/documentation/swiftui/view-deprecated)
https://developer.apple.com/documentation/swiftui/view/accessibilityactions(category:_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/accessibilitydefaultfocus(::))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/accessibilityscrollstatus(_:isenabled:))
https://developer.apple.com/documentation/swiftui/view/accessorywidgetgroupstyle(_:))
https://developer.apple.com/documentation/swiftui/view/addordertowalletbuttonstyle(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/addpasstowalletbuttonstyle(_:))
https://developer.apple.com/documentation/swiftui/view/allowswindowactivationevents())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/appstoreoffer(ispresented:kind:ondismiss:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/aspectratio3d(_:contentmode:))
https://developer.apple.com/documentation/swiftui/view/assistiveaccessnavigationicon(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/assistiveaccessnavigationicon(systemimage:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/attributedtextformattingdefinition(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/automateddeviceenrollmentaddition(ispresented:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/breakthrougheffect(_:))
https://developer.apple.com/documentation/swiftui/view/buttonsizing(_:))
https://developer.apple.com/documentation/swiftui/view/certificatesheet(trust:title:message:help:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/chart3dcameraprojection(_:))
https://developer.apple.com/documentation/swiftui/view/chart3dpose(_:))
https://developer.apple.com/documentation/swiftui/view/chart3drenderingstyle(_:))
https://developer.apple.com/documentation/swiftui/view/chartzaxis(_:))
https://developer.apple.com/documentation/swiftui/view/chartzaxis(content:))
https://developer.apple.com/documentation/swiftui/view/chartzaxislabel(_:position:alignment:spacing:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/chartzscale(domain:range:type:))
https://developer.apple.com/documentation/swiftui/view/chartzscale(domain:type:))
https://developer.apple.com/documentation/swiftui/view/chartzscale(range:type:))
https://developer.apple.com/documentation/swiftui/view/chartzselection(range:))
https://developer.apple.com/documentation/swiftui/view/chartzselection(value:))
https://developer.apple.com/documentation/swiftui/view/contactaccessbuttoncaption(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/contactaccessbuttonstyle(_:))
https://developer.apple.com/documentation/swiftui/view/contactaccesspicker(ispresented:completionhandler:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/containervalue(::))
https://developer.apple.com/documentation/swiftui/view/contentcaptureprotected(_:))
https://developer.apple.com/documentation/swiftui/view/contenttoolbar(for:content:))
https://developer.apple.com/documentation/swiftui/view/continuitydevicepicker(ispresented:ondidconnect:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/controlwidgetactionhint(_:))
https://developer.apple.com/documentation/swiftui/view/controlwidgetstatus(_:))
https://developer.apple.com/documentation/swiftui/view/currententitlementtask(for:priority:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/dialogpreventsapptermination(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/documentbrowsercontextmenu(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/dragconfiguration(_:))
https://developer.apple.com/documentation/swiftui/view/dragcontainer(for:id:in:_:))
https://developer.apple.com/documentation/swiftui/view/dragcontainer(for:id:in:selection:_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/dragcontainer(for:in:_:))
https://developer.apple.com/documentation/swiftui/view/dragcontainer(for:in:selection:_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/dragpreviewsformation(_:))
https://developer.apple.com/documentation/swiftui/view/draggable(::))
https://developer.apple.com/documentation/swiftui/view/draggable(containeritemid:))
https://developer.apple.com/documentation/swiftui/view/draggable(for🆔_:))
https://developer.apple.com/documentation/swiftui/view/dropconfiguration(_:))
https://developer.apple.com/documentation/swiftui/view/dropdestination(for:isenabled:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/droppreviewsformation(_:))
https://developer.apple.com/documentation/swiftui/view/formstyle(_:))
https://developer.apple.com/documentation/swiftui/view/gamesynceddirectoryloadingview(directory:finishedloading:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/glassbackgroundeffect(_:displaymode:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/glassbackgroundeffect(_:in:displaymode:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/glasseffectid(_:in:))
https://developer.apple.com/documentation/swiftui/view/glasseffecttransition(_:isenabled:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/glasseffectunion(id:namespace:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/groupactivityassociation(_:))
https://developer.apple.com/documentation/swiftui/view/handgestureshortcut(_:isenabled:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/handpointerbehavior(_:))
https://developer.apple.com/documentation/swiftui/view/handlesgamecontrollerevents(matching:))
https://developer.apple.com/documentation/swiftui/view/handlesgamecontrollerevents(matching:withoptions:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/healthdataaccessrequest(store:objecttype:predicate:trigger:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/healthdataaccessrequest(store:readtypes:trigger:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/healthdataaccessrequest(store:sharetypes:readtypes:trigger:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/imageplaygroundgenerationstyle(_:in:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/imageplaygroundpersonalizationpolicy(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/imageplaygroundsheet(ispresented:concept:sourceimage:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/imageplaygroundsheet(ispresented:concept:sourceimageurl:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/imageplaygroundsheet(ispresented:concepts:sourceimage:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/imageplaygroundsheet(ispresented:concepts:sourceimageurl:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/inapppurchaseoptions(_:))
https://developer.apple.com/documentation/swiftui/view/journalingsuggestionspicker(ispresented:journalingsuggestiontoken:oncompletion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/journalingsuggestionspicker(ispresented:oncompletion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/labelicontotitlespacing(_:))
https://developer.apple.com/documentation/swiftui/view/labelreservediconwidth(_:))
https://developer.apple.com/documentation/swiftui/view/labeledcontentstyle(_:))
https://developer.apple.com/documentation/swiftui/view/labelsvisibility(_:))
https://developer.apple.com/documentation/swiftui/view/lineheight(_:))
https://developer.apple.com/documentation/swiftui/view/listrowinsets(::))
https://developer.apple.com/documentation/swiftui/view/listsectionindexvisibility(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/listsectionmargins(::))
https://developer.apple.com/documentation/swiftui/view/lookaroundviewer(ispresented:initialscene:allowsnavigation:showsroadlabels:pointsofinterest:ondismiss:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/lookaroundviewer(ispresented:scene:allowsnavigation:showsroadlabels:pointsofinterest:ondismiss:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/managesubscriptionssheet(ispresented:subscriptiongroupid:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/managedcontentstyle(_:))
https://developer.apple.com/documentation/swiftui/view/manipulable(coordinatespace:operations:inertia:isenabled:onchanged:))
https://developer.apple.com/documentation/swiftui/view/manipulable(transform:coordinatespace:operations:inertia:isenabled:onchanged:))
https://developer.apple.com/documentation/swiftui/view/manipulable(using:))
https://developer.apple.com/documentation/swiftui/view/manipulationgesture(updating:coordinatespace:operations:inertia:isenabled:onchanged:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapcamerakeyframeanimator(trigger:keyframes:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapcontrolvisibility(_:))
https://developer.apple.com/documentation/swiftui/view/mapcontrols(_:))
https://developer.apple.com/documentation/swiftui/view/mapfeatureselectionaccessory(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapfeatureselectioncontent(content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapfeatureselectiondisabled(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapitemdetailpopover(ispresented:item:displaysmap:attachmentanchor:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapitemdetailpopover(ispresented:item:displaysmap:attachmentanchor:arrowedge:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapitemdetailpopover(item:displaysmap:attachmentanchor:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapitemdetailpopover(item:displaysmap:attachmentanchor:arrowedge:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapitemdetailsheet(ispresented:item:displaysmap:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapitemdetailsheet(item:displaysmap:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/mapscope(_:))
https://developer.apple.com/documentation/swiftui/view/mapstyle(_:))
https://developer.apple.com/documentation/swiftui/view/matchedtransitionsource(id:in:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/matchedtransitionsource(id:in:configuration:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/materialactiveappearance(_:))
https://developer.apple.com/documentation/swiftui/view/multilinetextalignment(strategy:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/navigationlinkindicatorvisibility(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/navigationtransition(_:))
https://developer.apple.com/documentation/swiftui/view/onappintentexecution(_:perform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/onapplepaycouponcodechange(perform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/onapplepaypaymentmethodchange(perform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/onapplepayshippingcontactchange(perform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/onapplepayshippingmethodchange(perform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/oncameracaptureevent(isenabled:defaultsounddisabled:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/oncameracaptureevent(isenabled:defaultsounddisabled:primaryaction:secondaryaction:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/ondragsessionupdated(_:))
https://developer.apple.com/documentation/swiftui/view/ondropsessionupdated(_:))
https://developer.apple.com/documentation/swiftui/view/ongeometrychange3d(for:of:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/oninapppurchasecompletion(perform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/oninapppurchasestart(perform:))
https://developer.apple.com/documentation/swiftui/view/onmapcamerachange(frequency:_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/onopenurl(prefersinapp:))
https://developer.apple.com/documentation/swiftui/view/onworldrecenter(action:))
https://developer.apple.com/documentation/swiftui/view/paylaterviewaction(_:))
https://developer.apple.com/documentation/swiftui/view/paylaterviewdisplaystyle(_:))
https://developer.apple.com/documentation/swiftui/view/paywithapplepaybuttondisablecardart())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/paywithapplepaybuttonstyle(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/popovertip(_:arrowedge:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/posttophotossharedalbumsheet(ispresented:items:photolibrary:defaultalbumidentifier:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/preferredsubscriptionoffer(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/preferredwindowclippingmargins(::))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/presentationbreakthrougheffect(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/presentationpreventsapptermination(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/productdescription(_:))
https://developer.apple.com/documentation/swiftui/view/producticonborder())
https://developer.apple.com/documentation/swiftui/view/productviewstyle(_:))
https://developer.apple.com/documentation/swiftui/view/realityviewcameracontrols(_:))
https://developer.apple.com/documentation/swiftui/view/realityviewlayoutbehavior(_:))
https://developer.apple.com/documentation/swiftui/view/rotation3dlayout(_:))
https://developer.apple.com/documentation/swiftui/view/rotation3dlayout(_:axis:))
https://developer.apple.com/documentation/swiftui/view/safeareabar(edge:alignment:spacing:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/scaledtofill3d())
https://developer.apple.com/documentation/swiftui/view/scaledtofit3d())
https://developer.apple.com/documentation/swiftui/view/scrolledgeeffectdisabled(_:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/scrolledgeeffectstyle(_:for:))
https://developer.apple.com/documentation/swiftui/view/scrollinputbehavior(_:for:))
https://developer.apple.com/documentation/swiftui/view/searchtoolbarbehavior(_:))
https://developer.apple.com/documentation/swiftui/view/sectionindexlabel(_:))
https://developer.apple.com/documentation/swiftui/view/signinwithapplebuttonstyle(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/spatialoverlay(alignment:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/spatialoverlaypreferencevalue(:alignment::))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/storebutton(_:for:))
https://developer.apple.com/documentation/swiftui/view/storeproducttask(for:priority:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/storeproductstask(for:priority:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionintroductoryoffer(applyoffer:compactjws:))
https://developer.apple.com/documentation/swiftui/view/subscriptionofferviewbuttonvisibility(_:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionofferviewdetailaction(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionofferviewstyle(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionpromotionaloffer(offer:compactjws:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionpromotionaloffer(offer:signature:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstatustask(for:priority:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstorebuttonlabel(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstorecontrolbackground(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstorecontrolicon(icon:))
https://developer.apple.com/documentation/swiftui/view/subscriptionstorecontrolstyle(_:))
https://developer.apple.com/documentation/swiftui/view/subscriptionstorecontrolstyle(_:placement:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstoreoptiongroupstyle(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepickeritembackground(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepickeritembackground(_:in:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepolicydestination(for:destination:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepolicydestination(url:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepolicyforegroundstyle(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstorepolicyforegroundstyle(::))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/subscriptionstoresigninaction(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/symbolcolorrenderingmode(_:))
https://developer.apple.com/documentation/swiftui/view/symbolvariablevaluemode(_:))
https://developer.apple.com/documentation/swiftui/view/tabbarminimizebehavior(_:))
https://developer.apple.com/documentation/swiftui/view/tabviewbottomaccessory(content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/tabletopgame(_:parent:automaticupdate:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/tabletopgame(_:parent:automaticupdate:interaction:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/textcontenttype(_:))
https://developer.apple.com/documentation/swiftui/view/textinputformattingcontrolvisibility(_:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/textrenderer(_:))
https://developer.apple.com/documentation/swiftui/view/textselectionaffinity(_:))
https://developer.apple.com/documentation/swiftui/view/tipbackground(_:))
https://developer.apple.com/documentation/swiftui/view/tipcornerradius(_:antialiased:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/tipimagesize(_:))
https://developer.apple.com/documentation/swiftui/view/tipimagestyle(_:))
https://developer.apple.com/documentation/swiftui/view/tipimagestyle(::))
https://developer.apple.com/documentation/swiftui/view/tipimagestyle(::_:))
https://developer.apple.com/documentation/swiftui/view/tipviewstyle(_:))
https://developer.apple.com/documentation/swiftui/view/toolbaritemhidden(_:))
https://developer.apple.com/documentation/swiftui/view/transactionpicker(ispresented:selection:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/transactiontask(_:action:))
https://developer.apple.com/documentation/swiftui/view/translationpresentation(ispresented:text:attachmentanchor:arrowedge:replacementaction:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/translationtask(_:action:))
https://developer.apple.com/documentation/swiftui/view/translationtask(source:target:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/verifyidentitywithwalletbuttonstyle(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/webviewbackforwardnavigationgestures(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/webviewcontentbackground(_:))
https://developer.apple.com/documentation/swiftui/view/webviewcontextmenu(menu:))
https://developer.apple.com/documentation/swiftui/view/webviewelementfullscreenbehavior(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/webviewlinkpreviews(_:))
https://developer.apple.com/documentation/swiftui/view/webviewmagnificationgestures(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/webviewonscrollgeometrychange(for:of:action:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/webviewscrollinputbehavior(_:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/webviewscrollposition(_:))
https://developer.apple.com/documentation/swiftui/view/webviewtextselection(_:))
https://developer.apple.com/documentation/swiftui/view/windowresizeanchor(_:))
https://developer.apple.com/documentation/swiftui/view/workoutpreview(_:ispresented:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/writingdirection(strategy:))
https://developer.apple.com/documentation/swiftui/view/writingtoolsaffordancevisibility(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/writingtoolsbehavior(_:))
https://developer.apple.com/documentation/swiftui/dynamicviewcontent)
https://developer.apple.com/documentation/swiftui/insettableshape)
https://developer.apple.com/documentation/swiftui/nsviewcontrollerrepresentable)
https://developer.apple.com/documentation/swiftui/nsviewrepresentable)
https://developer.apple.com/documentation/swiftui/shape)
https://developer.apple.com/documentation/swiftui/shapeview)
https://developer.apple.com/documentation/swiftui/uiviewcontrollerrepresentable)
https://developer.apple.com/documentation/swiftui/uiviewrepresentable)
https://developer.apple.com/documentation/swiftui/wkinterfaceobjectrepresentable)
https://developer.apple.com/documentation/swiftui/angulargradient)
https://developer.apple.com/documentation/swiftui/anyshape)
https://developer.apple.com/documentation/swiftui/anyview)
https://developer.apple.com/documentation/swiftui/asyncimage)
https://developer.apple.com/documentation/swiftui/button)
https://developer.apple.com/documentation/swiftui/buttonbordershape)
https://developer.apple.com/documentation/swiftui/buttonstyleconfiguration/label-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/canvas)
https://developer.apple.com/documentation/swiftui/capsule)
https://developer.apple.com/documentation/swiftui/circle)
https://developer.apple.com/documentation/swiftui/color)
https://developer.apple.com/documentation/swiftui/colorpicker)
https://developer.apple.com/documentation/swiftui/containerrelativeshape)
https://developer.apple.com/documentation/swiftui/contentunavailableview)
https://developer.apple.com/documentation/swiftui/controlgroup)
https://developer.apple.com/documentation/swiftui/controlgroupstyleconfiguration/content-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/controlgroupstyleconfiguration/label-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/datepicker)
https://developer.apple.com/documentation/swiftui/datepickerstyleconfiguration/label-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/debugreplaceableview)
https://developer.apple.com/documentation/swiftui/defaultbuttonlabel)
https://developer.apple.com/documentation/swiftui/defaultdateprogresslabel)
https://developer.apple.com/documentation/swiftui/defaultsettingslinklabel)
https://developer.apple.com/documentation/swiftui/defaultsharelinklabel)
https://developer.apple.com/documentation/swiftui/defaulttablabel)
https://developer.apple.com/documentation/swiftui/defaultwindowvisibilitytogglelabel)
https://developer.apple.com/documentation/swiftui/disclosuregroup)
https://developer.apple.com/documentation/swiftui/disclosuregroupstyleconfiguration/content-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/disclosuregroupstyleconfiguration/label-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/divider)
https://developer.apple.com/documentation/swiftui/editbutton)
https://developer.apple.com/documentation/swiftui/editablecollectioncontent)
https://developer.apple.com/documentation/swiftui/ellipse)
https://developer.apple.com/documentation/swiftui/ellipticalgradient)
https://developer.apple.com/documentation/swiftui/emptyview)
https://developer.apple.com/documentation/swiftui/equatableview)
https://developer.apple.com/documentation/swiftui/fillshapeview)
https://developer.apple.com/documentation/swiftui/foreach)
https://developer.apple.com/documentation/swiftui/form)
https://developer.apple.com/documentation/swiftui/formstyleconfiguration/content-swift.struct)
https://developer.apple.com/documentation/swiftui/gauge)
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/currentvaluelabel-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/label-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/markedvaluelabel)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/maximumvaluelabel-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/gaugestyleconfiguration/minimumvaluelabel-swift.struct)
https://developer.apple.com/documentation/swiftui/geometryreader)
https://developer.apple.com/documentation/swiftui/geometryreader3d)
https://developer.apple.com/documentation/swiftui/glassbackgroundeffectconfiguration/content-swift.struct)
https://developer.apple.com/documentation/swiftui/glasseffectcontainer)
https://developer.apple.com/documentation/swiftui/grid)
https://developer.apple.com/documentation/swiftui/gridrow)
https://developer.apple.com/documentation/swiftui/group)
https://developer.apple.com/documentation/swiftui/groupbox)
https://developer.apple.com/documentation/swiftui/groupboxstyleconfiguration/content-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/groupboxstyleconfiguration/label-swift.struct)
https://developer.apple.com/documentation/swiftui/groupelementsofcontent)
https://developer.apple.com/documentation/swiftui/groupsectionsofcontent)
https://developer.apple.com/documentation/swiftui/hstack)
https://developer.apple.com/documentation/swiftui/helplink)
https://developer.apple.com/documentation/swiftui/keyframeanimator)
https://developer.apple.com/documentation/swiftui/label)
https://developer.apple.com/documentation/swiftui/labelstyleconfiguration/icon-swift.struct)
https://developer.apple.com/documentation/swiftui/labelstyleconfiguration/title-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/labeledcontent)
https://developer.apple.com/documentation/swiftui/labeledcontentstyleconfiguration/content-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/labeledcontentstyleconfiguration/label-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/labeledcontrolgroupcontent)
https://developer.apple.com/documentation/swiftui/labeledtoolbaritemgroupcontent)
https://developer.apple.com/documentation/swiftui/lazyhgrid)
https://developer.apple.com/documentation/swiftui/lazyhstack)
https://developer.apple.com/documentation/swiftui/lazyvgrid)
https://developer.apple.com/documentation/swiftui/lazyvstack)
https://developer.apple.com/documentation/swiftui/lineargradient)
https://developer.apple.com/documentation/swiftui/link)
https://developer.apple.com/documentation/swiftui/list)
https://developer.apple.com/documentation/swiftui/menu)
https://developer.apple.com/documentation/swiftui/menubutton)
https://developer.apple.com/documentation/swiftui/menustyleconfiguration/content)
https://developer.apple.com/documentation/swiftui/menustyleconfiguration/label)
https://developer.apple.com/documentation/swiftui/meshgradient)
https://developer.apple.com/documentation/swiftui/modifiedcontent)
https://developer.apple.com/documentation/swiftui/multidatepicker)
https://developer.apple.com/documentation/swiftui/offsetshape)
https://developer.apple.com/documentation/swiftui/outlinegroup)
https://developer.apple.com/documentation/swiftui/outlinesubgroupchildren)
https://developer.apple.com/documentation/swiftui/pastebutton)
https://developer.apple.com/documentation/swiftui/path)
https://developer.apple.com/documentation/swiftui/phaseanimator)
https://developer.apple.com/documentation/swiftui/picker)
https://developer.apple.com/documentation/swiftui/placeholdercontentview)
https://developer.apple.com/documentation/swiftui/presentedwindowcontent)
https://developer.apple.com/documentation/swiftui/previewmodifiercontent)
https://developer.apple.com/documentation/swiftui/primitivebuttonstyleconfiguration/label-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/progressview)
https://developer.apple.com/documentation/swiftui/progressviewstyleconfiguration/currentvaluelabel-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/progressviewstyleconfiguration/label-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/radialgradient)
https://developer.apple.com/documentation/swiftui/rectangle)
https://developer.apple.com/documentation/swiftui/rotatedshape)
https://developer.apple.com/documentation/swiftui/roundedrectangle)
https://developer.apple.com/documentation/swiftui/scaledshape)
https://developer.apple.com/documentation/swiftui/scrollview)
https://developer.apple.com/documentation/swiftui/scrollviewreader)
https://developer.apple.com/documentation/swiftui/searchunavailablecontent/actions)
https://developer.apple.com/documentation/swiftui/searchunavailablecontent/description)
https://developer.apple.com/documentation/swiftui/searchunavailablecontent/label)
https://developer.apple.com/documentation/swiftui/section)
https://developer.apple.com/documentation/swiftui/sectionconfiguration/actions-swift.struct)
https://developer.apple.com/documentation/swiftui/securefield)
https://developer.apple.com/documentation/swiftui/sharelink)
https://developer.apple.com/documentation/swiftui/slider)
https://developer.apple.com/documentation/swiftui/spacer)
https://developer.apple.com/documentation/swiftui/stepper)
https://developer.apple.com/documentation/swiftui/strokebordershapeview)
https://developer.apple.com/documentation/swiftui/strokeshapeview)
https://developer.apple.com/documentation/swiftui/subscriptionview)
https://developer.apple.com/documentation/swiftui/subview)
https://developer.apple.com/documentation/swiftui/subviewscollection)
https://developer.apple.com/documentation/swiftui/subviewscollectionslice)
https://developer.apple.com/documentation/swiftui/tabcontentbuilder/content)
https://developer.apple.com/documentation/swiftui/table)
https://developer.apple.com/documentation/swiftui/texteditor)
https://developer.apple.com/documentation/swiftui/textfield)
https://developer.apple.com/documentation/swiftui/textfieldlink)
https://developer.apple.com/documentation/swiftui/timelineview)
https://developer.apple.com/documentation/swiftui/toggle)
https://developer.apple.com/documentation/swiftui/togglestyleconfiguration/label-swift.struct)
https://developer.apple.com/documentation/swiftui/transformedshape)
https://developer.apple.com/documentation/swiftui/tupleview)
https://developer.apple.com/documentation/swiftui/unevenroundedrectangle)
https://developer.apple.com/documentation/swiftui/vstack)
https://developer.apple.com/documentation/swiftui/viewthatfits)
https://developer.apple.com/documentation/swiftui/zstack)
https://developer.apple.com/documentation/swiftui/zstackcontent3d)
https://developer.apple.com/documentation/swiftui/viewbuilder)
https://developer.apple.com/documentation/swiftui/adding-a-search-interface-to-your-app
- SwiftUI
- Search
- Adding a search interface to your app
Article
Adding a search interface to your app
Present an interface that people can use to search for content in your app.
Overview
Add a search interface to your app by applying one of the searchable view modifiers — like searchable(text:placement:prompt:) — to a NavigationSplitView or NavigationStack, or to a view inside one of these. A search field then appears in the toolbar. The precise placement and appearance of the search field depends on the platform, where you put the modifier in code, and its configuration.
The searchable modifier that creates the field takes a Binding to a string that represents the search field’s text. You provide the storage for the string — and optionally for an array of discrete search tokens — that you use to conduct the search. To learn about managing the search field’s data, see Performing a search operation.
Place the search field automatically
You can automatically place the search field by adding the searchable(text:placement:prompt:) modifier to a navigation element like a navigation split view:
struct ContentView: View { @State private var departmentId: Department.ID? @State private var productId: Product.ID? @State private var searchText: String = ""
var body: some View { NavigationSplitView { DepartmentList(departmentId: $departmentId) } content: { ProductList(departmentId: departmentId, productId: $productId) } detail: { ProductDetails(productId: productId) } .searchable(text: $searchText) // Adds a search field. } }
With this configuration, the search field appears on the trailing edge of the toolbar in macOS. In iOS and iPadOS, the first or second column displays the search field in a double or triple column navigation view, respectively. The above three-column example puts the search field at the top of the middle column on iPad.
Control the placement structurally
To add a search field to a specific column in iOS and iPadOS, add the searchable modifier to a view in that column. For example, to indicate that the search covers departments in the previous example, you could place the search field in the first column by adding the modifier to that column’s DepartmentList view instead of to the navigation split view:
NavigationSplitView { DepartmentList(departmentId: $departmentId) .searchable(text: $searchText) } content: { ProductList(departmentId: departmentId, productId: $productId) } detail: { ProductDetails(productId: productId) }
Control the placement programmatically
You can alternatively use the placement input parameter to suggest a SearchFieldPlacement value for the search interface. For example, you can achieve the same results as the previous example in macOS using the sidebar placement:
NavigationSplitView { DepartmentList(departmentId: $departmentId) } content: { ProductList(departmentId: departmentId, productId: $productId) } detail: { ProductDetails(productId: productId) } .searchable(text: $searchText, placement: .sidebar)
If SwiftUI can’t satisfy the placement request, like when you ask for sidebar placement in a searchable modifier that isn’t applied to a navigation split view, SwiftUI relies instead on its automatic placement rules.
Set a prompt for the search field
By default, the search field contains Search as the placeholder text, to prompt people on how to use the field. You can customize the prompt by setting either a string, a Text view, or a LocalizedStringKey for the searchable modifier’s prompt input parameter. For example, you might use this to clarify that the search field in the Department column searches among both departments and the products in each department:
DepartmentList(departmentId: $departmentId) .searchable(text: $searchText, prompt: "Departments and products")
See Also
Searching your app’s data model
Performing a search operation
Update search results based on search text and optional tokens that you store.
func searchable(text:placement:prompt:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:placement:prompt:token:)
Marks this view as searchable with text and tokens.
func searchable(text:editableTokens:placement:prompt:token:)
struct SearchFieldPlacement
The placement of a search field in a view hierarchy.
https://developer.apple.com/documentation/swiftui/performing-a-search-operation
- SwiftUI
- Search
- Performing a search operation
Article
Performing a search operation
Update search results based on search text and optional tokens that you store.
Overview
To conduct a search in your app’s data model, create storage for the query text and present it with a searchable view modifier. Because you manage the storage, you can detect when it changes and update the search operation in response. By updating search results as people type, you ensure that your app’s search interface is responsive.
You can also optionally provide storage for tokens, which are discrete search terms that your app recognizes. Tokens provide a way to combine multiple search terms, and make it easier for you to indicate that a search term is common or expected in your app.
For information on how to control the placement of the search field in your app’s interface, see Adding a search interface to your app.
Provide storage for a string
The searchable modifiers take a Binding to a string value for the text input. The string serves as the storage for the search query field that SwiftUI displays. You can create this storage inside a view using a State property, and initialize it to an empty string:
@State private var searchText: String = ""
To make it easier to share the search query among different views, you can create a published value inside an observable object that’s part of your app’s model:
class Model: ObservableObject { @Published var searchText: String = "" }
In either case, pass a Binding to this string into the searchable view modifier by adding the dollar sign ( $) prefix to the value:
struct ContentView: View { @EnvironmentObject private var model: Model @State private var departmentId: Department.ID? @State private var productId: Product.ID?
var body: some View { NavigationSplitView { DepartmentList(departmentId: $departmentId) } content: { ProductList(departmentId: departmentId, productId: $productId) .searchable(text: $model.searchText) } detail: { ProductDetails(productId: productId) } } }
Provide storage for tokens
In addition to a search string, the search field can also display tokens when you use one of the searchable modifiers that has a tokens parameter, like searchable(text:tokens:placement:prompt:token:).
You create tokens by defining a group of values that conform to the Identifiable protocol, then instantiate the collection of values. For example you can create an enumeration of fruit tokens:
enum FruitToken: String, Identifiable, Hashable, CaseIterable { case apple case pear case banana var id: Self { self } }
Then add a new published property to your model to store a collection of tokens:
@Published var tokens: [FruitToken] = []
To display tokens, provide a Binding to the tokens array as the searchable modifier’s tokens input parameter, and describe how to draw each token using the token closure. From the closure, return the View that represents the token given as an input. For example, you can use a Text view to represent each token:
ProductList(departmentId: departmentId, productId: $productId) .searchable(text: $model.searchText, tokens: $model.tokens) { token in switch token { case .apple: Text("Apple") case .pear: Text("Pear") case .banana: Text("Banana") } }
You can represent the token with a Text view, as the above example demonstrates. In iOS and iPadOS, you can use a Label instead. Ensure the view clearly represents the corresponding search query, and if you use a label, that the tokens fit the search query field’s height. Tokens appear at the beginning of the search field before any plain text. The following shows how the search field looks when the tokens array contains the apple and banana tokens:
Support tokens that have a mutable component
You can enable people to mutate part of the data that represents a token by using a Picker in the token closure. For example, suppose you have fruit token data that contains both a kind and a hydration property:
struct FruitToken: String, Identifiable, Hashable, CaseIterable { enum Kind { case apple case pear case banana var id: Self { self } }
enum Hydration: String, Identifiable, Hashable, CaseIterable { case hydrated case dehydrated }
var kind: Kind var hydration: Hydration = .hydrated }
With your new model, specify a Binding to the token in the token closure by adding a dollar sign ( $). Use the binding to create a picker for the hydration property and a label that uses the kind property:
ProductList(departmentId: departmentId, productId: $productId) .searchable(text: $model.searchText, tokens: $model.tokens) { $token in Picker(selection: $token.hydration) { ForEach(FruitToken.Hydration.allCases) { hydration in switch hydration { case .hydrated: Text("Hydrated") case .dehydrated: Text("Dehydrated") } } } label: { switch token.kind { case .apple: Text("Apple") case .pear: Text("Pear") case .banana: Text("Banana") } } }
Add tokens to the search
Provide a way for people to add tokens to the search field. You can do this in different ways. For example, you can:
-
Suggest tokens to add to the array by using one of the searchable view modifiers that have a
suggestedTokensinput parameter, likesearchable(text:tokens:suggestedTokens:placement:prompt:token:). People select suggestions from a list that appears below the search field. For more information about offering suggestions for tokens, as well as for search text, see Suggesting search terms. -
Monitor the search string as people edit it. When you detect a substring that matches one of the tokens, convert the text into a token by removing the relevant characters from the string and add the corresponding token to the
tokensarray. -
Wait until you see a dividing character in the search string, like a comma or a space, and then attempt to tokenize the preceding characters.
-
Wait until someone submits the search, and then attempt to tokenize the entire search string. For more information about submitting a search, see Managing search interface activation.
Conduct the search
When you detect changes in the search query, your app can begin a search. How you perform the search operation depends on how your app stores and presents data. One approach is to filter the elements that appear in a List based on whether a field in the list’s items matches the search query. For example, you can create a method that returns only the items in an array of products with names that match the search text or one of the tokens currently in the search field:
func filteredProducts( products: [Product], searchText: String, tokens: [FruitToken]
guard !searchText.isEmpty || !tokens.isEmpty else { return products } return products.filter { product in product.name.lowercased().contains(searchText.lowercased()) || tokens.map({ $0.rawValue }).contains(product.name.lowercased()) } }
Consider the complexity of the search and the cost of changing the search terms. If the cost is high, like when updates require network access, or for complex filter logic, consider prefetching and caching data or reducing the frequency of updates. Alternatively, you can wait until someone submits the query before conducting the search. For information about detecting query submission, see Managing search interface activation.
If the search space can be broken into broad categories, you can help people narrow the search more quickly by providing a scope. See Scoping a search operation.
See Also
Searching your app’s data model
Adding a search interface to your app
Present an interface that people can use to search for content in your app.
func searchable(text:placement:prompt:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:placement:prompt:token:)
Marks this view as searchable with text and tokens.
func searchable(text:editableTokens:placement:prompt:token:)
struct SearchFieldPlacement
The placement of a search field in a view hierarchy.
https://developer.apple.com/documentation/swiftui/view/searchable(text:placement:prompt:)
#app-main)
- SwiftUI
- View
- searchable(text:placement:prompt:)
Instance Method
searchable(text:placement:prompt:)
Marks this view as searchable, which configures the display of a search field.
nonisolated func searchable(
placement: SearchFieldPlacement = .automatic, prompt: LocalizedStringKey
Show all declarations
Parameters
text
The text to display and edit in the search field.
placement
The preferred placement of the search field within the containing view hierarchy.
prompt
The key for the localized prompt of the search field which provides users with guidance on what to search for.
Mentioned in
Adding a search interface to your app
Managing search interface activation
Suggesting search terms
Discussion
For more information about using searchable modifiers, see Adding a search interface to your app.
See Also
Searching your app’s data model
Present an interface that people can use to search for content in your app.
Performing a search operation
Update search results based on search text and optional tokens that you store.
func searchable(text:tokens:placement:prompt:token:)
Marks this view as searchable with text and tokens.
func searchable(text:editableTokens:placement:prompt:token:)
struct SearchFieldPlacement
The placement of a search field in a view hierarchy.
https://developer.apple.com/documentation/swiftui/view/searchable(text:tokens:placement:prompt:token:)
#app-main)
- SwiftUI
- View
- searchable(text:tokens:placement:prompt:token:)
Instance Method
searchable(text:tokens:placement:prompt:token:)
Marks this view as searchable with text and tokens.
nonisolated
placement: SearchFieldPlacement = .automatic, prompt: S,
Show all declarations
Parameters
text
The text to display and edit in the search field.
tokens
A collection of tokens to display and edit in the search field.
placement
The preferred placement of the search field within the containing view hierarchy.
prompt
A string representing the prompt of the search field which provides users with guidance on what to search for.
token
A view builder that creates a view given an element in tokens.
Mentioned in
Performing a search operation
Discussion
For more information about using searchable modifiers, see Adding a search interface to your app.
See Also
Searching your app’s data model
Adding a search interface to your app
Present an interface that people can use to search for content in your app.
Update search results based on search text and optional tokens that you store.
func searchable(text:placement:prompt:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:editableTokens:placement:prompt:token:)
struct SearchFieldPlacement
The placement of a search field in a view hierarchy.
https://developer.apple.com/documentation/swiftui/view/searchable(text:editabletokens:placement:prompt:token:)
#app-main)
- SwiftUI
- View
- searchable(text:editableTokens:placement:prompt:token:)
Instance Method
searchable(text:editableTokens:placement:prompt:token:)
Marks this view as searchable, which configures the display of a search field.
nonisolated
placement: SearchFieldPlacement = .automatic, prompt: LocalizedStringKey,
Show all declarations
Parameters
text
The text to display and edit in the search field.
editableTokens
A collection of tokens to display and edit in the search field.
placement
The preferred placement of the search field within the containing view hierarchy.
prompt
The key for the localized prompt of the search field which provides users with guidance on what to search for.
token
A view builder that creates a view given an element in tokens.
Discussion
For more information about using searchable modifiers, see Adding a search interface to your app.
See Also
Searching your app’s data model
Adding a search interface to your app
Present an interface that people can use to search for content in your app.
Performing a search operation
Update search results based on search text and optional tokens that you store.
func searchable(text:placement:prompt:)
func searchable(text:tokens:placement:prompt:token:)
Marks this view as searchable with text and tokens.
struct SearchFieldPlacement
The placement of a search field in a view hierarchy.
https://developer.apple.com/documentation/swiftui/searchfieldplacement
- SwiftUI
- SearchFieldPlacement
Structure
SearchFieldPlacement
The placement of a search field in a view hierarchy.
struct SearchFieldPlacement
Mentioned in
Adding a search interface to your app
Overview
You can give a preferred placement to any of the searchable modifiers, like searchable(text:placement:prompt:):
var body: some View { NavigationView { PrimaryView() SecondaryView() Text("Select a primary and secondary item") } .searchable(text: $text, placement: .sidebar) }
Depending on the containing view hierachy, SwiftUI might not be able to fulfill your request.
Topics
Getting a search field placement
static let automatic: SearchFieldPlacement
SwiftUI places the search field automatically.
static let navigationBarDrawer: SearchFieldPlacement
The search field appears in the navigation bar.
The search field appears in the navigation bar using the specified display mode.
static var sidebar: SearchFieldPlacement
The search field appears in the sidebar of a navigation view.
static let toolbar: SearchFieldPlacement
The search field appears in the toolbar.
Supporting types
struct NavigationBarDrawerDisplayMode
A mode that determines when to display a search field that appears in a navigation bar.
Type Properties
static var toolbarPrincipal: SearchFieldPlacement
The search field appears in the principal section of the toolbar.
Relationships
Conforms To
SendableSendableMetatype
See Also
Searching your app’s data model
Present an interface that people can use to search for content in your app.
Performing a search operation
Update search results based on search text and optional tokens that you store.
func searchable(text:placement:prompt:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:placement:prompt:token:)
Marks this view as searchable with text and tokens.
func searchable(text:editableTokens:placement:prompt:token:)
https://developer.apple.com/documentation/swiftui/suggesting-search-terms
- SwiftUI
- Search
- Suggesting search terms
Article
Suggesting search terms
Provide suggestions to people searching for content in your app.
Overview
You can suggest query text during a search operation by providing a collection of search suggestion views. Because suggestion views are not limited to plain text, you must also provide the search string that each suggestion view represents. You can also provide suggestions for tokens, if your search interface includes them. SwiftUI presents the suggestions in a list below the search field.
For both text and tokens, you manage the list of suggestions, so you have complete flexibility to decide what to suggest. For example, you can:
-
Offer a static list of suggestions.
-
Remember previous searches and offer the most recent or most common ones.
-
Update the list of suggestions in real time based on the current search text.
-
Employ some combination of these and other strategies, possibly changing over time.
Suggest search text
Suggest search text by providing a collection of views to the searchSuggestions(_:) view modifier. This modifier applies to the searchable(text:placement:prompt:) modifier that appears before it.
When someone activates the search interface, it presents the suggestion views as a list of choices below the query string. Associate a string with each suggestion view by adding the searchCompletion(_:) modifier to the view inside the search suggestions closure. For example, you can include emoji with fruit types that you suggest as possible products to search for, and provide the corresponding search string as a search completion in each case:
ProductList(departmentId: departmentId, productId: $productId) .searchable(text: $model.searchText) .searchSuggestions { Text("🍎 Apple").searchCompletion("apple") Text("🍐 Pear").searchCompletion("pear") Text("🍌 Banana").searchCompletion("banana") }
When someone chooses a suggestion, SwiftUI replaces the text in the search field with the search completion string. In the above example, choosing “🍐 Pear” puts the text “pear” in the search query.
If you omit the search completion modifier for a particular suggestion view, SwiftUI displays the view, but the view doesn’t react to taps or clicks. However, you can group the views with Section containers that have headers, enabling you to distinguish different kinds of suggestions, like recent searches and common search terms.
Certain events or actions, like when someone moves a macOS window, might dismiss the suggestion list.
Suggest tokens
You can also suggest tokens for the search field. In this case, associate a suggestion view with a token using the version of the searchCompletion(_:) modifier that takes tokens as input:
ProductList(departmentId: departmentId, productId: $productId) .searchable(text: $model.searchText, tokens: $model.tokens) { token in switch token { case .apple: Text("Apple") case .pear: Text("Pear") case .banana: Text("Banana") } } .searchSuggestions { Text("Apple").searchCompletion(FruitToken.apple) Text("Pear").searchCompletion(FruitToken.pear) Text("Banana").searchCompletion(FruitToken.banana) }
You can use any type that conforms to the Identifiable protocol as a token. For more information about using tokens in the search query, see Performing a search operation.
Simplify token suggestions
As a convenience when you have a collection of suggestions that exactly matches the list of tokens, you can create a collection of possible tokens to suggest. For example, you can add a published suggestions property to your model that contains all the possible tokens:
@Published var suggestions: [FruitToken] = FruitToken.allCases
Then you can provide this array to one of the searchable modifiers that takes a suggestedTokens input parameter, like searchable(text:tokens:suggestedTokens:placement:prompt:token:). SwiftUI uses this to generate the suggestions automatically:
ProductList(departmentId: departmentId, productId: $productId) .searchable( text: $model.searchText, tokens: $model.tokens, suggestedTokens: $model.suggestions ) { token in switch token { case .apple: Text("Apple") case .pear: Text("Pear") case .banana: Text("Banana") } }
In this version of the searchable modifier, SwiftUI uses one view builder to describe the appearance of the tokens in both the search field and the suggestions container.
Update suggestions dynamically
You can update the suggestions that you provide as conditions change. For example, you can specify an array of suggestedSearches that you store in your app’s model:
ProductList(departmentId: departmentId, productId: $productId) .searchable(text: $model.searchText) .searchSuggestions { ForEach(model.suggestedSearches) { suggestion in Label(suggestion.title, image: suggestion.image) .searchCompletion(suggestion.text) } }
If suggestedSearches begins as an empty array, the interface doesn’t display any suggestions to start. You can then update the array as conditions change, like when you want to include previous searches.
See Also
Making search suggestions
Configures the search suggestions for this view.
Configures how to display search suggestions within this view.
func searchCompletion(_:)
Associates a fully formed string with the value of this view when used as a search suggestion.
func searchable(text:tokens:suggestedTokens:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions.
struct SearchSuggestionsPlacement
The ways that SwiftUI displays search suggestions.
https://developer.apple.com/documentation/swiftui/view/searchsuggestions(_:)
#app-main)
- SwiftUI
- View
- searchSuggestions(_:)
Instance Method
searchSuggestions(_:)
Configures the search suggestions for this view.
nonisolated
Parameters
suggestions
A view builder that produces content that populates a list of suggestions.
Mentioned in
Suggesting search terms
Scoping a search operation
Discussion
You can suggest search terms during a search operation by providing a collection of view to this modifier. The interface presents the suggestion views as a list of choices when someone activates the search interface. Associate a string with each suggestion view by adding the searchCompletion(_:) modifier to the view. For example, you can suggest fruit types by displaying their emoji, and provide the corresponding search string as a search completion in each case:
ProductList() .searchable(text: $text) .searchSuggestions { Text("🍎").searchCompletion("apple") Text("🍐").searchCompletion("pear") Text("🍌").searchCompletion("banana") }
When someone chooses a suggestion, SwiftUI replaces the text in the search field with the search completion string. If you omit the search completion modifier for a particular suggestion view, SwiftUI displays the suggestion, but the suggestion view doesn’t react to taps or clicks.
You can update the suggestions that you provide as conditions change.
For example, you can specify an array of suggestions that you store in a model:
ProductList() .searchable(text: $text) .searchSuggestions { ForEach(model.suggestedSearches) { suggestion in Label(suggestion.title, image: suggestion.image) .searchCompletion(suggestion.text) } }
If the model’s suggestedSearches begins as an empty array, the interface doesn’t display any suggestions to start. You can then provide logic that updates the array based on some condition. For example, you might update the completions based on the current search text. Note that certain events or actions, like when someone moves a macOS window, might dismiss the suggestion view.
For more information about using search modifiers, see Adding a search interface to your app.
See Also
Making search suggestions
Provide suggestions to people searching for content in your app.
Configures how to display search suggestions within this view.
func searchCompletion(_:)
Associates a fully formed string with the value of this view when used as a search suggestion.
func searchable(text:tokens:suggestedTokens:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions.
struct SearchSuggestionsPlacement
The ways that SwiftUI displays search suggestions.
https://developer.apple.com/documentation/swiftui/view/searchsuggestions(_:for:)
#app-main)
- SwiftUI
- View
- searchSuggestions(_:for:)
Instance Method
searchSuggestions(_:for:)
Configures how to display search suggestions within this view.
nonisolated func searchSuggestions( _ visibility: Visibility, for placements: SearchSuggestionsPlacement.Set
Parameters
visibility
The visibility of the search suggestions for the specified locations.
placements
The set of locations in which to set the visibility of search suggestions.
Discussion
SwiftUI presents search suggestions differently depending on several factors, like the platform, the position of the search field, and the size class. Use this modifier when you want to only display suggestions in certain ways under certain conditions. For example, you might choose to display suggestions in a menu when possible, but directly filter your data source otherwise.
enum FruitSuggestion: String, Identifiable { case apple, banana, orange var id: Self { self } }
@State private var text = "" @State private var suggestions: [FruitSuggestion] = []
var body: some View { MainContent() .searchable(text: $text) { ForEach(suggestions) { suggestion Text(suggestion.rawValue) .searchCompletion(suggestion.rawValue) } .searchSuggestions(.hidden, for: .content) } }
See Also
Making search suggestions
Suggesting search terms
Provide suggestions to people searching for content in your app.
Configures the search suggestions for this view.
func searchCompletion(_:)
Associates a fully formed string with the value of this view when used as a search suggestion.
func searchable(text:tokens:suggestedTokens:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions.
struct SearchSuggestionsPlacement
The ways that SwiftUI displays search suggestions.
https://developer.apple.com/documentation/swiftui/view/searchcompletion(_:)
#app-main)
- SwiftUI
- View
- searchCompletion(_:)
Instance Method
searchCompletion(_:)
Associates a fully formed string with the value of this view when used as a search suggestion.
nonisolated
Show all declarations
Mentioned in
Suggesting search terms
Discussion
Use this method to associate a fully formed string with a view that is within a search suggestion list context. The system uses this value when the view is selected to replace the partial text being currently edited of the associated search field.
On tvOS, the string that you provide to the this modifier is used when displaying the associated suggestion and when replacing the partial text of the search field.
SearchPlaceholderView() .searchable(text: $text) { Text("🍎").searchCompletion("apple") Text("🍐").searchCompletion("pear") Text("🍌").searchCompletion("banana") }
See Also
Making search suggestions
Provide suggestions to people searching for content in your app.
Configures the search suggestions for this view.
Configures how to display search suggestions within this view.
func searchable(text:tokens:suggestedTokens:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions.
struct SearchSuggestionsPlacement
The ways that SwiftUI displays search suggestions.
https://developer.apple.com/documentation/swiftui/view/searchable(text:tokens:suggestedtokens:placement:prompt:token:)
#app-main)
- SwiftUI
- View
- searchable(text:tokens:suggestedTokens:placement:prompt:token:)
Instance Method
searchable(text:tokens:suggestedTokens:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions.
nonisolated
placement: SearchFieldPlacement = .automatic, prompt: S,
Show all declarations
Parameters
text
The text to display and edit in the search field.
tokens
A collection of tokens to display and edit in the search field.
suggestedTokens
A collection of tokens to display as suggestions.
placement
The preferred placement of the search field within the containing view hierarchy.
prompt
A string representing the prompt of the search field which provides users with guidance on what to search for.
token
A view builder that creates a view given an element in tokens.
Mentioned in
Suggesting search terms
Performing a search operation
Discussion
For more information about using searchable modifiers, see Adding a search interface to your app.
See Also
Making search suggestions
Provide suggestions to people searching for content in your app.
Configures the search suggestions for this view.
Configures how to display search suggestions within this view.
func searchCompletion(_:)
Associates a fully formed string with the value of this view when used as a search suggestion.
struct SearchSuggestionsPlacement
The ways that SwiftUI displays search suggestions.
https://developer.apple.com/documentation/swiftui/searchsuggestionsplacement
- SwiftUI
- SearchSuggestionsPlacement
Structure
SearchSuggestionsPlacement
The ways that SwiftUI displays search suggestions.
struct SearchSuggestionsPlacement
Overview
You can influence which modes SwiftUI displays search suggestions for by using the searchSuggestions(_:for:) modifier:
enum FruitSuggestion: String, Identifiable { case apple, banana, orange var id: Self { self } }
@State private var text = "" @State private var suggestions: [FruitSuggestion] = []
var body: some View { MainContent() .searchable(text: $text) { ForEach(suggestions) { suggestion in Text(suggestion.rawValue) .searchCompletion(suggestion.rawValue) } .searchSuggestions(.hidden, for: .content) } }
In the above example, SwiftUI only displays search suggestions in a suggestions menu. You might want to do this when you want to render search suggestions in a container, like inline with your own set of search results.
You can get the current search suggestion placement by querying the searchSuggestionsPlacement environment value in your search suggestions.
Topics
Getting placements
static var automatic: SearchSuggestionsPlacement
Search suggestions render automatically based on the surrounding context.
static var content: SearchSuggestionsPlacement
Search suggestions render in the main content of the app.
static var menu: SearchSuggestionsPlacement
Search suggestions render inside of a menu attached to the search field.
Supporting types
struct Set
An efficient set of search suggestion display modes.
Relationships
Conforms To
EquatableSendableSendableMetatype
See Also
Making search suggestions
Suggesting search terms
Provide suggestions to people searching for content in your app.
Configures the search suggestions for this view.
Configures how to display search suggestions within this view.
func searchCompletion(_:)
Associates a fully formed string with the value of this view when used as a search suggestion.
func searchable(text:tokens:suggestedTokens:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions.
https://developer.apple.com/documentation/swiftui/scoping-a-search-operation
- SwiftUI
- Search
- Scoping a search operation
Article
Scoping a search operation
Divide the search space into a few broad categories.
Overview
If the data you want to search falls into a few categories, you can define different scopes to help people narrow their search. When you define a scope, SwiftUI presents a picker that people can use to choose one of them. You then use the current scope selection as one of the inputs to the search operation.
Define the possible scopes
Start by creating a type that conforms to the Hashable protocol to represent the possible scopes. For example, you can use an enumeration to scope a product search to just fruits or just vegetables:
enum ProductScope { case fruit case vegetable }
Then create a property to store the current scope, either as a state variable in a view, or a published property in your model:
@Published var scope: ProductScope = .fruit
Apply the scope
To use the scope information, bind the current scope to the searchScopes(_:scopes:) modifier. You also indicate a set of views that correspond to the different scopes. Like the searchSuggestions(_:) modifier, the scopes modifier operates on the searchable modifier that’s closer to the modified view, so it needs to follow the searchable modifier:
ProductList(departmentId: departmentId, productId: $productId) .searchable(text: $model.searchText, tokens: $model.tokens) { token in switch token { case .apple: Text("Apple") case .pear: Text("Pear") case .banana: Text("Banana") } } .searchScopes($model.scope) { Text("Fruit").tag(ProductScope.fruit) Text("Vegetable").tag(ProductScope.vegetable) }
SwiftUI uses the binding and views to add a Picker to the search field. By default, the picker appears below the search field in macOS when search is active, or in iOS when someone starts entering text into the search field:
You can change when the picker appears by using the searchScopes(_:activation:_:) modifier instead, and supplying one of the SearchScopeActivation values, like onTextEntry or onSearchPresentation.
To ensure that the picker operates correctly, match the type of the scope binding with the type of each view’s tag. In the above example, both the scope input and the tags for each view have the type ProductScope.
Use the scope in your search
Modify your search to account for the current value of the scope property, if you offer it, along with the text and tokens in the query. For example, you might include the scope as one element of a predicate that you define for a Core Data fetch request. For more information about conducting a search, see Performing a search operation.
See Also
Limiting search scope
Configures the search scopes for this view.
Configures the search scopes for this view with the specified activation strategy.
struct SearchScopeActivation
The ways that searchable modifiers can show or hide search scopes.
https://developer.apple.com/documentation/swiftui/view/searchscopes(_:scopes:)
#app-main)
- SwiftUI
- View
- searchScopes(_:scopes:)
Instance Method
searchScopes(_:scopes:)
Configures the search scopes for this view.
nonisolated
Parameters
scope
The active scope of the search field.
scopes
A view builder that represents the scoping options SwiftUI uses to populate a Picker.
Mentioned in
Scoping a search operation
Discussion
To enable people to narrow the scope of their searches, you can create a type that represents the possible scopes, and then create a state variable to hold the current selection. For example, you can scope the product search to just fruits or just vegetables:
enum ProductScope { case fruit case vegetable }
@State private var scope: ProductScope = .fruit
Provide a binding to the scope, as well as a view that represents each scope:
ProductList() .searchable(text: $text, tokens: $tokens) { token in switch token { case .apple: Text("Apple") case .pear: Text("Pear") case .banana: Text("Banana") } } .searchScopes($scope) { Text("Fruit").tag(ProductScope.fruit) Text("Vegetable").tag(ProductScope.vegetable) }
SwiftUI uses this binding and view to add a Picker with the search field. In iOS, iPadOS, macOS, and tvOS, the picker appears below the search field when search is active. To ensure that the picker operates correctly, match the type of the scope binding with the type of each view’s tag. Then modify your search to account for the current value of the scope state property.
For more information about using searchable modifiers, see Adding a search interface to your app.
See Also
Limiting search scope
Divide the search space into a few broad categories.
Configures the search scopes for this view with the specified activation strategy.
struct SearchScopeActivation
The ways that searchable modifiers can show or hide search scopes.
https://developer.apple.com/documentation/swiftui/view/searchscopes(:activation::)
#app-main)
- SwiftUI
- View
- searchScopes(_:activation:_:)
Instance Method
searchScopes(_:activation:_:)
Configures the search scopes for this view with the specified activation strategy.
nonisolated
activation: SearchScopeActivation,
Parameters
scope
The active scope of the search field.
activation
The activation style of the search field’s scopes.
scopes
A view builder that represents the scoping options SwiftUI uses to populate a Picker.
Mentioned in
Scoping a search operation
Discussion
To enable people to narrow the scope of their searches, you can create a type that represents the possible scopes, and then create a state variable to hold the current selection. For example, you can scope the product search to just fruits or just vegetables:
enum ProductScope { case fruit case vegetable }
@State private var scope: ProductScope = .fruit
Provide a binding to the scope, as well as a view that represents each scope:
ProductList() .searchable(text: $text, tokens: $tokens) { token in switch token { case .apple: Text("Apple") case .pear: Text("Pear") case .banana: Text("Banana") } } .searchScopes($scope) { Text("Fruit").tag(ProductScope.fruit) Text("Vegetable").tag(ProductScope.vegetable) }
SwiftUI uses this binding and view to add a Picker below the search field. In iOS, macOS, and tvOS, the picker appears below the search field when search is active. To ensure that the picker operates correctly, match the type of the scope binding with the type of each view’s tag. Then condition your search on the current value of the scope state property.
By default, the appearance of scopes varies by platform:
-
In iOS and iPadOS, search scopes appear when someone enters text into the search field and disappear when someone cancels the search.
-
In macOS, search scopes appear when SwiftUI presents search and disappear when someone cancels the search.
However, you can use the activation parameter with a value of onTextEntry or onSearchPresentation to configure this behavior:
.searchScopes($scope, activation: .onSearchPresentation) { Text("Fruit").tag(ProductScope.fruit) Text("Vegetable").tag(ProductScope.vegetable) }
For more information about using searchable modifiers, see Adding a search interface to your app.
See Also
Limiting search scope
Divide the search space into a few broad categories.
Configures the search scopes for this view.
struct SearchScopeActivation
The ways that searchable modifiers can show or hide search scopes.
https://developer.apple.com/documentation/swiftui/searchscopeactivation
- SwiftUI
- SearchScopeActivation
Structure
SearchScopeActivation
The ways that searchable modifiers can show or hide search scopes.
struct SearchScopeActivation
Mentioned in
Scoping a search operation
Topics
Getting search scope activiation types
static var automatic: SearchScopeActivation
The automatic activation of the scope bar.
static var onSearchPresentation: SearchScopeActivation
An activation where the system shows search scopes after presenting search and hides search scopes after search cancellation.
static var onTextEntry: SearchScopeActivation
An activation where the system shows search scopes when typing begins in the search field and hides search scopes after search cancellation.
See Also
Limiting search scope
Divide the search space into a few broad categories.
Configures the search scopes for this view.
Configures the search scopes for this view with the specified activation strategy.
https://developer.apple.com/documentation/swiftui/managing-search-interface-activation
- SwiftUI
- Search
- Managing search interface activation
Article
Managing search interface activation
Programmatically detect and dismiss a search field.
Overview
People activate a search field in your app by tapping or clicking it, after which they can enter search terms. In many cases, your app only needs to react to the corresponding changes in the search text values, which the interface updates through the binding that you provide, as described in Performing a search operation.
However, SwiftUI also provides controls that enable you to programmatically manage the search interface. In particular, you can:
-
Activate or deactivate the interface using a binding that you provide to the searchable modifier.
-
Detect whether the interface is active by reading an environment value.
-
Dismiss the interface by calling an action stored in the environment.
-
Wait for a search submission event before starting to search.
Control activation through a binding
You can control search interface activation programmatically by providing the searchable modifier’s isPresented parameter with a Binding to a Boolean value. For example, to present a sheet that appears with the search interface already active, create a binding that starts as true:
struct SheetView: View { @State private var isPresented = true @State private var text = ""
var body: some View { NavigationStack { SheetContent() .searchable(text: $text, isPresented: $isPresented) } } }
On iOS and macOS, SwiftUI focuses the search field when presenting search and unfocuses the search field when dismissing search. The search field can also lose focus while the search interface remains presented. For example, if your search interface contains a list of text fields, someone might move focus to one of the text fields without dismissing the interface.
Detect search activation
If you need to know when the search interface is active, you can query the environment’s isSearching property using the Environment property wrapper. The following example shows a view that updates the text it displays based on the state of the property:
struct SearchingExample: View { @State private var searchText = ""
var body: some View { NavigationStack { SearchedView() .searchable(text: $searchText) } } }
struct SearchedView: View { @Environment(.isSearching) private var isSearching
var body: some View { Text(isSearching ? "Searching" : "Not searching") } }
When someone first taps or clicks in a search field, the isSearching property becomes true. When they cancel the search operation, the property becomes false. It also becomes false if you programmatically dismiss the interface, as the next section describes.
Be sure to read the property from inside a view that’s wrapped, either directly or indirectly, by one of the searchable(text:placement:prompt:) view modifiers, like SearchedView in the above example. You won’t detect any change in the property value if you read it from outside of that context, like if you put it in the SearchingExample view.
Dismiss the search interface
You can programmatically deactivate the interface using the environment’s dismissSearch action. For example, consider a view with a Button that presents more information about the first matching item from a collection:
struct ContentView: View { @State private var searchText = ""
var body: some View { NavigationStack { SearchedView(searchText: searchText) .searchable(text: $searchText) } } }
private struct SearchedView: View { var searchText: String
let items = ["a", "b", "c"] var filteredItems: [String] { items.filter { $0 == searchText.lowercased() } }
@State private var isPresented = false @Environment(.dismissSearch) private var dismissSearch
var body: some View { if let item = filteredItems.first { Button("Details about (item)") { isPresented = true } .sheet(isPresented: $isPresented) { NavigationStack { DetailView(item: item, dismissSearch: dismissSearch) } } } } }
The button becomes visible only after someone enters search text that produces a match. The button’s action shows a sheet that provides more information about the item, including an Add button for adding the item to a stored list of items:
private struct DetailView: View { var item: String var dismissSearch: DismissSearchAction
@Environment(.dismiss) private var dismiss
var body: some View { Text("Information about (item).") .toolbar { Button("Add") { // Store the item here...
dismiss() dismissSearch() } } } }
People can dismiss the sheet by dragging it down, effectively canceling the operation, leaving the in-progress search interaction intact. Alternatively, They can tap the Add button to store the item. Because people are likely done with both the detail view and the search interaction at this point, the button’s closure uses the dismiss property to dismiss the sheet, and the dismissSearch property to reset the search field.
As with the isSearching property, be sure to only read dismissSearch from within the hierarchy of a searchable view modifier. Calling the action has no effect if you read it from the environment outside of that context. The above example reads the action from SearchedView, and passes that into the sheet, because the sheet has its own environment. The action also has no effect if the search interface isn’t active.
React to search submission
To specify an action that SwiftUI invokes when someone submits the search query (by pressing the Return key), add the onSubmit(of:_:) modifier:
SearchedView() .searchable(text: $searchText) .onSubmit(of: .search) { submitCurrentSearchQuery() }
Depending your app’s structure, you can use search submission in different ways. For example, you can take that opportunity to look for substrings among the search query string that you can convert into tokens. Alternatively, for a search operation that’s very slow, perhaps because it requires a network access, you can wait for a submission event before performing a search.
See Also
Detecting, activating, and dismissing search
var isSearching: Bool
A Boolean value that indicates when the user is searching.
var dismissSearch: DismissSearchAction
An action that ends the current search interaction.
struct DismissSearchAction
An action that can end a search interaction.
func searchable(text:isPresented:placement:prompt:)
Marks this view as searchable with programmatic presentation of the search field.
func searchable(text:tokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text and tokens, as well as programmatic presentation.
func searchable(text:editableTokens:isPresented:placement:prompt:token:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions, as well as programmatic presentation.
https://developer.apple.com/documentation/swiftui/environmentvalues/issearching
- SwiftUI
- EnvironmentValues
- isSearching
Instance Property
isSearching
A Boolean value that indicates when the user is searching.
var isSearching: Bool { get }
Mentioned in
Managing search interface activation
Discussion
You can read this value like any of the other EnvironmentValues, by creating a property with the Environment property wrapper:
@Environment(.isSearching) private var isSearching
Get the value to find out when the user interacts with a search field that’s produced by one of the searchable modifiers, like searchable(text:placement:prompt:):
struct SearchingExample: View { @State private var searchText = ""
var body: some View { NavigationStack { SearchedView() .searchable(text: $searchText) } } }
struct SearchedView: View { @Environment(.isSearching) private var isSearching
var body: some View { Text(isSearching ? "Searching!" : "Not searching.") } }
When the user first taps or clicks in a search field, the isSearching property becomes true. When the user cancels the search operation, the property becomes false. To programmatically set the value to false and dismiss the search operation, use dismissSearch.
See Also
Detecting, activating, and dismissing search
Programmatically detect and dismiss a search field.
var dismissSearch: DismissSearchAction
An action that ends the current search interaction.
struct DismissSearchAction
An action that can end a search interaction.
func searchable(text:isPresented:placement:prompt:)
Marks this view as searchable with programmatic presentation of the search field.
func searchable(text:tokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text and tokens, as well as programmatic presentation.
func searchable(text:editableTokens:isPresented:placement:prompt:token:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions, as well as programmatic presentation.
https://developer.apple.com/documentation/swiftui/environmentvalues/dismisssearch
- SwiftUI
- EnvironmentValues
- dismissSearch
Instance Property
dismissSearch
An action that ends the current search interaction.
var dismissSearch: DismissSearchAction { get }
Mentioned in
Managing search interface activation
Discussion
Use this environment value to get the DismissSearchAction instance for the current Environment. Then call the instance to dismiss the current search interaction. You call the instance directly because it defines a callAsFunction() method that Swift calls when you call the instance.
When you dismiss search, SwiftUI:
-
Sets
isSearchingtofalse. -
Clears any text from the search field.
-
Removes focus from the search field.
Use this action to dismiss a search operation based on another user interaction. For example, consider a searchable view with a Button that presents more information about the first matching item from a collection:
struct ContentView: View { @State private var searchText = ""
var body: some View { NavigationStack { SearchedView(searchText: searchText) .searchable(text: $searchText) } } }
private struct SearchedView: View { let searchText: String
let items = ["a", "b", "c"] var filteredItems: [String] { items.filter { $0 == searchText.lowercased() } }
@State private var isPresented = false @Environment(.dismissSearch) private var dismissSearch
var body: some View { if let item = filteredItems.first { Button("Details about (item)") { isPresented = true } .sheet(isPresented: $isPresented) { NavigationStack { DetailView(item: item, dismissSearch: dismissSearch) } } } } }
The button becomes visible only after the user enters search text that produces a match. When the user taps the button, SwiftUI shows a sheet that provides more information about the item, including an Add button for adding the item to a stored list of items:
private struct DetailView: View { var item: String var dismissSearch: DismissSearchAction
@Environment(.dismiss) private var dismiss
var body: some View { Text("Information about (item).") .toolbar { Button("Add") { // Store the item here...
dismiss() dismissSearch() } } } }
People can dismiss the sheet by dragging it down, effectively canceling the operation, leaving the in-progress search interaction intact. Alternatively, people can tap the Add button to store the item. Because the person using your app is likely to be done with both the detail view and the search interaction at this point, the button’s closure also uses the dismiss property to dismiss the sheet, and the dismissSearch property to reset the search field.
See Also
Detecting, activating, and dismissing search
Programmatically detect and dismiss a search field.
var isSearching: Bool
A Boolean value that indicates when the user is searching.
struct DismissSearchAction
An action that can end a search interaction.
func searchable(text:isPresented:placement:prompt:)
Marks this view as searchable with programmatic presentation of the search field.
func searchable(text:tokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text and tokens, as well as programmatic presentation.
func searchable(text:editableTokens:isPresented:placement:prompt:token:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions, as well as programmatic presentation.
https://developer.apple.com/documentation/swiftui/dismisssearchaction
- SwiftUI
- DismissSearchAction
Structure
DismissSearchAction
An action that can end a search interaction.
@MainActor @preconcurrency struct DismissSearchAction
Overview
Use the dismissSearch environment value to get the instance of this structure for a given Environment. Then call the instance to dismiss the current search interaction. You call the instance directly because it defines a callAsFunction() method that Swift calls when you call the instance.
When you dismiss search, SwiftUI:
-
Sets
isSearchingtofalse. -
Clears any text from the search field.
-
Removes focus from the search field.
Use this action to dismiss a search operation based on another user interaction. For example, consider a searchable view with a Button that presents more information about the first matching item from a collection:
struct ContentView: View { @State private var searchText = ""
var body: some View { NavigationStack { SearchedView(searchText: searchText) .searchable(text: $searchText) } } }
struct SearchedView: View { var searchText: String
let items = ["a", "b", "c"] var filteredItems: [String] { items.filter { $0 == searchText.lowercased() } }
@State private var isPresented = false @Environment(.dismissSearch) private var dismissSearch
var body: some View { if let item = filteredItems.first { Button("Details about (item)") { isPresented = true } .sheet(isPresented: $isPresented) { NavigationStack { DetailView(item: item, dismissSearch: dismissSearch) } } } } }
The button becomes visible only after the user enters search text that produces a match. When the user taps the button, SwiftUI shows a sheet that provides more information about the item, including an Add button for adding the item to a stored list of items:
private struct DetailView: View { var item: String var dismissSearch: DismissSearchAction
@Environment(.dismiss) private var dismiss
var body: some View { Text("Information about (item).") .toolbar { Button("Add") { // Store the item here...
dismiss() dismissSearch() } } } }
People can dismiss the sheet by dragging it down, effectively canceling the operation, leaving the in-progress search interaction intact. Alternatively, people can tap the Add button to store the item. Because the person using your app is likely to be done with both the detail view and the search interaction at this point, the button’s closure also uses the dismiss property to dismiss the sheet, and the dismissSearch property to reset the search field.
Topics
Calling the action
func callAsFunction()
Dismisses the current search operation, if any.
Relationships
Conforms To
SendableSendableMetatype
See Also
Detecting, activating, and dismissing search
Managing search interface activation
Programmatically detect and dismiss a search field.
var isSearching: Bool
A Boolean value that indicates when the user is searching.
var dismissSearch: DismissSearchAction
An action that ends the current search interaction.
func searchable(text:isPresented:placement:prompt:)
Marks this view as searchable with programmatic presentation of the search field.
func searchable(text:tokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text and tokens, as well as programmatic presentation.
func searchable(text:editableTokens:isPresented:placement:prompt:token:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions, as well as programmatic presentation.
https://developer.apple.com/documentation/swiftui/view/searchable(text:ispresented:placement:prompt:)
#app-main)
- SwiftUI
- View
- searchable(text:isPresented:placement:prompt:)
Instance Method
searchable(text:isPresented:placement:prompt:)
Marks this view as searchable with programmatic presentation of the search field.
nonisolated func searchable(
placement: SearchFieldPlacement = .automatic, prompt: LocalizedStringKey
Show all declarations
Parameters
text
The text to display and edit in the search field.
placement
The preferred placement of the search field within the containing view hierarchy.
prompt
The key for the localized prompt of the search field which provides users with guidance on what to search for.
Discussion
For more information about using searchable modifiers, see Adding a search interface to your app. For information about presenting a search field programmatically, see Managing search interface activation.
See Also
Detecting, activating, and dismissing search
Managing search interface activation
Programmatically detect and dismiss a search field.
var isSearching: Bool
A Boolean value that indicates when the user is searching.
var dismissSearch: DismissSearchAction
An action that ends the current search interaction.
struct DismissSearchAction
An action that can end a search interaction.
func searchable(text:tokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text and tokens, as well as programmatic presentation.
func searchable(text:editableTokens:isPresented:placement:prompt:token:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions, as well as programmatic presentation.
https://developer.apple.com/documentation/swiftui/view/searchable(text:tokens:ispresented:placement:prompt:token:)
#app-main)
- SwiftUI
- View
- searchable(text:tokens:isPresented:placement:prompt:token:)
Instance Method
searchable(text:tokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text and tokens, as well as programmatic presentation.
nonisolated
placement: SearchFieldPlacement = .automatic, prompt: S,
Show all declarations
Parameters
text
The text to display and edit in the search field.
tokens
A collection of tokens to display and edit in the search field.
placement
The preferred placement of the search field within the containing view hierarchy.
prompt
A string representing the prompt of the search field which provides users with guidance on what to search for.
token
A view builder that creates a view given an element in tokens.
Discussion
For more information about using searchable modifiers, see Adding a search interface to your app. For information about presenting a search field programmatically, see Managing search interface activation.
See Also
Detecting, activating, and dismissing search
Managing search interface activation
Programmatically detect and dismiss a search field.
var isSearching: Bool
A Boolean value that indicates when the user is searching.
var dismissSearch: DismissSearchAction
An action that ends the current search interaction.
struct DismissSearchAction
An action that can end a search interaction.
func searchable(text:isPresented:placement:prompt:)
Marks this view as searchable with programmatic presentation of the search field.
func searchable(text:editableTokens:isPresented:placement:prompt:token:)
Marks this view as searchable, which configures the display of a search field.
func searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions, as well as programmatic presentation.
https://developer.apple.com/documentation/swiftui/view/searchable(text:editabletokens:ispresented:placement:prompt:token:)
#app-main)
- SwiftUI
- View
- searchable(text:editableTokens:isPresented:placement:prompt:token:)
Instance Method
searchable(text:editableTokens:isPresented:placement:prompt:token:)
Marks this view as searchable, which configures the display of a search field.
nonisolated
placement: SearchFieldPlacement = .automatic, prompt: LocalizedStringKey,
Show all declarations
Parameters
text
The text to display and edit in the search field.
editableTokens
A collection of tokens to display and edit in the search field.
placement
The preferred placement of the search field within the containing view hierarchy.
prompt
The key for the localized prompt of the search field which provides users with guidance on what to search for.
token
A view builder that creates a view given an element in tokens.
Discussion
For more information about using searchable modifiers, see Adding a search interface to your app.
See Also
Detecting, activating, and dismissing search
Managing search interface activation
Programmatically detect and dismiss a search field.
var isSearching: Bool
A Boolean value that indicates when the user is searching.
var dismissSearch: DismissSearchAction
An action that ends the current search interaction.
struct DismissSearchAction
An action that can end a search interaction.
func searchable(text:isPresented:placement:prompt:)
Marks this view as searchable with programmatic presentation of the search field.
func searchable(text:tokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text and tokens, as well as programmatic presentation.
func searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions, as well as programmatic presentation.
https://developer.apple.com/documentation/swiftui/view/searchable(text:tokens:suggestedtokens:ispresented:placement:prompt:token:)
#app-main)
- SwiftUI
- View
- searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Instance Method
searchable(text:tokens:suggestedTokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text, tokens, and suggestions, as well as programmatic presentation.
nonisolated
placement: SearchFieldPlacement = .automatic, prompt: S,
Show all declarations
Parameters
text
The text to display and edit in the search field.
tokens
A collection of tokens to display and edit in the search field.
suggestedTokens
A collection of tokens to display as suggestions.
placement
The preferred placement of the search field within the containing view hierarchy.
prompt
A string representing the prompt of the search field which provides users with guidance on what to search for.
token
A view builder that creates a view given an element in tokens.
Discussion
For more information about using searchable modifiers, see Adding a search interface to your app. For information about presenting a search field programmatically, see Managing search interface activation.
See Also
Detecting, activating, and dismissing search
Managing search interface activation
Programmatically detect and dismiss a search field.
var isSearching: Bool
A Boolean value that indicates when the user is searching.
var dismissSearch: DismissSearchAction
An action that ends the current search interaction.
struct DismissSearchAction
An action that can end a search interaction.
func searchable(text:isPresented:placement:prompt:)
Marks this view as searchable with programmatic presentation of the search field.
func searchable(text:tokens:isPresented:placement:prompt:token:)
Marks this view as searchable with text and tokens, as well as programmatic presentation.
func searchable(text:editableTokens:isPresented:placement:prompt:token:)
Marks this view as searchable, which configures the display of a search field.
https://developer.apple.com/documentation/swiftui/view/searchpresentationtoolbarbehavior(_:)
#app-main)
- SwiftUI
- View
- searchPresentationToolbarBehavior(_:)
Instance Method
searchPresentationToolbarBehavior(_:)
Configures the search toolbar presentation behavior for any searchable modifiers within this view.
nonisolated
Discussion
By default on iOS, a toolbar may hide parts of its content when presenting search to focus on searching. You can override this behavior by providing a value of avoidHidingContent to this modifer.
@State private var searchText = ""
List { // ... content } .searchable(text: $searchText) .searchPresentationToolbarBehavior(.avoidHidingContent)
See Also
Displaying toolbar content during search
struct SearchPresentationToolbarBehavior
A type that defines how the toolbar behaves when presenting search.
https://developer.apple.com/documentation/swiftui/searchpresentationtoolbarbehavior
- SwiftUI
- SearchPresentationToolbarBehavior
Structure
SearchPresentationToolbarBehavior
A type that defines how the toolbar behaves when presenting search.
struct SearchPresentationToolbarBehavior
Overview
Use this type in combination with the searchPresentationToolbarBehavior(_:)
Topics
Getting toolbar behaviors
static var automatic: SearchPresentationToolbarBehavior
The automatic behavior.
static var avoidHidingContent: SearchPresentationToolbarBehavior
The avoid hiding content behavior.
See Also
Displaying toolbar content during search
Configures the search toolbar presentation behavior for any searchable modifiers within this view.
https://developer.apple.com/documentation/swiftui/view/findnavigator(ispresented:)
#app-main)
- SwiftUI
- View
- findNavigator(isPresented:)
Instance Method
findNavigator(isPresented:)
Programmatically presents the find and replace interface for text editor views.
nonisolated
Parameters
isPresented
A binding to a Boolean value that controls the presentation of the find and replace interface.
Return Value
A view that presents the find and replace interface when isPresented is true.
Discussion
Add this modifier to a TextEditor, or to a view hierarchy that contains at least one text editor, to control the presentation of the find and replace interface. When you set the isPresented binding to true, the system shows the interface, and when you set it to false, the system hides the interface. The following example shows and hides the interface based on the state of a toolbar button:
TextEditor(text: $text) .findNavigator(isPresented: $isPresented) .toolbar { Toggle(isOn: $isPresented) { Label("Find", systemImage: "magnifyingglass") } }
The find and replace interface allows people to search for instances of a specified string in the text editor, and optionally to replace instances of the search string with another string. They can also show and hide the interface using built-in controls, like menus and keyboard shortcuts. SwiftUI updates isPresented to reflect the users’s actions.
If the text editor view isn’t currently in focus, the system still presents the find and replace interface when you set isPresented to true. If the view hierarchy contains multiple editors, the one that shows the find and replace interface is nondeterministic.
You can disable the find and replace interface for a text editor by applying the findDisabled(_:) modifier to the editor. If you do that, setting this modifier’s isPresented binding to true has no effect, but only if the disabling modifier appears closer to the text editor, like this:
TextEditor(text: $text) .findDisabled(isDisabled) .findNavigator(isPresented: $isPresented)
See Also
Searching for text in a view
Prevents find and replace operations in a text editor.
Prevents replace operations in a text editor.
struct FindContext
The status of the find navigator for views which support text editing.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/finddisabled(_:)
#app-main)
- SwiftUI
- View
- findDisabled(_:)
Instance Method
findDisabled(_:)
Prevents find and replace operations in a text editor.
nonisolated
Parameters
isDisabled
A Boolean value that indicates whether to disable the find and replace interface for a text editor.
Return Value
A view that disables the find and replace interface.
Discussion
Add this modifier to ensure that people can’t activate the find and replace interface for a TextEditor:
TextEditor(text: $text) .findDisabled()
When you disable the find operation, you also implicitly disable the replace operation. If you want to only disable replace, use replaceDisabled(_:) instead.
Using this modifer also prevents programmatic find and replace interface presentation using the findNavigator(isPresented:) method. Be sure to place the disabling modifier closer to the text editor for this to work:
TextEditor(text: $text) .findDisabled(isDisabled) .findNavigator(isPresented: $isPresented)
If you apply this modifer at multiple levels of a view hierarchy, the call closest to the text editor takes precedence. For example, people can activate find and replace for the first text editor in the following example, but not the second:
VStack { TextEditor(text: $text1) .findDisabled(false) TextEditor(text: $text2) } .findDisabled(true)
See Also
Searching for text in a view
Programmatically presents the find and replace interface for text editor views.
Prevents replace operations in a text editor.
struct FindContext
The status of the find navigator for views which support text editing.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/replacedisabled(_:)
#app-main)
- SwiftUI
- View
- replaceDisabled(_:)
Instance Method
replaceDisabled(_:)
Prevents replace operations in a text editor.
nonisolated
Parameters
isDisabled
A Boolean value that indicates whether text replacement in the find and replace interface is disabled.
Return Value
A view that disables the replace feature of a find and replace interface.
Discussion
Add this modifier to ensure that people can’t activate the replace feature of a find and replace interface for a TextEditor:
TextEditor(text: $text) .replaceDisabled()
If you want to disable both find and replace, use the findDisabled(_:) modifier instead.
Using this modifer also disables the replace feature of a find and replace interface that you present programmatically using the findNavigator(isPresented:) method. Be sure to place the disabling modifier closer to the text editor for this to work:
TextEditor(text: $text) .replaceDisabled(isDisabled) .findNavigator(isPresented: $isPresented)
If you apply this modifer at multiple levels of a view hierarchy, the call closest to the text editor takes precedence. For example, people can activate find and replace for the first text editor in the following example, but only find for the second:
VStack { TextEditor(text: $text1) .replaceDisabled(false) TextEditor(text: $text2) } .replaceDisabled(true)
See Also
Searching for text in a view
Programmatically presents the find and replace interface for text editor views.
Prevents find and replace operations in a text editor.
struct FindContext
The status of the find navigator for views which support text editing.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/findcontext
https://developer.apple.com/documentation/swiftui/adding-a-search-interface-to-your-app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/performing-a-search-operation)
https://developer.apple.com/documentation/swiftui/view/searchable(text:placement:prompt:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/searchable(text:tokens:placement:prompt:token:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/searchable(text:editabletokens:placement:prompt:token:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/searchfieldplacement)
https://developer.apple.com/documentation/swiftui/suggesting-search-terms)
https://developer.apple.com/documentation/swiftui/view/searchsuggestions(_:))
https://developer.apple.com/documentation/swiftui/view/searchsuggestions(_:for:))
https://developer.apple.com/documentation/swiftui/view/searchcompletion(_:))
https://developer.apple.com/documentation/swiftui/view/searchable(text:tokens:suggestedtokens:placement:prompt:token:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/searchsuggestionsplacement)
https://developer.apple.com/documentation/swiftui/scoping-a-search-operation)
https://developer.apple.com/documentation/swiftui/view/searchscopes(_:scopes:))
https://developer.apple.com/documentation/swiftui/view/searchscopes(:activation::))
https://developer.apple.com/documentation/swiftui/searchscopeactivation)
https://developer.apple.com/documentation/swiftui/managing-search-interface-activation)
https://developer.apple.com/documentation/swiftui/environmentvalues/issearching)
https://developer.apple.com/documentation/swiftui/environmentvalues/dismisssearch)
https://developer.apple.com/documentation/swiftui/dismisssearchaction)
https://developer.apple.com/documentation/swiftui/view/searchable(text:ispresented:placement:prompt:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/searchable(text:tokens:ispresented:placement:prompt:token:))
https://developer.apple.com/documentation/swiftui/view/searchable(text:editabletokens:ispresented:placement:prompt:token:))
https://developer.apple.com/documentation/swiftui/view/searchable(text:tokens:suggestedtokens:ispresented:placement:prompt:token:))
https://developer.apple.com/documentation/swiftui/view/searchpresentationtoolbarbehavior(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/searchpresentationtoolbarbehavior)
https://developer.apple.com/documentation/swiftui/view/findnavigator(ispresented:))
https://developer.apple.com/documentation/swiftui/view/finddisabled(_:))
https://developer.apple.com/documentation/swiftui/view/replacedisabled(_:))
https://developer.apple.com/documentation/swiftui/findcontext)
https://developer.apple.com/documentation/swiftui/view/hidden()
https://developer.apple.com/documentation/swiftui/view/labelshidden()
https://developer.apple.com/documentation/swiftui/environmentvalues/labelsvisibility
https://developer.apple.com/documentation/swiftui/view/menuindicator(_:)
#app-main)
- SwiftUI
- View
- menuIndicator(_:)
Instance Method
menuIndicator(_:)
Sets the menu indicator visibility for controls within this view.
nonisolated
Parameters
visibility
The menu indicator visibility to apply.
Discussion
Use this modifier to override the default menu indicator visibility for controls in this view. For example, the code below creates a menu without an indicator:
Menu { ForEach(history , id: .self) { historyItem in Button(historyItem.title) { self.openURL(historyItem.url) } } } label: { Label("Back", systemImage: "chevron.backward") .labelStyle(.iconOnly) } primaryAction: { if let last = history.last { self.openURL(last.url) } } .menuIndicator(.hidden)
See Also
Showing a menu indicator
var menuIndicatorVisibility: Visibility
The menu indicator visibility to apply to controls within a view.
https://developer.apple.com/documentation/swiftui/view/statusbarhidden(_:)
https://developer.apple.com/documentation/swiftui/view/persistentsystemoverlays(_:)
https://developer.apple.com/documentation/swiftui/visibility
- SwiftUI
- Visibility
Enumeration
Visibility
The visibility of a UI element, chosen automatically based on the platform, current context, and other factors.
@frozen enum Visibility
Overview
For example, the preferred visibility of list row separators can be configured using the listRowSeparator(_:edges:).
Topics
Getting visibility options
case automatic
The element may be visible or hidden depending on the policies of the component accepting the visibility configuration.
case visible
The element may be visible.
case hidden
The element may be hidden.
Relationships
Conforms To
BitwiseCopyableCaseIterableCopyableEquatableHashableSendableSendableMetatype
See Also
Hiding system elements
Hides the labels of any controls contained within this view.
Controls the visibility of labels of any controls contained within this view.
var labelsVisibility: Visibility
The labels visibility set by labelsVisibility(_:).
Sets the menu indicator visibility for controls within this view.
Sets the visibility of the status bar.
Sets the preferred visibility of the non-transient system views overlaying the app.
https://developer.apple.com/documentation/swiftui/view/disabled(_:)
https://developer.apple.com/documentation/swiftui/environmentvalues/isenabled
https://developer.apple.com/documentation/swiftui/view/interactionactivitytrackingtag(_:)
#app-main)
- SwiftUI
- View
- interactionActivityTrackingTag(_:)
Instance Method
interactionActivityTrackingTag(_:)
Sets a tag that you use for tracking interactivity.
nonisolated
Parameters
tag
The tag used to track user interactions hosted by this view as activities.
Return Value
A view that uses a tracking tag.
Discussion
The following example tracks the scrolling activity of a List:
List { Section("Today") { ForEach(messageStore.today) { message in Text(message.title) } } } .interactionActivityTrackingTag("MessagesList")
The resolved activity tracking tag is additive, so using the modifier across the view hierarchy builds the tag from top to bottom. The example below shows a hierarchical usage of this modifier with the resulting tag Home-Feed:
var body: some View { Home() .interactionActivityTrackingTag("Home") }
struct Home: View { var body: some View { List { Text("A List Item") Text("A Second List Item") Text("A Third List Item") } .interactionActivityTrackingTag("Feed") } }
See Also
Managing view interaction
Adds a condition that controls whether users can interact with this view.
var isEnabled: Bool
A Boolean value that indicates whether the view associated with this environment allows user interaction.
Mark the receiver as their content might be invalidated.
https://developer.apple.com/documentation/swiftui/view/invalidatablecontent(_:)
#app-main)
- SwiftUI
- View
- invalidatableContent(_:)
Instance Method
invalidatableContent(_:)
Mark the receiver as their content might be invalidated.
nonisolated
Parameters
invalidatable
Whether the receiver content might be invalidated.
Discussion
Use this modifier to annotate views that display values that are derived from the current state of your data and might be invalidated in response of, for example, user interaction.
The view will change its appearance when RedactionReasons.invalidated is present in the environment.
In an interactive widget a view is invalidated from the moment the user interacts with a control on the widget to the moment when a new timeline update has been presented.
See Also
Managing view interaction
Adds a condition that controls whether users can interact with this view.
var isEnabled: Bool
A Boolean value that indicates whether the view associated with this environment allows user interaction.
Sets a tag that you use for tracking interactivity.
https://developer.apple.com/documentation/swiftui/view/help(_:)
#app-main)
- SwiftUI
- View
- help(_:)
Instance Method
help(_:)
Adds help text to a view using a text view that you provide.
nonisolated
Show all declarations
Parameters
text
The Text view to use as help.
Discussion
Adding help to a view configures the view’s accessibility hint and its help tag (also called a tooltip) in macOS or visionOS. For more information on using help tags, see Offering help in the Human Interface Guidelines.
Slider("Opacity", value: $selectedShape.opacity) .help(Text("Adjust the opacity of the selected (selectedShape.name)"))
https://developer.apple.com/documentation/swiftui/view/preferredcolorscheme(_:)
https://developer.apple.com/documentation/swiftui/environmentvalues/colorscheme
- SwiftUI
- EnvironmentValues
- colorScheme
Instance Property
colorScheme
The color scheme of this environment.
var colorScheme: ColorScheme { get set }
Discussion
Read this environment value from within a view to find out if SwiftUI is currently displaying the view using the ColorScheme.light or ColorScheme.dark appearance. The value that you receive depends on whether the user has enabled Dark Mode, possibly superseded by the configuration of the current presentation’s view hierarchy.
@Environment(.colorScheme) private var colorScheme
var body: some View { Text(colorScheme == .dark ? "Dark" : "Light") }
You can set the colorScheme environment value directly, but that usually isn’t what you want. Doing so changes the color scheme of the given view and its child views but not the views above it in the view hierarchy. Instead, set a color scheme using the preferredColorScheme(_:) modifier, which also propagates the value up through the view hierarchy to the enclosing presentation, like a sheet or a window.
When adjusting your app’s user interface to match the color scheme, consider also checking the colorSchemeContrast property, which reflects a system-wide contrast setting that the user controls. For information, see Accessibility in the Human Interface Guidelines.
See Also
Detecting and requesting the light or dark appearance
Sets the preferred color scheme for this presentation.
enum ColorScheme
The possible color schemes, corresponding to the light and dark appearances.
https://developer.apple.com/documentation/swiftui/colorscheme
- SwiftUI
- ColorScheme
Enumeration
ColorScheme
The possible color schemes, corresponding to the light and dark appearances.
enum ColorScheme
Overview
You receive a color scheme value when you read the colorScheme environment value. The value tells you if a light or dark appearance currently applies to the view. SwiftUI updates the value whenever the appearance changes, and redraws views that depend on the value. For example, the following Text view automatically updates when the user enables Dark Mode:
@Environment(.colorScheme) private var colorScheme
var body: some View { Text(colorScheme == .dark ? "Dark" : "Light") }
Set a preferred appearance for a particular view hierarchy to override the user’s Dark Mode setting using the preferredColorScheme(_:) view modifier.
Topics
Getting color schemes
case light
The color scheme that corresponds to a light appearance.
case dark
The color scheme that corresponds to a dark appearance.
Creating a color scheme
init?(UIUserInterfaceStyle)
Creates a color scheme from its user interface style equivalent.
Supporting types
struct PreferredColorSchemeKey
A key for specifying the preferred color scheme.
Relationships
Conforms To
CaseIterableCopyableEquatableHashableSendableSendableMetatype
See Also
Detecting and requesting the light or dark appearance
Sets the preferred color scheme for this presentation.
var colorScheme: ColorScheme
The color scheme of this environment.
https://developer.apple.com/documentation/swiftui/environmentvalues/colorschemecontrast
- SwiftUI
- EnvironmentValues
- colorSchemeContrast
Instance Property
colorSchemeContrast
The contrast associated with the color scheme of this environment.
var colorSchemeContrast: ColorSchemeContrast { get }
Discussion
Read this environment value from within a view to find out if SwiftUI is currently displaying the view using ColorSchemeContrast.standard or ColorSchemeContrast.increased contrast. The value that you read depends entirely on user settings, and you can’t change it.
@Environment(.colorSchemeContrast) private var colorSchemeContrast
var body: some View { Text(colorSchemeContrast == .standard ? "Standard" : "Increased") }
When adjusting your app’s user interface to match the contrast, consider also checking the colorScheme property to find out if SwiftUI is displaying the view with a light or dark appearance. For information, see Accessibility in the Human Interface Guidelines.
See Also
Getting the color scheme contrast
enum ColorSchemeContrast
The contrast between the app’s foreground and background colors.
https://developer.apple.com/documentation/swiftui/colorschemecontrast
https://developer.apple.com/documentation/swiftui/view/preferredsurroundingseffect(_:)
https://developer.apple.com/documentation/swiftui/surroundingseffect
- SwiftUI
- SurroundingsEffect
Structure
SurroundingsEffect
Effects that the system can apply to passthrough video.
struct SurroundingsEffect
Overview
Use one of these values with the preferredSurroundingsEffect(_:) view modifier to indicate what effect to apply to passthrough video when the modified view is displayed.
Topics
Getting the effect
static var systemDark: SurroundingsEffect
An effect that dims passthrough video.
Deprecated
Type Properties
static var dark: SurroundingsEffect
static var semiDark: SurroundingsEffect
An effect that dims passthrough video less than dark.
static var ultraDark: SurroundingsEffect
An effect that dims passthrough video more than dark
Type Methods
An effect that applies a custom tint to the passthrough video by multiplying the passthrough with a Color.
An effect that dims the passthrough video a custom amount.
Relationships
Conforms To
Equatable
See Also
Configuring passthrough
Applies an effect to passthrough video.
struct BreakthroughEffect Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/breakthrougheffect
- SwiftUI
- BreakthroughEffect Beta
Structure
BreakthroughEffect
struct BreakthroughEffect
Topics
Type Properties
static let automatic: BreakthroughEffect
The system will choose the best effect for the type of element and its position within the scene. This might result in no breakthrough effect.
static let none: BreakthroughEffect
The element is clipped by occluding content. This is not supported when used to customize a sheet breakthrough effect.
static let prominent: BreakthroughEffect
The element is prominently revealed through occluding content.
static let subtle: BreakthroughEffect
The element is subtly blended over occluding content.
Relationships
Conforms To
EquatableSendableSendableMetatype
See Also
Configuring passthrough
Applies an effect to passthrough video.
struct SurroundingsEffect
Effects that the system can apply to passthrough video.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/privacysensitive(_:)
#app-main)
- SwiftUI
- View
- privacySensitive(_:)
Instance Method
privacySensitive(_:)
Marks the view as containing sensitive, private user data.
nonisolated
Discussion
SwiftUI redacts views marked with this modifier when you apply the privacy redaction reason.
struct BankAccountView: View { var body: some View { VStack { Text("Account #")
Text(accountNumber) .font(.headline) .privacySensitive() // Hide only the account number. } } }
See Also
Redacting private content
Designing your app for the Always On state
Customize your watchOS app’s user interface for continuous display.
Adds a reason to apply a redaction to this view hierarchy.
Removes any reason to apply a redaction to this view hierarchy.
var redactionReasons: RedactionReasons
The current redaction reasons applied to the view hierarchy.
var isSceneCaptured: Bool
The current capture state.
struct RedactionReasons
The reasons to apply a redaction to data displayed on screen.
https://developer.apple.com/documentation/swiftui/view/redacted(reason:)
https://developer.apple.com/documentation/swiftui/view/unredacted()
#app-main)
- SwiftUI
- View
- unredacted()
Instance Method
unredacted()
Removes any reason to apply a redaction to this view hierarchy.
nonisolated
See Also
Redacting private content
Designing your app for the Always On state
Customize your watchOS app’s user interface for continuous display.
Marks the view as containing sensitive, private user data.
Adds a reason to apply a redaction to this view hierarchy.
var redactionReasons: RedactionReasons
The current redaction reasons applied to the view hierarchy.
var isSceneCaptured: Bool
The current capture state.
struct RedactionReasons
The reasons to apply a redaction to data displayed on screen.
https://developer.apple.com/documentation/swiftui/environmentvalues/redactionreasons
https://developer.apple.com/documentation/swiftui/environmentvalues/isscenecaptured
https://developer.apple.com/documentation/swiftui/redactionreasons
- SwiftUI
- RedactionReasons
Structure
RedactionReasons
The reasons to apply a redaction to data displayed on screen.
struct RedactionReasons
Topics
Getting redaction reasons
static let invalidated: RedactionReasons
Displayed data should appear as invalidated and pending a new update.
static let placeholder: RedactionReasons
Displayed data should appear as generic placeholders.
static let privacy: RedactionReasons
Displayed data should be obscured to protect private information.
Creating redaction reasons
init(rawValue: Int)
Creates a new set from a raw value.
let rawValue: Int
The raw value.
Relationships
Conforms To
EquatableExpressibleByArrayLiteralOptionSetRawRepresentableSendableSendableMetatypeSetAlgebra
See Also
Redacting private content
Designing your app for the Always On state
Customize your watchOS app’s user interface for continuous display.
Marks the view as containing sensitive, private user data.
Adds a reason to apply a redaction to this view hierarchy.
Removes any reason to apply a redaction to this view hierarchy.
var redactionReasons: RedactionReasons
The current redaction reasons applied to the view hierarchy.
var isSceneCaptured: Bool
The current capture state.
https://developer.apple.com/documentation/swiftui/view/hidden())
https://developer.apple.com/documentation/swiftui/view/labelshidden())
https://developer.apple.com/documentation/swiftui/environmentvalues/labelsvisibility)
https://developer.apple.com/documentation/swiftui/view/labelsvisibility(_:)).
https://developer.apple.com/documentation/swiftui/view/menuindicator(_:))
https://developer.apple.com/documentation/swiftui/view/statusbarhidden(_:))
https://developer.apple.com/documentation/swiftui/view/persistentsystemoverlays(_:))
https://developer.apple.com/documentation/swiftui/visibility)
https://developer.apple.com/documentation/swiftui/view/disabled(_:))
https://developer.apple.com/documentation/swiftui/environmentvalues/isenabled)
https://developer.apple.com/documentation/swiftui/view/interactionactivitytrackingtag(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/invalidatablecontent(_:))
https://developer.apple.com/documentation/swiftui/view/help(_:))
https://developer.apple.com/documentation/swiftui/view/preferredcolorscheme(_:))
https://developer.apple.com/documentation/swiftui/environmentvalues/colorscheme)
https://developer.apple.com/documentation/swiftui/colorscheme)
https://developer.apple.com/documentation/swiftui/environmentvalues/colorschemecontrast)
https://developer.apple.com/documentation/swiftui/colorschemecontrast)
https://developer.apple.com/documentation/swiftui/view/preferredsurroundingseffect(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/surroundingseffect)
https://developer.apple.com/documentation/swiftui/breakthrougheffect)
https://developer.apple.com/documentation/swiftui/view/privacysensitive(_:))
https://developer.apple.com/documentation/swiftui/view/redacted(reason:))
https://developer.apple.com/documentation/swiftui/view/unredacted())
https://developer.apple.com/documentation/swiftui/environmentvalues/redactionreasons)
https://developer.apple.com/documentation/swiftui/environmentvalues/isscenecaptured)
https://developer.apple.com/documentation/swiftui/redactionreasons)
https://developer.apple.com/documentation/swiftui/preferencekey
- SwiftUI
- PreferenceKey
Protocol
PreferenceKey
A named value produced by a view.
protocol PreferenceKey
Overview
A view with multiple children automatically combines its values for a given preference into a single value visible to its ancestors.
Topics
Getting the default value
static var defaultValue: Self.Value
The default value of the preference.
Required Default implementation provided.
associatedtype Value
The type of value produced by this preference.
Required
Combining preferences
Combines a sequence of values by modifying the previously-accumulated value with the result of a closure that provides the next value.
Relationships
Conforming Types
PreferredColorSchemeKeyText.LayoutKey
https://developer.apple.com/documentation/swiftui/view/preference(key:value:)
#app-main)
- SwiftUI
- View
- preference(key:value:)
Instance Method
preference(key:value:)
Sets a value for the given preference.
nonisolated
key: K.Type = K.self, value: K.Value
See Also
Setting preferences
Applies a transformation to a preference value.
https://developer.apple.com/documentation/swiftui/view/transformpreference(::)
#app-main)
- SwiftUI
- View
- transformPreference(_:_:)
Instance Method
transformPreference(_:_:)
Applies a transformation to a preference value.
nonisolated
_ key: K.Type = K.self,
See Also
Setting preferences
Sets a value for the given preference.
https://developer.apple.com/documentation/swiftui/view/anchorpreference(key:value:transform:)
#app-main)
- SwiftUI
- View
- anchorPreference(key:value:transform:)
Instance Method
anchorPreference(key:value:transform:)
Sets a value for the specified preference key, the value is a function of a geometry value tied to the current coordinate space, allowing readers of the value to convert the geometry to their local coordinates.
nonisolated
key _: K.Type = K.self,
Parameters
key
The preference key type.
value
The geometry value in the current coordinate space.
transform
The function to produce the preference value.
Return Value
A new version of the view that writes the preference.
See Also
Setting preferences based on geometry
Sets a value for the specified preference key, the value is a function of the key’s current value and a geometry value tied to the current coordinate space, allowing readers of the value to convert the geometry to their local coordinates.
https://developer.apple.com/documentation/swiftui/view/transformanchorpreference(key:value:transform:)
https://developer.apple.com/documentation/swiftui/view/onpreferencechange(_:perform:)
https://developer.apple.com/documentation/swiftui/view/backgroundpreferencevalue(::)
https://developer.apple.com/documentation/swiftui/view/backgroundpreferencevalue(:alignment::)
https://developer.apple.com/documentation/swiftui/view/overlaypreferencevalue(::)
https://developer.apple.com/documentation/swiftui/view/overlaypreferencevalue(:alignment::)
#app-main)
- SwiftUI
- View
- overlayPreferenceValue(_:alignment:_:)
Instance Method
overlayPreferenceValue(_:alignment:_:)
Reads the specified preference value from the view, using it to produce a second view that is applied as an overlay to the original view.
nonisolated
_ key: K.Type, alignment: Alignment = .center,
Parameters
key
The preference key type whose value is to be read.
alignment
An optional alignment to use when positioning the overlay view relative to the original view.
transform
A function that produces the overlay view from the preference value read from the original view.
Return Value
A view that layers a second view in front of the view.
Discussion
The values of the preference key from both views are combined and made visible to the parent view.
See Also
Generating backgrounds and overlays from preferences
Reads the specified preference value from the view, using it to produce a second view that is applied as the background of the original view.
https://developer.apple.com/documentation/swiftui/preferencekey)
https://developer.apple.com/documentation/swiftui/view/preference(key:value:))
https://developer.apple.com/documentation/swiftui/view/navigationtitle(_:)),
https://developer.apple.com/documentation/swiftui/view/transformpreference(::))
https://developer.apple.com/documentation/swiftui/view/anchorpreference(key:value:transform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/transformanchorpreference(key:value:transform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/onpreferencechange(_:perform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/backgroundpreferencevalue(::))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/backgroundpreferencevalue(:alignment::))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/overlaypreferencevalue(::))
https://developer.apple.com/documentation/swiftui/view/overlaypreferencevalue(:alignment::))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/environment
- SwiftUI
- Environment
Structure
Environment
A property wrapper that reads a value from a view’s environment.
@frozen @propertyWrapper
Mentioned in
Building and customizing the menu bar with SwiftUI
Migrating to the SwiftUI life cycle
Managing search interface activation
Overview
Use the Environment property wrapper to read a value stored in a view’s environment. Indicate the value to read using an EnvironmentValues key path in the property declaration. For example, you can create a property that reads the color scheme of the current view using the key path of the colorScheme property:
@Environment(.colorScheme) var colorScheme: ColorScheme
You can condition a view’s content on the associated value, which you read from the declared property’s wrappedValue. As with any property wrapper, you access the wrapped value by directly referring to the property:
if colorScheme == .dark { // Checks the wrapped value. DarkContent() } else { LightContent() }
If the value changes, SwiftUI updates any parts of your view that depend on the value. For example, that might happen in the above example if the user changes the Appearance settings.
You can use this property wrapper to read — but not set — an environment value. SwiftUI updates some environment values automatically based on system settings and provides reasonable defaults for others. You can override some of these, as well as set custom environment values that you define, using the environment(_:_:) view modifier.
For the complete list of environment values SwiftUI provides, see the properties of the EnvironmentValues structure. For information about creating custom environment values, see the Entry() macro.
Get an observable object
You can also use Environment to get an observable object from a view’s environment. The observable object must conform to the Observable protocol, and your app must set the object in the environment using the the object itself or a key path.
To set the object in the environment using the object itself, use the environment(_:) modifier:
@Observable class Library { var books: [Book] = [Book(), Book(), Book()]
var availableBooksCount: Int { books.filter(.isAvailable).count } }
@main struct BookReaderApp: App { @State private var library = Library()
var body: some Scene { WindowGroup { LibraryView() .environment(library) } } }
To get the observable object using its type, create a property and provide the Environment property wrapper the object’s type:
struct LibraryView: View { @Environment(Library.self) private var library
var body: some View { // ... } }
By default, reading an object from the environment returns a non-optional object when using the object type as the key. This default behavior assumes that a view in the current hierarchy previously stored a non-optional instance of the type using the environment(_:) modifier. If a view attempts to retrieve an object using its type and that object isn’t in the environment, SwiftUI throws an exception.
In cases where there is no guarantee that an object is in the environment, retrieve an optional version of the object as shown in the following code. If the object isn’t available the environment, SwiftUI returns nil instead of throwing an exception.
@Environment(Library.self) private var library: Library?
Get an observable object using a key path
To set the object with a key path, use the environment(_:_:) modifier:
var body: some Scene { WindowGroup { LibraryView() .environment(.library, library) } } }
To get the object, create a property and specify the key path:
struct LibraryView: View { @Environment(.library) private var library
Topics
Creating an environment instance
init(_:)
Creates an environment property to read the specified key path.
Getting the value
var wrappedValue: Value
The current value of the environment property.
Relationships
Conforms To
DynamicPropertySendableSendableMetatype
See Also
Accessing environment values
struct EnvironmentValues
A collection of environment values propagated through a view hierarchy.
https://developer.apple.com/documentation/swiftui/view/environment(::)
#app-main)
- SwiftUI
- View
- environment(_:_:)
Instance Method
environment(_:_:)
Sets the environment value of the specified key path to the given value.
nonisolated
_ value: V
Parameters
keyPath
A key path that indicates the property of the EnvironmentValues structure to update.
value
The new value to set for the item specified by keyPath.
Return Value
A view that has the given value set in its environment.
Mentioned in
Applying custom fonts to text
Discussion
Use this modifier to set one of the writable properties of the EnvironmentValues structure, including custom values that you create. For example, you can set the value associated with the truncationMode key:
MyView() .environment(.truncationMode, .head)
You then read the value inside MyView or one of its descendants using the Environment property wrapper:
struct MyView: View { @Environment(.truncationMode) var truncationMode: Text.TruncationMode
var body: some View { ... } }
SwiftUI provides dedicated view modifiers for setting most environment values, like the truncationMode(_:) modifier which sets the truncationMode value:
MyView() .truncationMode(.head)
Prefer the dedicated modifier when available, and offer your own when defining custom environment values, as described in Entry().
This modifier affects the given view, as well as that view’s descendant views. It has no effect outside the view hierarchy on which you call it.
See Also
Modifying the environment of a view
Places an observable object in the view’s environment.
Transforms the environment value of the specified key path with the given function.
https://developer.apple.com/documentation/swiftui/environmentvalues
- SwiftUI
- EnvironmentValues
Structure
EnvironmentValues
A collection of environment values propagated through a view hierarchy.
struct EnvironmentValues
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:
MyView() .environment(.lineLimit, 2)
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:
MyView() .lineLimit(2)
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:
MyView() .popover(isPresented: $isPopped) { PopoverContent() .preferredColorScheme(.dark) }
Create a custom environment value by declaring a new property in an extension to the environment values structure and applying the Entry() macro to the variable declaration:
extension EnvironmentValues { @Entry var myCustomValue: String = "Default value" }
extension 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.
Topics
Creating and accessing values
init()
Creates an environment values instance.
subscript(_:)
Accesses the environment value associated with a custom key.
var description: String
A string that represents the contents of the environment values instance.
Accessibility
var accessibilityAssistiveAccessEnabled: Bool
A Boolean value that indicates whether Assistive Access is in use.
var accessibilityDimFlashingLights: Bool
Whether the setting to reduce flashing or strobing lights in video content is on. This setting can also be used to determine if UI in playback controls should be shown to indicate upcoming content that includes flashing or strobing lights.
var accessibilityDifferentiateWithoutColor: Bool
Whether the system preference for Differentiate without Color is enabled.
var accessibilityEnabled: Bool
A Boolean value that indicates whether the user has enabled an assistive technology.
var accessibilityInvertColors: Bool
Whether the system preference for Invert Colors is enabled.
var accessibilityLargeContentViewerEnabled: Bool
Whether the Large Content Viewer is enabled.
var accessibilityPlayAnimatedImages: Bool
Whether the setting for playing animations in an animated image is on. When this value is false, any presented image that contains animation should not play automatically.
var accessibilityPrefersHeadAnchorAlternative: Bool
Whether the system setting to prefer alternatives to head-anchored content is on.
var accessibilityQuickActionsEnabled: Bool
A Boolean that indicates whether the quick actions feature is enabled.
var accessibilityReduceMotion: Bool
Whether the system preference for Reduce Motion is enabled.
var accessibilityReduceTransparency: Bool
Whether the system preference for Reduce Transparency is enabled.
var accessibilityShowButtonShapes: Bool
Whether the system preference for Show Button Shapes is enabled.
var accessibilitySwitchControlEnabled: Bool
A Boolean value that indicates whether the Switch Control motor accessibility feature is in use.
var accessibilityVoiceOverEnabled: Bool
A Boolean value that indicates whether the VoiceOver screen reader is in use.
var legibilityWeight: LegibilityWeight?
The font weight to apply to text.
Actions
var dismiss: DismissAction
An action that dismisses the current presentation.
var dismissSearch: DismissSearchAction
An action that ends the current search interaction.
var dismissWindow: DismissWindowAction
A window dismissal action stored in a view’s environment.
var openImmersiveSpace: OpenImmersiveSpaceAction
An action that presents an immersive space.
var dismissImmersiveSpace: DismissImmersiveSpaceAction
An immersive space dismissal action stored in a view’s environment.
var newDocument: NewDocumentAction
An action in the environment that presents a new document.
var openDocument: OpenDocumentAction
An action in the environment that presents an existing document.
var openURL: OpenURLAction
An action that opens a URL.
var openWindow: OpenWindowAction
A window presentation action stored in a view’s environment.
var pushWindow: PushWindowAction
var purchase: PurchaseAction
An action that starts an in-app purchase.
var refresh: RefreshAction?
A refresh action stored in a view’s environment.
var rename: RenameAction?
An action that activates the standard rename interaction.
var resetFocus: ResetFocusAction
An action that requests the focus system to reevaluate default focus.
var openSettings: OpenSettingsAction
A Settings presentation action stored in a view’s environment.
Authentication
var authorizationController: AuthorizationController
A value provided in the SwiftUI environment that views can use to perform authorization requests.
var webAuthenticationSession: WebAuthenticationSession
A value provided in the SwiftUI environment that views can use to authenticate a user through a web service.
Controls and input
var buttonRepeatBehavior: ButtonRepeatBehavior
Whether buttons with this associated environment should repeatedly trigger their actions on prolonged interactions.
var defaultWheelPickerItemHeight: CGFloat
The default height of an item in a wheel-style picker, such as a date picker.
var keyboardShortcut: KeyboardShortcut?
The keyboard shortcut that buttons in this environment will be triggered with.
var menuIndicatorVisibility: Visibility
The menu indicator visibility to apply to controls within a view.
var menuOrder: MenuOrder
The preferred order of items for menus presented from this view.
var searchSuggestionsPlacement: SearchSuggestionsPlacement
The current placement of search suggestions.
var preferredPencilDoubleTapAction: PencilPreferredAction
The action that the user prefers to perform after double-tapping their Apple Pencil, as selected in the Settings app.
var preferredPencilSqueezeAction: PencilPreferredAction
The action that the user prefers to perform when squeezing their Apple Pencil, as selected in the Settings app.
Display characteristics
var appearsActive: Bool
Whether views and styles in this environment should prefer an active appearance over an inactive appearance.
var colorScheme: ColorScheme
The color scheme of this environment.
var colorSchemeContrast: ColorSchemeContrast
The contrast associated with the color scheme of this environment.
var displayScale: CGFloat
The display scale of this environment.
var horizontalSizeClass: UserInterfaceSizeClass?
The horizontal size class of this environment.
var imageScale: Image.Scale
The image scale for this environment.
var pixelLength: CGFloat
The size of a pixel on the screen.
var sidebarRowSize: SidebarRowSize
The current size of sidebar rows.
var verticalSizeClass: UserInterfaceSizeClass?
The vertical size class of this environment.
var immersiveSpaceDisplacement: Pose3D
The displacement that the system applies to the immersive space when moving the space away from its default position, in meters.
var labelsVisibility: Visibility
The labels visibility set by labelsVisibility(_:).
var materialActiveAppearance: MaterialActiveAppearance
The behavior materials should use for their active state, defaulting to automatic.
struct TabBarPlacement
A placement for tabs in a tab view.
var toolbarLabelStyle: ToolbarLabelStyle?
The label style to apply to controls within a toolbar.
Global objects
var calendar: Calendar
The current calendar that views should use when handling dates.
var documentConfiguration: DocumentConfiguration?
The configuration of a document in a DocumentGroup.
var locale: Locale
The current locale that views should use.
var managedObjectContext: NSManagedObjectContext
var modelContext: ModelContext
The SwiftData model context that will be used for queries and other model operations within this environment.
var timeZone: TimeZone
The current time zone that views should use when handling dates.
var undoManager: UndoManager?
The undo manager used to register a view’s undo operations.
Scrolling
var isScrollEnabled: Bool
A Boolean value that indicates whether any scroll views associated with this environment allow scrolling to occur.
var horizontalScrollIndicatorVisibility: ScrollIndicatorVisibility
The visibility to apply to scroll indicators of any horizontally scrollable content.
var verticalScrollIndicatorVisibility: ScrollIndicatorVisibility
The visiblity to apply to scroll indicators of any vertically scrollable content.
var scrollDismissesKeyboardMode: ScrollDismissesKeyboardMode
The way that scrollable content interacts with the software keyboard.
var horizontalScrollBounceBehavior: ScrollBounceBehavior
The scroll bounce mode for the horizontal axis of scrollable views.
var verticalScrollBounceBehavior: ScrollBounceBehavior
The scroll bounce mode for the vertical axis of scrollable views.
State
An indication of whether the user can edit the contents of a view associated with this environment.
var isActivityFullscreen: Bool
A Boolean value that indicates whether the Live Activity appears in a full-screen presentation.
var isEnabled: Bool
A Boolean value that indicates whether the view associated with this environment allows user interaction.
var isFocused: Bool
Returns whether the nearest focusable ancestor has focus.
var isFocusEffectEnabled: Bool
A Boolean value that indicates whether the view associated with this environment allows focus effects to be displayed.
var isHoverEffectEnabled: Bool
A Boolean value that indicates whether the view associated with this environment allows hover effects to be displayed.
var isLuminanceReduced: Bool
A Boolean value that indicates whether the display or environment currently requires reduced luminance.
var isPresented: Bool
A Boolean value that indicates whether the view associated with this environment is currently presented.
var isSceneCaptured: Bool
The current capture state.
var isSearching: Bool
A Boolean value that indicates when the user is searching.
var isTabBarShowingSections: Bool
A Boolean value that determines whether a tab view shows the expanded contents of a tab section.
var scenePhase: ScenePhase
The current phase of the scene.
var supportsMultipleWindows: Bool
A Boolean value that indicates whether the current platform supports opening multiple windows.
StoreKit configuration
var displayStoreKitMessage: DisplayMessageAction
var requestReview: RequestReviewAction
Text styles
var allowsTightening: Bool
A Boolean value that indicates whether inter-character spacing should tighten to fit the text into the available space.
var autocorrectionDisabled: Bool
A Boolean value that determines whether the view hierarchy has auto-correction enabled.
var dynamicTypeSize: DynamicTypeSize
The current Dynamic Type size.
var font: Font?
The default font of this environment.
var layoutDirection: LayoutDirection
The layout direction associated with the current environment.
var lineLimit: Int?
The maximum number of lines that text can occupy in a view.
var lineSpacing: CGFloat
The distance in points between the bottom of one line fragment and the top of the next.
var minimumScaleFactor: CGFloat
The minimum permissible proportion to shrink the font size to fit the text into the available space.
var multilineTextAlignment: TextAlignment
An environment value that indicates how a text view aligns its lines when the content wraps or contains newlines.
var textCase: Text.Case?
A stylistic override to transform the case of Text when displayed, using the environment’s locale.
var truncationMode: Text.TruncationMode
A value that indicates how the layout truncates the last line of text to fit into the available space.
var textSelectionAffinity: TextSelectionAffinity
A representation of the direction or association of a selection or cursor relative to a text character. This concept becomes much more prominent when dealing with bidirectional text (text that contains both LTR and RTL scripts, like English and Arabic combined).
View attributes
var allowedDynamicRange: Image.DynamicRange?
The allowed dynamic range for the view, or nil.
var backgroundMaterial: Material?
The material underneath the current view.
var backgroundProminence: BackgroundProminence
The prominence of the background underneath views associated with this environment.
var backgroundStyle: AnyShapeStyle?
An optional style that overrides the default system background style when set.
var badgeProminence: BadgeProminence
The prominence to apply to badges associated with this environment.
var contentTransition: ContentTransition
The current method of animating the contents of views.
var contentTransitionAddsDrawingGroup: Bool
A Boolean value that controls whether views that render content transitions use GPU-accelerated rendering.
var defaultMinListHeaderHeight: CGFloat?
The default minimum height of a header in a list.
var defaultMinListRowHeight: CGFloat
The default minimum height of a row in a list.
var headerProminence: Prominence
The prominence to apply to section headers within a view.
var physicalMetrics: PhysicalMetricsConverter
The physical metrics associated with a scene.
var realityKitScene: Scene?
var realityViewCameraControls: CameraControls
The camera controls for the reality view.
var redactionReasons: RedactionReasons
The current redaction reasons applied to the view hierarchy.
var springLoadingBehavior: SpringLoadingBehavior
The behavior of spring loaded interactions for the views associated with this environment.
var symbolRenderingMode: SymbolRenderingMode?
The current symbol rendering mode, or nil denoting that the mode is picked automatically using the current image and foreground style as parameters.
var symbolVariants: SymbolVariants
The symbol variant to use in this environment.
The current limitations of the device tracking the user’s surroundings.
Widgets
var showsWidgetContainerBackground: Bool
An environment variable that indicates whether the background of a widget appears.
var showsWidgetLabel: Bool
A Boolean value that indicates whether an accessory family widget can display an accessory label.
var widgetFamily: WidgetFamily
The template of the widget — small, medium, or large.
var widgetRenderingMode: WidgetRenderingMode
The widget’s rendering mode, based on where the system is displaying it.
var widgetContentMargins: EdgeInsets
A property that identifies the content margins of a widget.
Deprecated environment values
var disableAutocorrection: Bool?
Deprecated
var sizeCategory: ContentSizeCategory
The size of content.
A binding to the current presentation mode of the view associated with this environment.
struct PresentationMode
An indication whether a view is currently presented by another view.
var complicationRenderingMode: ComplicationRenderingMode
The complication rendering mode for the current environment.
var controlActiveState: ControlActiveState
The active appearance expected of controls in a window.
Instance Properties
var activityFamily: ActivityFamily
The size family of the current Live Activity.
var buttonSizing: ButtonSizing Beta
var controlSize: ControlSize
The size to apply to controls within a view.
var credentialExportManager: ASCredentialExportManager
This environment variable is for SwiftUI clients of the credential exchange API. An example usage might look like:
Beta
var credentialImportManager: ASCredentialImportManager
var devicePickerSupports: DevicePickerSupportedAction
Checks for support to present a DevicePicker.
var findContext: FindContext? Beta
var fontResolutionContext: Font.Context
Information used to resolve a font.
var imagePlaygroundAllowedGenerationStyles: [ImagePlaygroundStyle]
var imagePlaygroundPersonalizationPolicy: ImagePlaygroundPersonalizationPolicy
var imagePlaygroundSelectedGenerationStyle: ImagePlaygroundStyle
var isActivityUpdateReduced: Bool
A Boolean value that indicates whether the Live Activity update synchronization rate is reduced.
var isUserAuthenticationEnabled: Bool
The current system user authentication enablement status.
var labelIconToTitleSpacing: CGFloat?
The spacing between the icon and title of a label.
var labelReservedIconWidth: CGFloat?
The width reserved for icons in labels.
var levelOfDetail: LevelOfDetail
The level of detail the view is recommended to have.
var lineHeight: AttributedString.LineHeight?
The default line height for text influenced by this environment.
var navigationLinkIndicatorVisibility: Visibility
A value that says whether a built-in navigation link would show a disclosure indicator in the current context.
var remoteDeviceIdentifier: RemoteDeviceIdentifier?
An opaque object that identifies the device on which the scene (from which this value is accessed from) is being presented on.
var requestAgeRange: DeclaredAgeRangeAction
The property in the environment for adoption of the age range API.
An environment value that that indicates potential rendered family for a Live Activity.
var supportsImagePlayground: Bool
A Boolean value that indicates whether image generation is available on the current device.
var supportsRemoteScenes: Bool
Indicates if the current device supports presenting a RemoteImmersiveSpace on a remote device.
var surfaceSnappingInfo: SurfaceSnappingInfo
Provides information about the current snap state of the scene.
var symbolColorRenderingMode: SymbolColorRenderingMode?
The property specifying how symbol images fill their layers, or nil to use the default fill style.
var symbolVariableValueMode: SymbolVariableValueMode?
The current symbol variable value mode, or nil denoting that the mode is picked automatically.
var tabBarPlacement: TabBarPlacement?
The current placement of the tab bar.
var tabViewBottomAccessoryPlacement: TabViewBottomAccessoryPlacement?
The current placement of the tab view bottom accessory.
var windowClippingMargins: EdgeInsets3D Beta
var writingToolsBehavior: WritingToolsBehavior?
The current Writing Tools behavior for text and text input.
Relationships
Conforms To
CustomStringConvertible
See Also
Accessing environment values
struct Environment
A property wrapper that reads a value from a view’s environment.
https://developer.apple.com/documentation/swiftui/entry()
#app-main)
- SwiftUI
- Entry()
Macro
Entry()
Creates an environment values, transaction, container values, or focused values entry.
@attached(accessor) @attached(peer, names: prefixed(_Key)) macro Entry()
Mentioned in
Building and customizing the menu bar with SwiftUI
Environment Values
Create EnvironmentValues entries by extending the EnvironmentValues structure with new properties and attaching the @Entry macro to the variable declarations:
extension EnvironmentValues { @Entry var myCustomValue: String = "Default value" @Entry var anotherCustomValue = true }
Transaction Values
Create Transaction entries by extending the Transaction structure with new properties and attaching the @Entry macro to the variable declarations:
extension Transaction { @Entry var myCustomValue: String = "Default value" }
Container Values
Create ContainerValues entries by extending the ContainerValues structure with new properties and attaching the @Entry macro to the variable declarations:
extension ContainerValues { @Entry var myCustomValue: String = "Default value" }
Focused Values
Since the default value for FocusedValues is always nil, FocusedValues entries cannot specify a different default value and must have an Optional type.
Create FocusedValues entries by extending the FocusedValues structure with new properties and attaching the @Entry macro to the variable declarations:
extension FocusedValues { @Entry var myCustomValue: String? }
See Also
Moving an animation to another view
Executes a closure with the specified transaction and returns the result.
Executes a closure with the specified transaction key path and value and returns the result.
Applies the given transaction mutation function to all animations used within the view.
Applies the given transaction mutation function to all animations used within the body closure.
struct Transaction
The context of the current state-processing update.
protocol TransactionKey
A key for accessing values in a transaction.
https://developer.apple.com/documentation/swiftui/environmentkey
- SwiftUI
- EnvironmentKey
Protocol
EnvironmentKey
A key for accessing values in the environment.
protocol EnvironmentKey
Overview
You can create custom environment values by extending the EnvironmentValues structure with new properties. First declare a new environment key type and specify a value for the required defaultValue property:
private struct MyEnvironmentKey: EnvironmentKey { static let defaultValue: String = "Default value" }
The Swift compiler automatically infers the associated Value type as the type you specify for the default value. Then use the key to define a new environment value property:
extension EnvironmentValues { var myCustomValue: String { get { self[MyEnvironmentKey.self] } set { self[MyEnvironmentKey.self] = newValue } } }
Clients of your environment value never use the key directly. Instead, they use the key path of your custom environment value property. To set the environment value for a view and all its subviews, add the environment(_:_:) view modifier to that view:
MyView() .environment(.myCustomValue, "Another string")
As a convenience, you can also define a dedicated view modifier to apply this environment value:
extension View {
environment(.myCustomValue, myCustomValue) } }
This improves clarity at the call site:
MyView() .myCustomValue("Another string")
To read the value from inside MyView or one of its descendants, use the Environment property wrapper:
struct MyView: View { @Environment(.myCustomValue) var customValue: String
var body: some View { Text(customValue) // Displays "Another string". } }
Topics
Getting the default value
static var defaultValue: Self.Value
The default value for the environment key.
Required
associatedtype Value
The associated type representing the type of the environment key’s value.
See Also
Creating custom environment values
macro Entry()
Creates an environment values, transaction, container values, or focused values entry.
https://developer.apple.com/documentation/swiftui/view/environment(_:)
#app-main)
- SwiftUI
- View
- environment(_:)
Instance Method
environment(_:)
Places an observable object in the view’s environment.
nonisolated
Parameters
object
The object to set for this object’s type in the environment, or nil to clear an object of this type from the environment.
Return Value
A view that has the specified object in its environment.
Discussion
Use this modifier to place an object that you declare with the Observable() macro into a view’s environment. For example, you can add an instance of a custom observable Profile class to the environment of a ContentView:
@Observable class Profile { ... }
struct RootView: View { @State private var currentProfile: Profile?
var body: some View { ContentView() .environment(currentProfile) } }
You then read the object inside ContentView or one of its descendants using the Environment property wrapper:
struct ContentView: View { @Environment(Profile.self) private var currentProfile: Profile
var body: some View { ... } }
This modifier affects the given view, as well as that view’s descendant views. It has no effect outside the view hierarchy on which you call it. The environment of a given view hierarchy holds only one observable object of a given type.
See Also
Modifying the environment of a view
Sets the environment value of the specified key path to the given value.
Transforms the environment value of the specified key path with the given function.
https://developer.apple.com/documentation/swiftui/view/transformenvironment(_:transform:)
#app-main)
- SwiftUI
- View
- transformEnvironment(_:transform:)
Instance Method
transformEnvironment(_:transform:)
Transforms the environment value of the specified key path with the given function.
nonisolated
See Also
Modifying the environment of a view
Places an observable object in the view’s environment.
Sets the environment value of the specified key path to the given value.
https://developer.apple.com/documentation/swiftui/scene/environment(_:)
#app-main)
- SwiftUI
- Scene
- environment(_:)
Instance Method
environment(_:)
Places an observable object in the scene’s environment.
nonisolated
Parameters
object
The object to set for this object’s type in the environment, or nil to clear an object of this type from the environment.
Return Value
A scene that has the specified object in its environment.
Discussion
Use this modifier to place an object that you declare with the Observable() macro into a scene’s environment. For example, you can add an instance of a custom observable Profile class to the environment of a WindowGroup scene:
@Observable class Profile { ... }
@main struct MyApp: App { var body: some View { WindowGroup { ContentView() } .environment(Profile.currentProfile) } }
You then read the object inside ContentView or one of its descendants using the Environment property wrapper:
struct ContentView: View { @Environment(Profile.self) private var currentProfile: Profile
var body: some View { ... } }
This modifier affects the given scene, as well as the scene’s descendant views. It has no effect outside the view hierarchy on which you call it. The environment of a given view hierarchy holds only one observable object of a given type.
See Also
Modifying the environment of a scene
Sets the environment value of the specified key path to the given value.
Transforms the environment value of the specified key path with the given function.
https://developer.apple.com/documentation/swiftui/scene/environment(::)
#app-main)
- SwiftUI
- Scene
- environment(_:_:)
Instance Method
environment(_:_:)
Sets the environment value of the specified key path to the given value.
nonisolated
_ value: V
Parameters
keyPath
A key path that indicates the property of the EnvironmentValues structure to update.
value
The new value to set for the item specified by keyPath.
Return Value
A view that has the given value set in its environment.
Discussion
Use this modifier to set one of the writable properties of the EnvironmentValues structure, including custom values that you create. For example, you can create a custom environment key styleOverrides to set a value that represents style settings that for the entire app:
WindowGroup { ContentView() } .environment(.styleOverrides, StyleOverrides())
You then read the value inside ContentView or one of its descendants using the Environment property wrapper:
struct MyView: View { @Environment(.styleOverrides) var styleOverrides: StyleOverrides
var body: some View { ... } }
This modifier affects the given scene, as well as that scene’s descendant views. It has no effect outside the view hierarchy on which you call it.
See Also
Modifying the environment of a scene
Places an observable object in the scene’s environment.
Transforms the environment value of the specified key path with the given function.
https://developer.apple.com/documentation/swiftui/scene/transformenvironment(_:transform:)
#app-main)
- SwiftUI
- Scene
- transformEnvironment(_:transform:)
Instance Method
transformEnvironment(_:transform:)
Transforms the environment value of the specified key path with the given function.
nonisolated
See Also
Modifying the environment of a scene
Places an observable object in the scene’s environment.
Sets the environment value of the specified key path to the given value.
https://developer.apple.com/documentation/swiftui/environment)
https://developer.apple.com/documentation/swiftui/view/environment(::))
https://developer.apple.com/documentation/swiftui/environmentvalues)
https://developer.apple.com/documentation/swiftui/entry())
https://developer.apple.com/documentation/swiftui/environmentkey)
https://developer.apple.com/documentation/swiftui/view/environment(_:))
https://developer.apple.com/documentation/swiftui/view/transformenvironment(_:transform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/scene/environment(_:))
https://developer.apple.com/documentation/swiftui/scene/environment(::))
https://developer.apple.com/documentation/swiftui/scene/transformenvironment(_:transform:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/state
https://developer.apple.com/documentation/swiftui/binding
- SwiftUI
- Binding
Structure
Binding
A property wrapper type that can read and write a value owned by a source of truth.
@frozen @propertyWrapper @dynamicMemberLookup
Mentioned in
Performing a search operation
Understanding the navigation stack
Adding a search interface to your app
Managing user interface state
Managing search interface activation
Overview
Use a binding to create a two-way connection between a property that stores data, and a view that displays and changes the data. A binding connects a property to a source of truth stored elsewhere, instead of storing data directly. For example, a button that toggles between play and pause can create a binding to a property of its parent view using the Binding property wrapper.
struct PlayButton: View { @Binding var isPlaying: Bool
var body: some View { Button(isPlaying ? "Pause" : "Play") { isPlaying.toggle() } } }
The parent view declares a property to hold the playing state, using the State property wrapper to indicate that this property is the value’s source of truth.
struct PlayerView: View { var episode: Episode @State private var isPlaying: Bool = false
var body: some View { VStack { Text(episode.title) .foregroundStyle(isPlaying ? .primary : .secondary) PlayButton(isPlaying: $isPlaying) // Pass a binding. } } }
When PlayerView initializes PlayButton, it passes a binding of its state property into the button’s binding property. Applying the $ prefix to a property wrapped value returns its projectedValue, which for a state property wrapper returns a binding to the value.
Whenever the user taps the PlayButton, the PlayerView updates its isPlaying state.
A binding conforms to Sendable only if its wrapped value type also conforms to Sendable. It is always safe to pass a sendable binding between different concurrency domains. However, reading from or writing to a binding’s wrapped value from a different concurrency domain may or may not be safe, depending on how the binding was created. SwiftUI will issue a warning at runtime if it detects a binding being used in a way that may compromise data safety.
Topics
Creating a binding
init(_:)
Creates a binding by projecting the base value to a hashable value.
Creates a binding from the value of another binding.
init(get:set:)
Creates a binding with closures that read and write the binding value.
Creates a binding with an immutable value.
Getting the value
var wrappedValue: Value
The underlying value referenced by the binding variable.
A projection of the binding value that returns a binding.
Returns a binding to the resulting value of a given key path.
Managing changes
var id: Value.ID
The stable identity of the entity associated with this instance, corresponding to the id of the binding’s wrapped value.
Specifies an animation to perform when the binding value changes.
Specifies a transaction for the binding.
var transaction: Transaction
The binding’s transaction.
Subscripts
subscript(_:) Beta
Relationships
Conforms To
-
BidirectionalCollection -
Collection -
Copyable -
DynamicPropertyConforms whenValueconforms toCopyableandEscapable. -
Identifiable -
RandomAccessCollection -
Sendable -
SendableMetatype -
Sequence
See Also
Creating and sharing view state
Encapsulate view-specific data within your app’s view hierarchy to make your views reusable.
struct State
A property wrapper type that can read and write a value managed by SwiftUI.
struct Bindable
A property wrapper type that supports creating bindings to the mutable properties of observable objects.
https://developer.apple.com/documentation/swiftui/managing-user-interface-state
- SwiftUI
- Model data
- Managing user interface state
Article
Managing user interface state
Encapsulate view-specific data within your app’s view hierarchy to make your views reusable.
Overview
Store data as state in the least common ancestor of the views that need the data to establish a single source of truth that’s shared across views. Provide the data as read-only through a Swift property, or create a two-way connection to the state with a binding. SwiftUI watches for changes in the data, and updates any affected views as needed.
Don’t use state properties for persistent storage because the life cycle of state variables mirrors the view life cycle. Instead, use them to manage transient state that only affects the user interface, like the highlight state of a button, filter settings, or the currently selected list item. You might also find this kind of storage convenient while you prototype, before you’re ready to make changes to your app’s data model.
Manage mutable values as state
If a view needs to store data that it can modify, declare a variable with the State property wrapper. For example, you can create an isPlaying Boolean inside a podcast player view to keep track of when a podcast is running:
struct PlayerView: View { @State private var isPlaying: Bool = false
var body: some View { // ... } }
Marking the property as state tells the framework to manage the underlying storage. Your view reads and writes the data, found in the state’s wrappedValue property, by using the property name. When you change the value, SwiftUI updates the affected parts of the view. For example, you can add a button to the PlayerView that toggles the stored value when tapped, and that displays a different image depending on the stored value:
Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle" : "play.circle") }
Limit the scope of state variables by declaring them as private. This ensures that the variables remain encapsulated in the view hierarchy that declares them.
Declare Swift properties to store immutable values
To provide a view with data that the view doesn’t modify, declare a standard Swift property. For example, you can extend the podcast player to have an input structure that contains strings for the episode title and the show name:
struct PlayerView: View { let episode: Episode // The queued episode. @State private var isPlaying: Bool = false
var body: some View { VStack { // Display information about the episode. Text(episode.title) Text(episode.showTitle)
Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle" : "play.circle") } } } }
While the value of the episode property is a constant for PlayerView, it doesn’t need to be constant in this view’s parent view. When the user selects a different episode in the parent, SwiftUI detects the state change and recreates the PlayerView with a new input.
Share access to state with bindings
If a view needs to share control of state with a child view, declare a property in the child with the Binding property wrapper. A binding represents a reference to existing storage, preserving a single source of truth for the underlying data. For example, if you refactor the podcast player view’s button into a child view called PlayButton, you can give it a binding to the isPlaying property:
struct PlayButton: View { @Binding var isPlaying: Bool
var body: some View { Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle" : "play.circle") } } }
As shown above, you read and write the binding’s wrapped value by referring directly to the property, just like state. But unlike a state property, the binding doesn’t have its own storage. Instead, it references a state property stored somewhere else, and provides a two-way connection to that storage.
When you instantiate PlayButton, provide a binding to the corresponding state variable declared in the parent view by prefixing it with the dollar sign ( $):
struct PlayerView: View { var episode: Episode @State private var isPlaying: Bool = false
var body: some View { VStack { Text(episode.title) Text(episode.showTitle) PlayButton(isPlaying: $isPlaying) // Pass a binding. } } }
The $ prefix asks a wrapped property for its projectedValue, which for state is a binding to the underlying storage. Similarly, you can get a binding from a binding using the $ prefix, allowing you to pass a binding through an arbitrary number of levels of view hierarchy.
You can also get a binding to a scoped value within a state variable. For example, if you declare episode as a state variable in the player’s parent view, and the episode structure also contains an isFavorite Boolean that you want to control with a toggle, then you can refer to $episode.isFavorite to get a binding to the episode’s favorite status:
struct Podcaster: View { @State private var episode = Episode(title: "Some Episode", showTitle: "Great Show", isFavorite: false) var body: some View { VStack { Toggle("Favorite", isOn: $episode.isFavorite) // Bind to the Boolean. PlayerView(episode: episode) } } }
Animate state transitions
When the view state changes, SwiftUI updates affected views right away. If you want to smooth visual transitions, you can tell SwiftUI to animate them by wrapping the state change that triggers them in a call to the withAnimation(_:_:) function. For example, you can animate changes controlled by the isPlaying Boolean:
withAnimation(.easeInOut(duration: 1)) { self.isPlaying.toggle() }
By changing isPlaying inside the animation function’s trailing closure, you tell SwiftUI to animate anything that depends on the wrapped value, like a scale effect on the button’s image:
Image(systemName: isPlaying ? "pause.circle" : "play.circle") .scaleEffect(isPlaying ? 1 : 1.5)
SwiftUI transitions the scale effect input over time between the given values of 1 and 1.5, using the curve and duration that you specify, or reasonable default values if you provide none. On the other hand, the image content isn’t affected by the animation, even though the same Boolean dictates which system image to display. That’s because SwiftUI can’t incrementally transition in a meaningful way between the two strings pause.circle and play.circle.
You can add animation to a state property, or as in the above example, to a binding. Either way, SwiftUI animates any view changes that happen when the underlying stored value changes. For example, if you add a background color to the PlayerView — at a level of view hierarchy above the location of the animation block — SwiftUI animates that as well:
VStack { Text(episode.title) Text(episode.showTitle) PlayButton(isPlaying: $isPlaying) } .background(isPlaying ? Color.green : Color.red) // Transitions with animation.
When you want to apply animations to specific views, rather than across all views triggered by a change in state, use the animation(_:value:) view modifier instead.
See Also
Creating and sharing view state
struct State
A property wrapper type that can read and write a value managed by SwiftUI.
struct Bindable
A property wrapper type that supports creating bindings to the mutable properties of observable objects.
struct Binding
A property wrapper type that can read and write a value owned by a source of truth.
https://developer.apple.com/documentation/swiftui/bindable
- SwiftUI
- Bindable
Structure
Bindable
A property wrapper type that supports creating bindings to the mutable properties of observable objects.
@dynamicMemberLookup @propertyWrapper
Overview
Use this property wrapper to create bindings to mutable properties of a data model object that conforms to the Observable protocol. For example, the following code wraps the book input with @Bindable. Then it uses a TextField to change the title property of a book, and a Toggle to change the isAvailable property, using the $ syntax to pass a binding for each property to those controls.
@Observable class Book: Identifiable { var title = "Sample Book Title" var isAvailable = true }
struct BookEditView: View { @Bindable var book: Book @Environment(.dismiss) private var dismiss
var body: some View { Form { TextField("Title", text: $book.title)
Toggle("Book is available", isOn: $book.isAvailable)
Button("Close") { dismiss() } } } }
You can use the Bindable property wrapper on properties and variables to an Observable object. This includes global variables, properties that exists outside of SwiftUI types, or even local variables. For example, you can create a @Bindable variable within a view’s body:
struct LibraryView: View { @State private var books = [Book(), Book(), Book()]
var body: some View { List(books) { book in @Bindable var book = book TextField("Title", text: $book.title) } } }
The @Bindable variable book provides a binding that connects TextField to the title property of a book so that a person can make changes directly to the model data.
Use this same approach when you need a binding to a property of an observable object stored in a view’s environment. For example, the following code uses the Environment property wrapper to retrieve an instance of the observable type Book. Then the code creates a @Bindable variable book and passes a binding for the title property to a TextField using the $ syntax.
struct TitleEditView: View { @Environment(Book.self) private var book
var body: some View { @Bindable var book = book TextField("Title", text: $book.title) } }
Topics
Creating a bindable value
init(Value)
Creates a bindable object from an observable object.
init(wrappedValue: Value)
Creates a bindable from the value of another bindable.
Getting the value
var wrappedValue: Value
The wrapped object.
The bindable wrapper for the object that creates bindings to its properties using dynamic member lookup.
Returns a binding to the value of a given key path.
Relationships
Conforms To
CopyableIdentifiableSendableSendableMetatype
See Also
Creating and sharing view state
Managing user interface state
Encapsulate view-specific data within your app’s view hierarchy to make your views reusable.
struct State
A property wrapper type that can read and write a value managed by SwiftUI.
struct Binding
A property wrapper type that can read and write a value owned by a source of truth.
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
- SwiftUI
- Model data
- Managing model data in your app
Sample Code
Managing model data in your app
Create connections between your app’s data model and views.
Download
Xcode 15.0+
Overview
A SwiftUI app can display data that people can change using the app’s user interface (UI). To manage that data, an app creates a data model, which is a custom type that represents the data. A data model provides separation between the data and the views that interact with the data. This separation promotes modularity, improves testability, and helps make it easier to reason about how the app works.
Keeping the model data (that is, an instance of a data model) in sync with what appears on the screen can be challenging, especially when the data appears in multiple views of the UI at the same time.
SwiftUI helps keep your app’s UI up to date with changes made to the data thanks to Observation. With Observation, a view in SwiftUI can form dependencies on observable data models and update the UI when data changes.
Make model data observable
To make data changes visible to SwiftUI, apply the Observable() macro to your data model. This macro generates code that adds observation support to your data model at compile time, keeping your data model code focused on the properties that store data. For example, the following code defines a data model for books:
@Observable class Book: Identifiable { var title = "Sample Book Title" var author = Author() var isAvailable = true }
Observe model data in a view
In SwiftUI, a view forms a dependency on an observable data model object, such as an instance of Book, when the view’s body property reads a property of the object. If body doesn’t read any properties of an observable data model object, the view doesn’t track any dependencies.
When a tracked property changes, SwiftUI updates the view. If other properties change that body doesn’t read, the view is unaffected and avoids unnecessary updates. For example, the view in the following code updates only when a book’s title changes but not when author or isAvailable changes:
struct BookView: View { var book: Book
var body: some View { Text(book.title) } }
SwiftUI establishes this dependency tracking even if the view doesn’t store the observable type, such as when using a global property or singleton:
var globalBook: Book = Book()
struct BookView: View { var body: some View { Text(globalBook.title) } }
Observation also supports tracking of computed properties when the computed property makes use of an observable property. For instance, the view in the following code updates when the number of available books changes:
@Observable class Library { var books: [Book] = [Book(), Book(), Book()]
var availableBooksCount: Int { books.filter(.isAvailable).count } }
struct LibraryView: View { @Environment(Library.self) private var library
var body: some View { NavigationStack { List(library.books) { book in // ... } .navigationTitle("Books available: (library.availableBooksCount)") } } }
When a view forms a dependency on a collection of objects, of any collection type, the view tracks changes made to the collection itself. For instance, the view in the following code forms a dependency on books because body reads it. As changes occur to books, such as inserting, deleting, moving, or replacing items in the collection, SwiftUI updates the view.
struct LibraryView: View { @State private var books = [Book(), Book(), Book()]
var body: some View { List(books) { book in Text(book.title) } } }
However, LibraryView doesn’t form a dependency on the property title because the view’s body doesn’t read it directly. The view stores the List content closure as an @escaping closure that SwiftUI calls when lazily creating list items before they appear on the screen. This means that instead of LibraryView depending on a book’s title, each Text item of the list depends on title. Any changes to a title updates only the individual Text representing the book and not the others.
You can also share an observable model data object with another view. The receiving view forms a dependency if it reads any properties of the object in the its body. For example, in the following code LibraryView shares an instance of Book with BookView, and BookView displays the book’s title. If the book’s title changes, SwiftUI updates only BookView, and not LibraryView, because only BookView reads the title property.
var body: some View { List(books) { book in BookView(book: book) } } }
If a view doesn’t have any dependencies, SwiftUI doesn’t update the view when data changes. This approach allows an observable model data object to pass through multiple layers of a view hierarchy without each intermediate view forming a dependency.
// Will not update when any property of book changes.
struct LibraryView: View {
@State private var books = [Book(), Book(), Book()]
var body: some View { LibraryItemView(book: book) } }
// Will not update when any property of book changes.
struct LibraryItemView: View {
var book: Book
var body: some View { BookView(book: book) } }
// Will update when book.title changes.
struct BookView: View {
var book: Book
However, a view that stores a reference to the observable object updates if the reference changes. This happens because the stored reference is part of the view’s value and not because the object is observable. For example, if the reference to book in the follow code changes, SwiftUI updates the view:
var body: some View { // ... } }
A view can also form a dependency on an observable data model object accessed through another object. For example, the view in the following code updates when the author’s name changes:
struct LibraryItemView: View { var book: Book
var body: some View { VStack(alignment: .leading) { Text(book.title) Text("Written by: (book.author.name)") .font(.caption) } } }
Create the source of truth for model data
To create and store the source of truth for model data, declare a private variable and initialize it with a instance of an observable data model type. Then wrap it with a State property wrapper. For example, the following code stores an instance of the data model type Book in the state variable book:
struct BookView: View { @State private var book = Book()
By wrapping the book with State, you’re telling SwiftUI to manage the storage of the instance. Each time SwiftUI re-creates BookView, it connects the book variable to the managed instance, providing the view a single source of truth for the model data.
You can also create a state object in your top-level App instance or in one of your app’s Scene instances. For example, the following code creates an instance of Library in the app’s top-level structure:
@main struct BookReaderApp: App { @State private var library = Library()
var body: some Scene { WindowGroup { LibraryView() .environment(library) } } }
Share model data throughout a view hierarchy
If you have a data model object, like Library, that you want to share throughout your app, you can either:
-
pass the data model object to each view in the view hierarchy; or
-
add the data model object to the view’s environment
Passing model data to each view is convenient when you have a shallow view hierarchy; for example, when a view doesn’t share the object with its subviews. However, you usually don’t know if a view needs to pass the object to subviews, and you may not know if a subview deep inside the layers of the hierarchy needs the model data.
To share model data throughout a view hierarchy without needing to pass it to each view, add the model data to the view’s environment. You can add the data to the environment using either environment(_:_:) or the environment(_:) modifier, passing in the model data.
Before you can use the environment(_:_:) modifier, you need to create a custom EnvironmentKey. Then extend EnvironmentValues to include a custom environment property that gets and sets the value for the custom key. For instance, the following code creates an environment key and property for library:
extension EnvironmentValues { var library: Library { get { self[LibraryKey.self] } set { self[LibraryKey.self] = newValue } } }
private struct LibraryKey: EnvironmentKey { static let defaultValue: Library = Library() }
With the custom environment key and property in place, a view can add model data to its environment. For example, LibraryView adds the source of truth for a Library instance to its environment using the environment(_:_:) modifier:
var body: some Scene { WindowGroup { LibraryView() .environment(.library, library) } } }
To retrieve the Library instance from the environment, a view defines a local variable that stores a reference to the instance, and then wraps the variable with the Environment property wrapper, passing in the key path to the custom environment value.
struct LibraryView: View { @Environment(.library) private var library
You can also store model data directly in the environment without defining a custom environment value by using the environment(_:) modifier. For instance, the following code adds a Library instance to the environment using this modifier:
To retrieve the instance from the environment, another view defines a local variable to store the instance and wraps it with the Environment property wrapper. But instead of providing a key path to the environment value, you can provide the model data type, as shown in the following code:
By default, reading an object from the environment returns a non-optional object when using the object type as the key. This default behavior assumes that a view in the current hierarchy previously stored a non-optional instance of the type using the environment(_:) modifier. If a view attempts to retrieve an object using its type and that object isn’t in the environment, SwiftUI throws exception.
In cases where there is no guarantee that an object is in the environment, retrieve an optional version of the object as shown in the following code. If the object isn’t available the environment, SwiftUI returns nil instead of throwing an exception.
@Environment(Library.self) private var library: Library?
Change model data in a view
In most apps, people can change data that the app presents. When data changes, any views that display the data should update to reflect the changed data. With Observation in SwiftUI, a view can support data changes without using property wrappers or bindings. For example, the following toggles the isAvailable property of a book in the action closure of a button:
var body: some View { List { Text(book.title) HStack { Text(book.isAvailable ? "Available for checkout" : "Waiting for return") Spacer() Button(book.isAvailable ? "Check out" : "Return") { book.isAvailable.toggle() } } } } }
However, there may be times when a view expects a binding before it can change the value of a mutable property. To provide a binding, wrap the model data with the Bindable property wrapper. For example, the following code wraps the book variable with @Bindable. Then it uses a TextField to change the title property of a book, and a Toggle to change the isAvailable property, using the $ syntax to pass a binding to each property.
struct BookEditView: View { @Bindable var book: Book @Environment(.dismiss) private var dismiss
var body: some View { VStack() { HStack { Text("Title") TextField("Title", text: $book.title) .textFieldStyle(.roundedBorder) .onSubmit { dismiss() } }
Toggle(isOn: $book.isAvailable) { Text("Book is available") }
Button("Close") { dismiss() } .buttonStyle(.borderedProminent) } .padding() } }
You can use the Bindable property wrapper on properties and variables to an Observable object. This includes global variables, properties that exists outside of SwiftUI types, or even local variables. For example, you can create a @Bindable variable within a view’s body:
var body: some View { List(books) { book in @Bindable var book = book TextField("Title", text: $book.title) } } }
The @Bindable variable book provides a binding that connects TextField to the title property of a book so that a person can make changes directly to the model data.
See Also
Creating model data
Migrating from the Observable Object protocol to the Observable macro
Update your existing app to leverage the benefits of Observation in Swift.
@attached(member, names: named(_$observationRegistrar), named(access), named(withMutation), named(shouldNotifyObservers)) @attached(memberAttribute) @attached(extension, conformances: Observable) macro Observable()
Defines and implements conformance of the Observable protocol.
Monitoring data changes in your app
Show changes to data in your app’s user interface by using observable objects.
struct StateObject
A property wrapper type that instantiates an observable object.
struct ObservedObject
A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.
protocol ObservableObject : AnyObject
A type of object with a publisher that emits before the object has changed.
https://developer.apple.com/documentation/swiftui/migrating-from-the-observable-object-protocol-to-the-observable-macro
- SwiftUI
- Model data
- Migrating from the Observable Object protocol to the Observable macro
Sample Code
Migrating from the Observable Object protocol to the Observable macro
Update your existing app to leverage the benefits of Observation in Swift.
Download
Xcode 15.0+
Overview
Starting with iOS 17, iPadOS 17, macOS 14, tvOS 17, and watchOS 10, SwiftUI provides support for Observation, a Swift-specific implementation of the observer design pattern. Adopting Observation provides your app with the following benefits:
-
Tracking optionals and collections of objects, which isn’t possible when using
ObservableObject. -
Using existing data flow primitives like
StateandEnvironmentinstead of object-based equivalents such asStateObjectandEnvironmentObject. -
Updating views based on changes to the observable properties that a view’s
bodyreads instead of any property changes that occur to an observable object, which can help improve your app’s performance.
To take advantage of these benefits in your app, you’ll discover how to replace existing source code that relies on ObservableObject with code that leverages the Observable() macro.
Use the Observable macro
To adopt Observation in an existing app, begin by replacing ObservableObject in your data model type with the Observable() macro. The Observable() macro generates source code at compile time that adds observation support to the type.
// BEFORE import SwiftUI
class Library: ObservableObject { // ... }
// AFTER import SwiftUI
@Observable class Library { // ... }
Then remove the Published property wrapper from observable properties. Observation doesn’t require a property wrapper to make a property observable. Instead, the accessibility of the property in relationship to an observer, such as a view, determines whether a property is observable.
// BEFORE @Observable class Library { @Published var books: [Book] = [Book(), Book(), Book()] }
// AFTER @Observable class Library { var books: [Book] = [Book(), Book(), Book()] }
If you have properties that are accessible to an observer that you don’t want to track, apply the ObservationIgnored() macro to the property.
Migrate incrementally
You don’t need to make a wholesale replacement of the ObservableObject protocol throughout your app. Instead, you can make changes incrementally. Start by changing one data model type to use the Observable() macro. Your app can mix data model types that use different observation systems. However, SwiftUI tracks changes differently based on the observation system that a data model type uses, Observable versus ObservableObject.
You may notice slight behavioral differences in your app based on the tracking method. For instance, when tracking as Observable(), SwiftUI updates a view only when an observable property changes and the view’s body reads the property directly. The view doesn’t update when observable properties not read by body changes. In contrast, a view updates when any published property of an ObservableObject instance changes, even if the view doesn’t read the property that changes, when tracking as ObservableObject.
Migrate other source code
The only change made to the sample app so far is to apply the Observable() macro to Library and remove support for the ObservableObject protocol. The app still uses the ObservableObject data flow primitive like StateObject to manage an instance of Library. If you were to build and run the app, SwiftUI still updates the views as expected. That’s because data flow property wrappers such as StateObject and EnvironmentObject support types that use the Observable() macro. SwiftUI provides this support so apps can make source code changes incrementally.
However, to fully adopt Observation, replace the use of StateObject with State after updating your data model type. For example, in the following code the main app structure creates an instance of Library and stores it as a StateObject. It also adds the Library instance to the environment using the environmentObject(_:) modifier.
// BEFORE @main struct BookReaderApp: App { @StateObject private var library = Library()
var body: some Scene { WindowGroup { LibraryView() .environmentObject(library) } } }
Now that Library no longer conforms to ObservableObject, the code can change to use State instead of StateObject and to add library to the environment using the environment(_:) modifier.
// AFTER @main struct BookReaderApp: App { @State private var library = Library()
var body: some Scene { WindowGroup { LibraryView() .environment(library) } } }
One more change must happen before Library fully adopts Observation. Previously the view LibraryView retrieved a Library instance from the environment using the EnvironmentObject property wrapper. The new code, however, uses the Environment property wrapper instead.
// BEFORE struct LibraryView: View { @EnvironmentObject var library: Library
var body: some View { List(library.books) { book in BookView(book: book) } } }
// AFTER struct LibraryView: View { @Environment(Library.self) private var library
Remove the ObservedObject property wrapper
To wrap up the migration of the sample app, change the data model type Book to support Observation by removing ObservableObject from the type declaration and apply the Observable() macro. Then remove the Published property wrapper from observable properties.
// BEFORE class Book: ObservableObject, Identifiable { @Published var title = "Sample Book Title"
let id = UUID() // A unique identifier that never changes. }
// AFTER @Observable class Book: Identifiable { var title = "Sample Book Title"
Next, remove the ObservedObject property wrapper from the book variable in the BookView. This property wrapper isn’t needed when adopting Observation. That’s because SwiftUI automatically tracks any observable properties that a view’s body reads directly. For example, SwiftUI updates BookView when book.title changes.
// BEFORE struct BookView: View { @ObservedObject var book: Book @State private var isEditorPresented = false
var body: some View { HStack { Text(book.title) Spacer() Button("Edit") { isEditorPresented = true } } .sheet(isPresented: $isEditorPresented) { BookEditView(book: book) } } }
// AFTER struct BookView: View { var book: Book @State private var isEditorPresented = false
However, if a view needs a binding to an observable type, replace ObservedObject with the Bindable property wrapper. This property wrapper provides binding support to an observable type so that views that expect a binding can change an observable property. For instance, in the following code TextField receives a binding to book.title:
// BEFORE struct BookEditView: View { @ObservedObject var book: Book @Environment(.dismiss) private var dismiss
var body: some View { VStack() { TextField("Title", text: $book.title) .textFieldStyle(.roundedBorder) .onSubmit { dismiss() }
Button("Close") { dismiss() } .buttonStyle(.borderedProminent) } .padding() } }
// AFTER struct BookEditView: View { @Bindable var book: Book @Environment(.dismiss) private var dismiss
See Also
Creating model data
Managing model data in your app
Create connections between your app’s data model and views.
@attached(member, names: named(_$observationRegistrar), named(access), named(withMutation), named(shouldNotifyObservers)) @attached(memberAttribute) @attached(extension, conformances: Observable) macro Observable()
Defines and implements conformance of the Observable protocol.
Monitoring data changes in your app
Show changes to data in your app’s user interface by using observable objects.
struct StateObject
A property wrapper type that instantiates an observable object.
struct ObservedObject
A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.
protocol ObservableObject : AnyObject
A type of object with a publisher that emits before the object has changed.
https://developer.apple.com/documentation/swiftui/monitoring-model-data-changes-in-your-app
- SwiftUI
- Model data
- Monitoring data changes in your app
Sample Code
Monitoring data changes in your app
Show changes to data in your app’s user interface by using observable objects.
Download
Xcode 14.3+
Overview
You typically store and process data in your app using a data model that’s separate from your app’s user interface (UI) and other logic. The separation promotes modularity, improves testability, and makes it easier to reason about how your app works.
Traditionally, you use a view controller to move data back and forth between the model and the UI, but SwiftUI handles most of this synchronization for you. To update views when data changes, you make your data model classes observable objects, publish their properties, and declare instances of them using property wrappers. To ensure user-driven data changes flow back into the model, you bind UI controls to model properties. Working together, these features help you to maintain a single source of truth for your data.
Make model data observable
To make the data changes in your model visible to SwiftUI, adopt the ObservableObject protocol for model classes. For example, you can create a Book class that’s an observable object:
class Book: ObservableObject { }
The system automatically infers the ObjectWillChangePublisher associated type for the class and synthesizes the required doc://com.apple.documentation/documentation/Combine/ObservableObject/objectWillChange-2oa5v method that emits the changed values of published properties. To publish a property, add the Published property wrapper to the property’s declaration:
class Book: ObservableObject { @Published var title = "Sample Book Title" }
Avoid the overhead of a published property when you don’t need it. Only publish properties that both can change and that matter to the UI. For example, the Book class might have an identifier property that never changes after initialization:
class Book: ObservableObject { @Published var title = "Sample Book Title"
let identifier = UUID() // A unique identifier that never changes. }
You can still display the identifier in your user interface, but because it isn’t published, SwiftUI doesn’t watch that particular property for changes.
Monitor changes in observable objects
To tell SwiftUI to monitor an observable object, add the ObservedObject property wrapper to the property’s declaration:
struct BookView: View { @ObservedObject var book: Book
var body: some View { Text(book.title) } }
You can pass individual properties of an observed object to child views, as shown above. When the data changes, like when you load new data from disk, SwiftUI updates all the affected views. You can also pass an entire observable object to a child view and share model objects across levels of a view hierarchy:
var body: some View { BookEditView(book: book) } }
struct BookEditView: View { @ObservedObject var book: Book
// ... }
Instantiate a model object in a view
SwiftUI might create or recreate a view at any time, so it’s important that initializing a view with a given set of inputs always results in the same view. As a result, it’s unsafe to create an observed object inside a view. Instead, SwiftUI provides the StateObject property wrapper, which creates a single source of truth for a reference type that you store in a view hierarchy. You can safely create a Book instance inside a view this way:
struct LibraryView: View { @StateObject private var book = Book()
var body: some View { BookView(book: book) } }
A state object behaves like an observed object, except that SwiftUI creates and manages a single object instance for a given view instance, regardless of how many times it recreates the view. You can use the object locally, or pass the state object into another view’s observed object property, as shown in the above example.
While SwiftUI doesn’t recreate the state object within a view, it does create a distinct object instance for each view instance. For example, each LibraryView in the following code gets a unique Book instance:
VStack { LibraryView() LibraryView() }
You can also create a state object in your top level App instance, or in one of your app’s Scene instances. For example, if you define an observable object called Library to hold a collection of books for a book reader app, you could create a single library instance in the app’s top level structure:
@main struct BookReader: App { @StateObject private var library = Library()
Share an object throughout your app
If you have a data model object that you want to use throughout your app, but don’t want to pass it through many layers of hierarchy, you can use the environmentObject(_:) view modifier to put the object into the environment instead:
var body: some Scene { WindowGroup { LibraryView() .environmentObject(library) } } }
Any descendant view of the view to which you apply the modifier can then access the data model instance by declaring a property with the EnvironmentObject property wrapper:
struct LibraryView: View { @EnvironmentObject var library: Library
If you use an environment object, you might add it to the view at the top of your app’s hierarchy, as shown above. Alternatively, you might add it to the root view of a subtree in your view hierarchy. Either way, remember to also add it to the preview provider of any view that uses the object, or that has a descendant that uses the object:
struct LibraryView_Previews: PreviewProvider { static var previews: some View { LibraryView() .environmentObject(Library()) } }
Create a two-way connection using bindings
When you allow a person to change the data in the UI, use a binding to the corresponding property. This ensures that updates flow back into the data model automatically. You can get a binding to an observed object, state object, or environment object property by prefixing the name of the object with the dollar sign ( $). For example, if you let someone edit the title of a book by adding a TextField to the BookEditView, give the text field a binding to the book’s title property:
var body: some View { TextField("Title", text: $book.title) } }
The binding connects the view element to the underlying model so that a person makes changes directly to the model data.
See Also
Creating model data
Managing model data in your app
Create connections between your app’s data model and views.
Migrating from the Observable Object protocol to the Observable macro
Update your existing app to leverage the benefits of Observation in Swift.
@attached(member, names: named(_$observationRegistrar), named(access), named(withMutation), named(shouldNotifyObservers)) @attached(memberAttribute) @attached(extension, conformances: Observable) macro Observable()
Defines and implements conformance of the Observable protocol.
struct StateObject
A property wrapper type that instantiates an observable object.
struct ObservedObject
A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.
protocol ObservableObject : AnyObject
A type of object with a publisher that emits before the object has changed.
https://developer.apple.com/documentation/swiftui/view/onchange(of:initial:_:)
#app-main)
- SwiftUI
- View
- onChange(of:initial:_:)
Instance Method
onChange(of:initial:_:)
Adds a modifier for this view that fires an action when a specific value changes.
nonisolated
of value: V, initial: Bool = false,
Show all declarations
Parameters
value
The value to check against when determining whether to run the closure.
initial
Whether the action should be run when this view initially appears.
action
A closure to run when the value changes.
Return Value
A view that fires an action when the specified value changes.
Mentioned in
Understanding the navigation stack
Discussion
You can use onChange to trigger a side effect as the result of a value changing, such as an Environment key or a Binding.
The system may call the action closure on the main actor, so avoid long-running tasks in the closure. If you need to perform such tasks, detach an asynchronous background task.
When the value changes, the new version of the closure will be called, so any captured values will have their values from the time that the observed value has its new value. In the following code example, PlayerView calls into its model when playState changes model.
struct PlayerView: View { var episode: Episode @State private var playState: PlayState = .paused
var body: some View { VStack { Text(episode.title) Text(episode.showTitle) PlayButton(playState: $playState) } .onChange(of: playState) { model.playStateDidChange(state: playState) } } }
See Also
Responding to data changes
Adds an action to perform when this view detects data emitted by the given publisher.
https://developer.apple.com/documentation/swiftui/view/onreceive(_:perform:)
https://developer.apple.com/documentation/swiftui/view/environmentobject(_:)
#app-main)
- SwiftUI
- View
- environmentObject(_:)
Instance Method
environmentObject(_:)
Supplies an observable object to a view’s hierarchy.
nonisolated
Parameters
object
The object to store and make available to the view’s hierarchy.
Discussion
Use this modifier to add an observable object to a view’s environment. The object must conform to the ObservableObject protocol.
Adding an object to a view’s environment makes the object available to subviews in the view’s hierarchy. To retrieve the object in a subview, use the EnvironmentObject property wrapper.
See Also
Distributing model data throughout your app
Supplies an ObservableObject to a view subhierarchy.
struct EnvironmentObject
A property wrapper type for an observable object that a parent or ancestor view supplies.
https://developer.apple.com/documentation/swiftui/scene/environmentobject(_:)
#app-main)
- SwiftUI
- Scene
- environmentObject(_:)
Instance Method
environmentObject(_:)
Supplies an ObservableObject to a view subhierarchy.
nonisolated
Parameters
object
The object to store and make available to the scene’s subhierarchy.
Discussion
The object can be read by any child by using EnvironmentObject:
final class Profile: ObservableObject { ... }
@main struct MyApp: App { var body: some View { WindowGroup { ContentView() } .environment(ProfileService.currentProfile) } }
You then read the object inside ContentView or one of its descendants using the EnvironmentObject property wrapper:
struct ContentView: View { @EnvironmentObject private var currentAccount: Account
var body: some View { ... } }
See Also
Distributing model data throughout your app
Supplies an observable object to a view’s hierarchy.
struct EnvironmentObject
A property wrapper type for an observable object that a parent or ancestor view supplies.
https://developer.apple.com/documentation/swiftui/dynamicproperty
- SwiftUI
- DynamicProperty
Protocol
DynamicProperty
An interface for a stored variable that updates an external property of a view.
protocol DynamicProperty
Overview
The view gives values to these properties prior to recomputing the view’s body.
Topics
Updating the value
func update()
Updates the underlying value of the stored value.
Required Default implementation provided.
Relationships
Conforming Types
-
AccessibilityFocusState -
AppStorage -
BindingConforms whenValueconforms toCopyableandEscapable. -
Environment -
EnvironmentObject -
FetchRequestConforms whenResultconforms toNSFetchRequestResult. -
FocusState -
FocusedBinding -
FocusedObject -
FocusedValue -
GestureState -
NSApplicationDelegateAdaptor -
Namespace -
ObservedObject -
PhysicalMetric -
ScaledMetric -
SceneStorage -
SectionedFetchRequestConforms whenSectionIdentifierconforms toHashableandResultconforms toNSFetchRequestResult. -
State -
StateObject -
UIApplicationDelegateAdaptor -
WKApplicationDelegateAdaptor -
WKExtensionDelegateAdaptor
https://developer.apple.com/documentation/swiftui/state)
https://developer.apple.com/documentation/swiftui/binding)
https://developer.apple.com/documentation/swiftui/binding),
https://developer.apple.com/documentation/swiftui/managing-user-interface-state)
https://developer.apple.com/documentation/swiftui/bindable)
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app)
https://developer.apple.com/documentation/swiftui/migrating-from-the-observable-object-protocol-to-the-observable-macro)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/monitoring-model-data-changes-in-your-app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/onchange(of:initial:_:))
https://developer.apple.com/documentation/swiftui/view/onreceive(_:perform:))
https://developer.apple.com/documentation/swiftui/view/environmentobject(_:))
https://developer.apple.com/documentation/swiftui/scene/environmentobject(_:))
https://developer.apple.com/documentation/swiftui/dynamicproperty)
https://developer.apple.com/documentation/swiftui/widget
- SwiftUI
- Widget
Protocol
Widget
The configuration and content of a widget to display on the Home screen or in Notification Center.
@MainActor @preconcurrency protocol Widget
Overview
Widgets show glanceable and relevant content from your app right on the iOS Home screen or in Notification Center on macOS. Users can add, configure, and arrange widgets to suit their individual needs. You can provide multiple types of widgets, each presenting a specific kind of information. When users want more information, like to read the full article for a headline or to see the details of a package delivery, the widget lets them get to the information in your app quickly.
There are three key components to a widget:
-
A configuration that determines whether the widget is configurable, identifies the widget, and defines the SwiftUI views that show the widget’s content.
-
A timeline provider that drives the process of updating the widget’s view over time.
-
SwiftUI views used by WidgetKit to display the widget.
For information about adding a widget extension to your app, and keeping your widget up to date, see Creating a widget extension and Keeping a widget up to date, respectively.
By adding a custom SiriKit intent definition, you can let users customize their widgets to show the information that’s most relevant to them. If you’ve already added support for Siri or Shortcuts, you’re well on your way to supporting customizable widgets. For more information, see Making a configurable widget.
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is included in the type’s base declaration:
struct MyCustomType: Transition {
// @preconcurrency @MainActor isolation by default
}
Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt out of main actor isolation:
extension MyCustomType: Transition {
// nonisolated by default
}
Topics
Implementing a widget
var body: Self.Body
The content and behavior of the widget.
Required
associatedtype Body : WidgetConfiguration
The type of configuration representing the content of the widget.
Running a widget
init()
Creates a widget using body as its content.
static func main()
Initializes and runs the widget.
See Also
Creating widgets
Building Widgets Using WidgetKit and SwiftUI
Create widgets to show your app’s content on the Home screen, with custom intents for user-customizable settings.
Creating a widget extension
Display your app’s content in a convenient, informative widget on various devices.
Keeping a widget up to date
Plan your widget’s timeline to show timely, relevant information using dynamic views, and update the timeline when things change.
Making a configurable widget
Give people the option to customize their widgets by adding a custom app intent to your project.
protocol WidgetBundle
A container used to expose multiple widgets from a single widget extension.
struct LimitedAvailabilityConfiguration
A type-erased widget configuration.
protocol WidgetConfiguration
A type that describes a widget’s content.
struct EmptyWidgetConfiguration
An empty widget configuration.
https://developer.apple.com/documentation/swiftui/widgetbundle
- SwiftUI
- WidgetBundle
Protocol
WidgetBundle
A container used to expose multiple widgets from a single widget extension.
@MainActor @preconcurrency protocol WidgetBundle
Overview
To support multiple types of widgets, add the @main attribute to a structure that conforms to WidgetBundle. For example, a game might have one widget to display summary information about the game and a second widget to display detailed information about individual characters.
@main struct GameWidgets: WidgetBundle { var body: some Widget { GameStatusWidget() CharacterDetailWidget() } }
Topics
Implementing a widget bundle
var body: Self.Body
Declares the group of widgets that an app supports.
Required
associatedtype Body : Widget
The type of widget that represents the content of the bundle.
struct WidgetBundleBuilder
A custom attribute that constructs a widget bundle’s body.
Running a widget bundle
init()
Creates a widget bundle using the bundle’s body as its content.
static func main()
Initializes and runs the widget bundle.
See Also
Creating widgets
Building Widgets Using WidgetKit and SwiftUI
Create widgets to show your app’s content on the Home screen, with custom intents for user-customizable settings.
Creating a widget extension
Display your app’s content in a convenient, informative widget on various devices.
Keeping a widget up to date
Plan your widget’s timeline to show timely, relevant information using dynamic views, and update the timeline when things change.
Making a configurable widget
Give people the option to customize their widgets by adding a custom app intent to your project.
protocol Widget
The configuration and content of a widget to display on the Home screen or in Notification Center.
struct LimitedAvailabilityConfiguration
A type-erased widget configuration.
protocol WidgetConfiguration
A type that describes a widget’s content.
struct EmptyWidgetConfiguration
An empty widget configuration.
https://developer.apple.com/documentation/swiftui/limitedavailabilityconfiguration
- SwiftUI
- LimitedAvailabilityConfiguration
Structure
LimitedAvailabilityConfiguration
A type-erased widget configuration.
@MainActor @frozen @preconcurrency struct LimitedAvailabilityConfiguration
Overview
You don’t use this type directly. Instead SwiftUI creates this type on your behalf.
Relationships
Conforms To
WidgetConfiguration
See Also
Creating widgets
Building Widgets Using WidgetKit and SwiftUI
Create widgets to show your app’s content on the Home screen, with custom intents for user-customizable settings.
Creating a widget extension
Display your app’s content in a convenient, informative widget on various devices.
Keeping a widget up to date
Plan your widget’s timeline to show timely, relevant information using dynamic views, and update the timeline when things change.
Making a configurable widget
Give people the option to customize their widgets by adding a custom app intent to your project.
protocol Widget
The configuration and content of a widget to display on the Home screen or in Notification Center.
protocol WidgetBundle
A container used to expose multiple widgets from a single widget extension.
protocol WidgetConfiguration
A type that describes a widget’s content.
struct EmptyWidgetConfiguration
An empty widget configuration.
https://developer.apple.com/documentation/swiftui/widgetconfiguration
- SwiftUI
- WidgetConfiguration
Protocol
WidgetConfiguration
A type that describes a widget’s content.
@MainActor @preconcurrency protocol WidgetConfiguration
Overview
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is included in the type’s base declaration:
struct MyCustomType: Transition {
// @preconcurrency @MainActor isolation by default
}
Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt out of main actor isolation:
extension MyCustomType: Transition {
// nonisolated by default
}
Topics
Implementing a widget
var body: Self.Body
The content and behavior of this widget.
Required
associatedtype Body : WidgetConfiguration
The type of widget configuration representing the body of this configuration.
Setting a name
func configurationDisplayName(_:)
Sets the localized name shown for a widget when a user adds or edits the widget.
Setting a description
func description(_:)
Sets the description shown for a widget when a user adds or edits it using the contents of a text view.
Setting the appearance
Sets the sizes that a widget supports.
Disable default content margins.
Sets the disfavored locations for a widget.
A modifier that marks the background of a widget as removable.
Managing background tasks
Runs the given action when the system provides a background task.
func onBackgroundURLSessionEvents(matching:_:)
Adds an action to perform when events related to a URL session identified by a closure are waiting to be processed.
Instance Methods
Tells the system that a relevance-based widget can replace a timeline-based widget.
Beta
Specifies that a widget’s configuration UI should be automatically presented after the widget is added.
Register a type that can handle push tokens changing for widgets.
Sets the sizes that a Live Activity supports.
Specifies the mounting style for this widget.
Specifies the widget texture for this widget.
Relationships
Conforming Types
EmptyWidgetConfigurationLimitedAvailabilityConfiguration
See Also
Creating widgets
Building Widgets Using WidgetKit and SwiftUI
Create widgets to show your app’s content on the Home screen, with custom intents for user-customizable settings.
Creating a widget extension
Display your app’s content in a convenient, informative widget on various devices.
Keeping a widget up to date
Plan your widget’s timeline to show timely, relevant information using dynamic views, and update the timeline when things change.
Making a configurable widget
Give people the option to customize their widgets by adding a custom app intent to your project.
protocol Widget
The configuration and content of a widget to display on the Home screen or in Notification Center.
protocol WidgetBundle
A container used to expose multiple widgets from a single widget extension.
struct LimitedAvailabilityConfiguration
A type-erased widget configuration.
struct EmptyWidgetConfiguration
An empty widget configuration.
https://developer.apple.com/documentation/swiftui/emptywidgetconfiguration
- SwiftUI
- EmptyWidgetConfiguration
Structure
EmptyWidgetConfiguration
An empty widget configuration.
@frozen struct EmptyWidgetConfiguration
Topics
Creating a configuration
init()
Relationships
Conforms To
BitwiseCopyableCopyableSendableSendableMetatypeWidgetConfiguration
See Also
Creating widgets
Building Widgets Using WidgetKit and SwiftUI
Create widgets to show your app’s content on the Home screen, with custom intents for user-customizable settings.
Creating a widget extension
Display your app’s content in a convenient, informative widget on various devices.
Keeping a widget up to date
Plan your widget’s timeline to show timely, relevant information using dynamic views, and update the timeline when things change.
Making a configurable widget
Give people the option to customize their widgets by adding a custom app intent to your project.
protocol Widget
The configuration and content of a widget to display on the Home screen or in Notification Center.
protocol WidgetBundle
A container used to expose multiple widgets from a single widget extension.
struct LimitedAvailabilityConfiguration
A type-erased widget configuration.
protocol WidgetConfiguration
A type that describes a widget’s content.
https://developer.apple.com/documentation/swiftui/controlwidget
- SwiftUI
- ControlWidget
Protocol
ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
@MainActor @preconcurrency protocol ControlWidget
Overview
Controls allow users to quickly read the state of your app or its accessories, and take quick actions, without having to open your app. Users can add, configure, and arrange controls to suit their individual needs. You can provide multiple types of controls, each representing a specific kind of action.
There are three key components to a control:
-
A configuration that determines whether the control is configurable, identifies the control, and defines the SwiftUI template that provides the control’s content.
-
A value provider that defines the value of the control when being previewed and when being actually rendered
-
The template used by WidgetKit to display the control.
Controls are defined using templates in order to ensure that they control will work at all sizes and in all system spaces in which they might be displayed. These templates define images (specifically, symbol images) and text using simple SwiftUI views like Label, Text, and Image; and tint colors using the tint(_:) modifier.
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is included in the type’s base declaration:
struct MyCustomType: Transition {
// @preconcurrency @MainActor isolation by default
}
Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt out of main actor isolation:
extension MyCustomType: Transition {
// nonisolated by default
}
Topics
Associated Types
associatedtype Body : ControlWidgetConfiguration
The type of configuration representing the content of this control.
Required
Initializers
init()
Creates a control using body as its content.
Instance Properties
var body: Self.Body
The content and behavior of the control.
Type Methods
static func main()
See Also
Composing control widgets
protocol ControlWidgetConfiguration
A type that describes a control widget’s content.
struct EmptyControlWidgetConfiguration
An empty control widget configuration.
struct ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
protocol ControlWidgetTemplate
struct EmptyControlWidgetTemplate
An empty control widget template.
struct ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/controlwidgetconfiguration
- SwiftUI
- ControlWidgetConfiguration
Protocol
ControlWidgetConfiguration
A type that describes a control widget’s content.
@MainActor @preconcurrency protocol ControlWidgetConfiguration
Overview
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is included in the type’s base declaration:
struct MyCustomType: Transition {
// @preconcurrency @MainActor isolation by default
}
Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt out of main actor isolation:
extension MyCustomType: Transition {
// nonisolated by default
}
Topics
Associated Types
associatedtype Body : ControlWidgetConfiguration
The type of control widget configuration representing the body of this configuration.
Required
Instance Properties
var body: Self.Body
The content and behavior of the control.
Instance Methods
Sets the description shown for the control when a user adds or edits it, using the specified string.
Sets the name shown for the control when a user adds or edits it, using the specified string.
Specifies that a control’s configuration UI should be automatically presented after the widget is added.
Register a type that can handle push tokens changing for controls of this type.
Relationships
Conforming Types
EmptyControlWidgetConfiguration
See Also
Composing control widgets
protocol ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
struct EmptyControlWidgetConfiguration
An empty control widget configuration.
struct ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
protocol ControlWidgetTemplate
struct EmptyControlWidgetTemplate
An empty control widget template.
struct ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/emptycontrolwidgetconfiguration
- SwiftUI
- EmptyControlWidgetConfiguration
Structure
EmptyControlWidgetConfiguration
An empty control widget configuration.
@MainActor @frozen @preconcurrency struct EmptyControlWidgetConfiguration
Topics
Initializers
init()
Relationships
Conforms To
BitwiseCopyableControlWidgetConfigurationCopyable
See Also
Composing control widgets
protocol ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
protocol ControlWidgetConfiguration
A type that describes a control widget’s content.
struct ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
protocol ControlWidgetTemplate
struct EmptyControlWidgetTemplate
An empty control widget template.
struct ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/controlwidgetconfigurationbuilder
- SwiftUI
- ControlWidgetConfigurationBuilder
Structure
ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
@resultBuilder struct ControlWidgetConfigurationBuilder
Overview
The @ControlWidgetConfigurationBuilder attribute allows your control widget’s body closure to produce a control widget configuration after zero or more other statements:
struct GarageDoorOpener: ControlWidget { var body: some ControlWidgetConfiguration { let kind = "com.yourcompany.GarageDoorOpener"
StaticControlConfiguration( kind: kind ) { ... } } }
Topics
Type Methods
Passes a single control widget configuration written as a child control through unmodified.
Builds an expression within the builder.
See Also
Composing control widgets
protocol ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
protocol ControlWidgetConfiguration
A type that describes a control widget’s content.
struct EmptyControlWidgetConfiguration
An empty control widget configuration.
protocol ControlWidgetTemplate
struct EmptyControlWidgetTemplate
An empty control widget template.
struct ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/controlwidgettemplate
- SwiftUI
- ControlWidgetTemplate
Protocol
ControlWidgetTemplate
A type that describes a control widget’s content.
@MainActor @preconcurrency protocol ControlWidgetTemplate
Overview
Controls are defined using templates in order to ensure that they control will work at all sizes and in all system spaces in which they might be displayed. These templates define images (specifically, symbol images) and text using simple SwiftUI views like Label, Text, and Image; and tint colors using the tint(_:) modifier.
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is included in the type’s base declaration:
struct MyCustomType: Transition {
// @preconcurrency @MainActor isolation by default
}
Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt out of main actor isolation:
extension MyCustomType: Transition {
// nonisolated by default
}
Topics
Associated Types
associatedtype Body : ControlWidgetTemplate
The type of control widget template representing the body of this template.
Required
Instance Properties
var body: Self.Body
The content and behavior of this control widget.
Instance Methods
Determines whether users can interact with this control widget.
Marks the control template as containing sensitive, private user data.
Sets the tint color within this control widget template.
Relationships
Conforming Types
EmptyControlWidgetTemplate
See Also
Composing control widgets
protocol ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
protocol ControlWidgetConfiguration
struct EmptyControlWidgetConfiguration
An empty control widget configuration.
struct ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
struct EmptyControlWidgetTemplate
An empty control widget template.
struct ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/emptycontrolwidgettemplate
- SwiftUI
- EmptyControlWidgetTemplate
Structure
EmptyControlWidgetTemplate
An empty control widget template.
@MainActor @frozen @preconcurrency struct EmptyControlWidgetTemplate
Topics
Initializers
init()
Relationships
Conforms To
BitwiseCopyableControlWidgetTemplateCopyable
See Also
Composing control widgets
protocol ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
protocol ControlWidgetConfiguration
A type that describes a control widget’s content.
struct EmptyControlWidgetConfiguration
An empty control widget configuration.
struct ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
protocol ControlWidgetTemplate
struct ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/controlwidgettemplatebuilder
- SwiftUI
- ControlWidgetTemplateBuilder
Structure
ControlWidgetTemplateBuilder
A custom attribute that constructs a control widget template’s body.
@resultBuilder struct ControlWidgetTemplateBuilder
Overview
The @ControlWidgetTemplateBuilder attribute allows your control template’s body closure to produce a control template after zero or more other statements:
struct GarageDoorOpener: ControlWidget { var body: some ControlWidgetConfiguration { let kind = "com.yourcompany.GarageDoorOpener"
StaticControlConfiguration( kind: kind ) { let isOpen = ...
ControlWidgetToggle( "Garage Door", isOn: isOpen, action: ToggleGarageDoor() ) { Label( $0 ? "Open" : "Closed", systemImage: $0 ? "door.garage.open" : "door.garage.closed" ) } } } }
Topics
Type Methods
Passes a single control widget template written as a child view through unmodified.
Builds an expression within the builder.
See Also
Composing control widgets
protocol ControlWidget
The configuration and content of a control widget to display in system spaces such as Control Center, the Lock Screen, and the Action Button.
protocol ControlWidgetConfiguration
A type that describes a control widget’s content.
struct EmptyControlWidgetConfiguration
An empty control widget configuration.
struct ControlWidgetConfigurationBuilder
A custom attribute that constructs a control widget’s body.
protocol ControlWidgetTemplate
struct EmptyControlWidgetTemplate
An empty control widget template.
func controlWidgetActionHint(_:)
The action hint of the control described by the modified label.
func controlWidgetStatus(_:)
The status of the control described by the modified label.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/widgetlabel(_:)
#app-main)
- SwiftUI
- View
- widgetLabel(_:)
Instance Method
widgetLabel(_:)
Returns a localized text label that displays additional content outside the accessory family widget’s main SwiftUI view.
@MainActor @preconcurrency
Show all declarations
Parameters
label
A label generated from a localized string.
Discussion
To add a text label to an accessory family widget, call this method on the widget’s main SwiftUI view, and pass in a supported LocalizedStringResource. The system determines whether it can use the text label. If it can’t, it ignores the label. The system also sets the label’s size, placement, and style based on the clock face. For example, setting the font and rendering the text along a curve.
The following widget families support text accessory labels:
-
The
WidgetFamily.accessoryCornerwidget-based complication can display a curved text label on the inside edge of the corner. Adding a label to an accessory corner complication causes the main SwiftUI view to shrink to make space for the label. -
The
WidgetFamily.accessoryCircularwidget can display a text label in watchOS; however, WidgetKit only renders the label along the bezel on the Infograph watch face (the top circular complication).
See Also
Labeling a widget
Creates a label for displaying additional content outside an accessory family widget’s main SwiftUI view.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/widgetlabel(label:)
#app-main)
- SwiftUI
- View
- widgetLabel(label:)
Instance Method
widgetLabel(label:)
Creates a label for displaying additional content outside an accessory family widget’s main SwiftUI view.
@MainActor @preconcurrency
Parameters
label
A view that WidgetKit can display alongside the accessory family widget’s main SwiftUI view. You can use a Image, Text, Gauge, ProgressView, or a container with multiple subviews.
Discussion
The system only displays labels on widget-based complications in watchOS. The system ignores any labels attached to widgets on the Lock Screen on iPhone. Therefore, you can use the same code to display an accessory family widget on both iPhone and Apple Watch.
To create the widget label, call widgetLabel(label:) on a complication’s main SwiftUI view. Pass the desired content as the label parameter. The label can be a Gauge, ProgressView, Text, or Image. To provide multiple views, wrap your views in a container, such as a VStack. WidgetKit determines whether it can use any of the label’s content. If it can’t, it ignores the label.
struct Complication: View { @Environment(.widgetFamily) var widgetFamily
var body: some View { switch widgetFamily { case .accessoryCorner: Text("Hi") .widgetLabel { Gauge(value: 0.8) } case .accessoryCircular: VStack { Image(systemName: "emoji.globe") Text("Hi") } .widgetLabel("World!") case .accessoryInline: Text("(Image(systemName: "emoji.globe.face")) World!") } }
WidgetKit configures the label so that the watch face presents a unified look. For example, it sets the size for an image, the font for text, and can even render text and gauges along a curve.
The following widget families support widget labels:
WidgetFamily.accessoryCorner
In watchOS, this widget-based complication can display a Gauge, a ProgressView, or a Text. Adding a label to an accessory corner causes the main SwiftUI view to shrink to make space for the label. If you pass a view containing multiple, valid subviews, the system picks which view to display as the widget label.
WidgetFamily.accessoryCircular
In watchOS, the widget-based complication can display either an Image or a Text. To pass both an image and text, wrap those views in a container.
However, WidgetKit only renders the label along the bezel on the Infograph watch face (the top circular complication). On all other circular complications — including widgets on all other platforms — WidgetKit ignores the label.
See Also
Labeling a widget
func widgetLabel(_:)
Returns a localized text label that displays additional content outside the accessory family widget’s main SwiftUI view.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/widgetaccentable(_:)
#app-main)
- SwiftUI
- View
- widgetAccentable(_:)
Instance Method
widgetAccentable(_:)
Adds the view and all of its subviews to the accented group.
@MainActor @preconcurrency
Parameters
accentable
A Boolean value that indicates whether to add the view and its subviews to the accented group.
Discussion
When the system renders the widget using the WidgetKit/WidgetRenderingMode/accented mode, it divides the widget’s view hierarchy into two groups: the accented group and the default group. It then applies a different color to each group.
When applying the colors, the system treats the widget’s views as if they were template images. It ignores the view’s color — rendering the new colors based on the view’s alpha channel.
To control your view’s appearance, add the widgetAccentable(_:) modifier to part of your view’s hierarchy. If the accentable parameter is true, the system adds that view and all of its subviews to the accent group. It puts all other views in the default group.
var body: some View { VStack { Text("MON") .font(.caption) .widgetAccentable() Text("6") .font(.title) } } }
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/dynamicisland(verticalplacement:)
#app-main)
- SwiftUI
- View
- dynamicIsland(verticalPlacement:)
Instance Method
dynamicIsland(verticalPlacement:)
Specifies the vertical placement for a view of an expanded Live Activity that appears in the Dynamic Island.
@MainActor @preconcurrency
Parameters
verticalPlacement
The vertical placement for a view that’s part of an expanded Live Activity in the Dynamic Island.
Return Value
A view with the specified vertical placement.
https://developer.apple.com/documentation/swiftui/widget)
https://developer.apple.com/documentation/swiftui/widgetbundle)
https://developer.apple.com/documentation/swiftui/limitedavailabilityconfiguration)
https://developer.apple.com/documentation/swiftui/widgetconfiguration)
https://developer.apple.com/documentation/swiftui/emptywidgetconfiguration)
https://developer.apple.com/documentation/swiftui/controlwidget)
https://developer.apple.com/documentation/swiftui/controlwidgetconfiguration)
https://developer.apple.com/documentation/swiftui/emptycontrolwidgetconfiguration)
https://developer.apple.com/documentation/swiftui/controlwidgetconfigurationbuilder)
https://developer.apple.com/documentation/swiftui/controlwidgettemplate)
https://developer.apple.com/documentation/swiftui/emptycontrolwidgettemplate)
https://developer.apple.com/documentation/swiftui/controlwidgettemplatebuilder)
https://developer.apple.com/documentation/swiftui/view/widgetlabel(_:))
https://developer.apple.com/documentation/swiftui/view/widgetlabel(label:))
https://developer.apple.com/documentation/swiftui/view/widgetaccentable(_:))
https://developer.apple.com/documentation/swiftui/view/dynamicisland(verticalplacement:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/dialogseverity
- SwiftUI
- DialogSeverity
Structure
DialogSeverity
The severity of an alert or confirmation dialog.
struct DialogSeverity
Overview
You can use dialog severity to indicate that people need to take extra care when interacting with the dialog, like when an action taken from the dialog permanently deletes data.
Topics
Getting severities
static let automatic: DialogSeverity
The default dialog severity. Alerts that present an error will use .critical and all others will use .standard.
static let standard: DialogSeverity
A severity that indicates the dialog is being displayed for the purpose of presenting information to the user.
static let critical: DialogSeverity
A severity that indicates extra attention should be given to the dialog, for example when unexpected data loss may occur as a result of the action taken.
Relationships
Conforms To
Equatable
https://developer.apple.com/documentation/swiftui/view/sheet(ispresented:ondismiss:content:)
#app-main)
- SwiftUI
- View
- sheet(isPresented:onDismiss:content:)
Instance Method
sheet(isPresented:onDismiss:content:)
Presents a sheet when a binding to a Boolean value that you provide is true.
nonisolated
Parameters
isPresented
A binding to a Boolean value that determines whether to present the sheet that you create in the modifier’s content closure.
onDismiss
The closure to execute when dismissing the sheet.
content
A closure that returns the content of the sheet.
Discussion
Use this method when you want to present a modal view to the user when a Boolean value you provide is true. The example below displays a modal view of the mockup for a software license agreement when the user toggles the isShowingSheet variable by clicking or tapping on the “Show License Agreement” button:
struct ShowLicenseAgreement: View { @State private var isShowingSheet = false var body: some View { Button(action: { isShowingSheet.toggle() }) { Text("Show License Agreement") } .sheet(isPresented: $isShowingSheet, onDismiss: didDismiss) { VStack { Text("License Agreement") .font(.title) .padding(50) Text(""" Terms and conditions go here. """) .padding(50) Button("Dismiss", action: { isShowingSheet.toggle() }) } } }
func didDismiss() { // Handle the dismissing action. } }
In vertically compact environments, such as iPhone in landscape orientation, a sheet presentation automatically adapts to appear as a full-screen cover. Use the presentationCompactAdaptation(_:) or presentationCompactAdaptation(horizontal:vertical:) modifier to override this behavior.
See Also
Showing a sheet, cover, or popover
Presents a sheet using the given item as a data source for the sheet’s content.
Presents a modal view that covers as much of the screen as possible when binding to a Boolean value you provide is true.
Presents a modal view that covers as much of the screen as possible using the binding you provide as a data source for the sheet’s content.
Presents a popover using the given item as a data source for the popover’s content.
Presents a popover when a given condition is true.
enum PopoverAttachmentAnchor
An attachment anchor for a popover.
https://developer.apple.com/documentation/swiftui/view/sheet(item:ondismiss:content:)
#app-main)
- SwiftUI
- View
- sheet(item:onDismiss:content:)
Instance Method
sheet(item:onDismiss:content:)
Presents a sheet using the given item as a data source for the sheet’s content.
nonisolated
Parameters
item
A binding to an optional source of truth for the sheet. When item is non- nil, the system passes the item’s content to the modifier’s closure. You display this content in a sheet that you create that the system displays to the user. If item changes, the system dismisses the sheet and replaces it with a new one using the same process.
onDismiss
The closure to execute when dismissing the sheet.
content
A closure returning the content of the sheet.
Discussion
Use this method when you need to present a modal view with content from a custom data source. The example below shows a custom data source InventoryItem that the content closure uses to populate the display the action sheet shows to the user:
struct ShowPartDetail: View { @State private var sheetDetail: InventoryItem?
var body: some View { Button("Show Part Details") { sheetDetail = InventoryItem( id: "0123456789", partNumber: "Z-1234A", quantity: 100, name: "Widget") } .sheet(item: $sheetDetail, onDismiss: didDismiss) { detail in VStack(alignment: .leading, spacing: 20) { Text("Part Number: (detail.partNumber)") Text("Name: (detail.name)") Text("Quantity On-Hand: (detail.quantity)") } .onTapGesture { sheetDetail = nil } } }
func didDismiss() { // Handle the dismissing action. } }
struct InventoryItem: Identifiable { var id: String let partNumber: String let quantity: Int let name: String }
In vertically compact environments, such as iPhone in landscape orientation, a sheet presentation automatically adapts to appear as a full-screen cover. Use the presentationCompactAdaptation(_:) or presentationCompactAdaptation(horizontal:vertical:) modifier to override this behavior.
See Also
Showing a sheet, cover, or popover
Presents a sheet when a binding to a Boolean value that you provide is true.
Presents a modal view that covers as much of the screen as possible when binding to a Boolean value you provide is true.
Presents a modal view that covers as much of the screen as possible using the binding you provide as a data source for the sheet’s content.
Presents a popover using the given item as a data source for the popover’s content.
Presents a popover when a given condition is true.
enum PopoverAttachmentAnchor
An attachment anchor for a popover.
https://developer.apple.com/documentation/swiftui/view/fullscreencover(ispresented:ondismiss:content:)
#app-main)
- SwiftUI
- View
- fullScreenCover(isPresented:onDismiss:content:)
Instance Method
fullScreenCover(isPresented:onDismiss:content:)
Presents a modal view that covers as much of the screen as possible when binding to a Boolean value you provide is true.
nonisolated
Parameters
isPresented
A binding to a Boolean value that determines whether to present the sheet.
onDismiss
The closure to execute when dismissing the modal view.
content
A closure that returns the content of the modal view.
Discussion
Use this method to show a modal view that covers as much of the screen as possible. The example below displays a custom view when the user toggles the value of the isPresenting binding:
struct FullScreenCoverPresentedOnDismiss: View { @State private var isPresenting = false var body: some View { Button("Present Full-Screen Cover") { isPresenting.toggle() } .fullScreenCover(isPresented: $isPresenting, onDismiss: didDismiss) { VStack { Text("A full-screen modal view.") .font(.title) Text("Tap to Dismiss") } .onTapGesture { isPresenting.toggle() } .foregroundColor(.white) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.blue) .ignoresSafeArea(edges: .all) } }
func didDismiss() { // Handle the dismissing action. } }
See Also
Showing a sheet, cover, or popover
Presents a sheet when a binding to a Boolean value that you provide is true.
Presents a sheet using the given item as a data source for the sheet’s content.
Presents a modal view that covers as much of the screen as possible using the binding you provide as a data source for the sheet’s content.
Presents a popover using the given item as a data source for the popover’s content.
Presents a popover when a given condition is true.
enum PopoverAttachmentAnchor
An attachment anchor for a popover.
https://developer.apple.com/documentation/swiftui/view/fullscreencover(item:ondismiss:content:)
#app-main)
- SwiftUI
- View
- fullScreenCover(item:onDismiss:content:)
Instance Method
fullScreenCover(item:onDismiss:content:)
Presents a modal view that covers as much of the screen as possible using the binding you provide as a data source for the sheet’s content.
nonisolated
Parameters
item
A binding to an optional source of truth for the sheet. When item is non- nil, the system passes the contents to the modifier’s closure. You display this content in a sheet that you create that the system displays to the user. If item changes, the system dismisses the currently displayed sheet and replaces it with a new one using the same process.
onDismiss
The closure to execute when dismissing the modal view.
content
A closure returning the content of the modal view.
Discussion
Use this method to display a modal view that covers as much of the screen as possible. In the example below a custom structure — CoverData — provides data for the full-screen view to display in the content closure when the user clicks or taps the “Present Full-Screen Cover With Data” button:
struct FullScreenCoverItemOnDismissContent: View { @State private var coverData: CoverData?
var body: some View { Button("Present Full-Screen Cover With Data") { coverData = CoverData(body: "Custom Data") } .fullScreenCover(item: $coverData, onDismiss: didDismiss) { details in VStack(spacing: 20) { Text("(details.body)") } .onTapGesture { coverData = nil } } }
func didDismiss() { // Handle the dismissing action. }
}
struct CoverData: Identifiable { var id: String { return body } let body: String }
See Also
Showing a sheet, cover, or popover
Presents a sheet when a binding to a Boolean value that you provide is true.
Presents a sheet using the given item as a data source for the sheet’s content.
Presents a modal view that covers as much of the screen as possible when binding to a Boolean value you provide is true.
Presents a popover using the given item as a data source for the popover’s content.
Presents a popover when a given condition is true.
enum PopoverAttachmentAnchor
An attachment anchor for a popover.
https://developer.apple.com/documentation/swiftui/view/popover(item:attachmentanchor:arrowedge:content:)
#app-main)
- SwiftUI
- View
- popover(item:attachmentAnchor:arrowEdge:content:)
Instance Method
popover(item:attachmentAnchor:arrowEdge:content:)
Presents a popover using the given item as a data source for the popover’s content.
nonisolated
attachmentAnchor: PopoverAttachmentAnchor = .rect(.bounds), arrowEdge: Edge? = nil,
Parameters
item
A binding to an optional source of truth for the popover. When item is non- nil, the system passes the contents to the modifier’s closure. You use this content to populate the fields of a popover that you create that the system displays to the user. If item changes, the system dismisses the currently presented popover and replaces it with a new popover using the same process.
attachmentAnchor
The positioning anchor that defines the attachment point of the popover. The default is bounds.
arrowEdge
The edge of the attachmentAnchor that defines the location of the popover’s arrow. The default is nil, which results in the system allowing any arrow edge.
content
A closure returning the content of the popover.
Discussion
Use this method when you need to present a popover with content from a custom data source. The example below uses data in the PopoverModel structure to populate the view in the content closure that the popover displays to the user:
struct PopoverExample: View { @State private var popover: PopoverModel?
var body: some View { Button("Show Popover") { popover = PopoverModel(message: "Custom Message") } .popover(item: $popover, arrowEdge: .bottom) { detail in Text("(detail.message)") .padding() } } }
struct PopoverModel: Identifiable { var id: String { message } let message: String }
See Also
Showing a sheet, cover, or popover
Presents a sheet when a binding to a Boolean value that you provide is true.
Presents a sheet using the given item as a data source for the sheet’s content.
Presents a modal view that covers as much of the screen as possible when binding to a Boolean value you provide is true.
Presents a modal view that covers as much of the screen as possible using the binding you provide as a data source for the sheet’s content.
Presents a popover when a given condition is true.
enum PopoverAttachmentAnchor
An attachment anchor for a popover.
https://developer.apple.com/documentation/swiftui/view/popover(ispresented:attachmentanchor:arrowedge:content:)
#app-main)
- SwiftUI
- View
- popover(isPresented:attachmentAnchor:arrowEdge:content:)
Instance Method
popover(isPresented:attachmentAnchor:arrowEdge:content:)
Presents a popover when a given condition is true.
nonisolated
attachmentAnchor: PopoverAttachmentAnchor = .rect(.bounds), arrowEdge: Edge? = nil,
Parameters
isPresented
A binding to a Boolean value that determines whether to present the popover content that you return from the modifier’s content closure.
attachmentAnchor
The positioning anchor that defines the attachment point of the popover. The default is bounds.
arrowEdge
The edge of the attachmentAnchor that defines the location of the popover’s arrow. The default is nil, which results in the system allowing any arrow edge.
content
A closure returning the content of the popover.
Discussion
Use this method to show a popover whose contents are a SwiftUI view that you provide when a bound Boolean variable is true. In the example below, a popover displays whenever the user toggles the isShowingPopover state variable by pressing the “Show Popover” button:
struct PopoverExample: View { @State private var isShowingPopover = false
var body: some View { Button("Show Popover") { self.isShowingPopover = true } .popover( isPresented: $isShowingPopover, arrowEdge: .bottom ) { Text("Popover Content") .padding() } } }
See Also
Showing a sheet, cover, or popover
Presents a sheet when a binding to a Boolean value that you provide is true.
Presents a sheet using the given item as a data source for the sheet’s content.
Presents a modal view that covers as much of the screen as possible when binding to a Boolean value you provide is true.
Presents a modal view that covers as much of the screen as possible using the binding you provide as a data source for the sheet’s content.
Presents a popover using the given item as a data source for the popover’s content.
enum PopoverAttachmentAnchor
An attachment anchor for a popover.
https://developer.apple.com/documentation/swiftui/popoverattachmentanchor
- SwiftUI
- PopoverAttachmentAnchor
Enumeration
PopoverAttachmentAnchor
An attachment anchor for a popover.
enum PopoverAttachmentAnchor
Topics
Getting attachment anchors
case point(UnitPoint)
The anchor point for the popover expressed as a unit point that describes possible alignments relative to a SwiftUI view.
The anchor point for the popover relative to the source’s frame.
See Also
Showing a sheet, cover, or popover
Presents a sheet when a binding to a Boolean value that you provide is true.
Presents a sheet using the given item as a data source for the sheet’s content.
Presents a modal view that covers as much of the screen as possible when binding to a Boolean value you provide is true.
Presents a modal view that covers as much of the screen as possible using the binding you provide as a data source for the sheet’s content.
Presents a popover using the given item as a data source for the popover’s content.
Presents a popover when a given condition is true.
https://developer.apple.com/documentation/swiftui/view/presentationcompactadaptation(horizontal:vertical:)
#app-main)
- SwiftUI
- View
- presentationCompactAdaptation(horizontal:vertical:)
Instance Method
presentationCompactAdaptation(horizontal:vertical:)
Specifies how to adapt a presentation to horizontally and vertically compact size classes.
nonisolated func presentationCompactAdaptation( horizontal horizontalAdaptation: PresentationAdaptation, vertical verticalAdaptation: PresentationAdaptation
Parameters
horizontalAdaptation
The adaptation to use in a horizontally compact size class.
verticalAdaptation
The adaptation to use in a vertically compact size class. In a size class that is both horizontally and vertically compact, SwiftUI uses the verticalAdaptation value.
Discussion
Some presentations adapt their appearance depending on the context. For example, a popover presentation over a horizontally-compact view uses a sheet appearance by default. Use this modifier to indicate a custom adaptation preference.
struct ContentView: View { @State private var showInfo = false
var body: some View { Button("View Info") { showInfo = true } .popover(isPresented: $showInfo) { InfoView() .presentationCompactAdaptation( horizontal: .popover, vertical: .sheet) } } }
If you want to specify the same adaptation for both dimensions, use the presentationCompactAdaptation(_:) method instead.
See Also
Adapting a presentation size
Specifies how to adapt a presentation to compact size classes.
struct PresentationAdaptation
Strategies for adapting a presentation to a different size class.
Sets the sizing of the containing presentation.
protocol PresentationSizing
A type that defines the size of the presentation content and how the presentation size adjusts to its content’s size changing.
struct PresentationSizingRoot
A proxy to a view provided to the presentation with a defined presentation size.
struct PresentationSizingContext
Contextual information about a presentation.
https://developer.apple.com/documentation/swiftui/view/presentationcompactadaptation(_:)
#app-main)
- SwiftUI
- View
- presentationCompactAdaptation(_:)
Instance Method
presentationCompactAdaptation(_:)
Specifies how to adapt a presentation to compact size classes.
nonisolated
Parameters
adaptation
The adaptation to use in either a horizontally or vertically compact size class.
Discussion
Some presentations adapt their appearance depending on the context. For example, a sheet presentation over a vertically-compact view uses a full-screen-cover appearance by default. Use this modifier to indicate a custom adaptation preference. For example, the following code uses a presentation adaptation value of none to request that the system not adapt the sheet in compact size classes:
struct ContentView: View { @State private var showSettings = false
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView() .presentationDetents([.medium, .large]) .presentationCompactAdaptation(.none) } } }
If you want to specify different adaptations for each dimension, use the presentationCompactAdaptation(horizontal:vertical:) method instead.
See Also
Adapting a presentation size
Specifies how to adapt a presentation to horizontally and vertically compact size classes.
struct PresentationAdaptation
Strategies for adapting a presentation to a different size class.
Sets the sizing of the containing presentation.
protocol PresentationSizing
A type that defines the size of the presentation content and how the presentation size adjusts to its content’s size changing.
struct PresentationSizingRoot
A proxy to a view provided to the presentation with a defined presentation size.
struct PresentationSizingContext
Contextual information about a presentation.
https://developer.apple.com/documentation/swiftui/presentationadaptation
- SwiftUI
- PresentationAdaptation
Structure
PresentationAdaptation
Strategies for adapting a presentation to a different size class.
struct PresentationAdaptation
Overview
Use values of this type with the presentationCompactAdaptation(_:) and presentationCompactAdaptation(horizontal:vertical:) modifiers.
Topics
Getting adaptation strategies
static var automatic: PresentationAdaptation
Use the default presentation adaptation.
static var none: PresentationAdaptation
Don’t adapt for the size class, if possible.
static var fullScreenCover: PresentationAdaptation
Prefer a full-screen-cover appearance when adapting for size classes.
static var popover: PresentationAdaptation
Prefer a popover appearance when adapting for size classes.
static var sheet: PresentationAdaptation
Prefer a sheet appearance when adapting for size classes.
Relationships
Conforms To
SendableSendableMetatype
See Also
Adapting a presentation size
Specifies how to adapt a presentation to horizontally and vertically compact size classes.
Specifies how to adapt a presentation to compact size classes.
Sets the sizing of the containing presentation.
protocol PresentationSizing
A type that defines the size of the presentation content and how the presentation size adjusts to its content’s size changing.
struct PresentationSizingRoot
A proxy to a view provided to the presentation with a defined presentation size.
struct PresentationSizingContext
Contextual information about a presentation.
https://developer.apple.com/documentation/swiftui/view/presentationsizing(_:)
#app-main)
- SwiftUI
- View
- presentationSizing(_:)
Instance Method
presentationSizing(_:)
Sets the sizing of the containing presentation.
nonisolated
Parameters
sizing
A value dictating size to propose to presentation content and how the presentation responds to changes in content size.
Discussion
Use this modifier to apply a PresentationSizing to a presentation like sheet(isPresented:onDismiss:content:). The sizing parameter defines the size proposed to the content, and the presentation adopts the returned size. The default value is automatic.
Sizings can be modified to fix their dimensions based on the content, and optionally be sticky.
For example, a presentation with facts about flowers could prefer .page sizing because its content is primarily informational. Since the user can choose different flowers from the picker, each with different lengths of information, the size is fitted vertically to size the sheet to the textual content, and vertically sticky is specified to prevent the presentation from changing size too frequently as the user changes selection.
struct ContentView: View { @State private var presentInfo = true
var body: some View { ContentView.sheet(isPresented: $presentInfo) { VStack { Picker("Flower Species", selection: $flower) { ForEach(Flower.allCases) { Text($0.rawValue.uppercased()).tag($0) } } Text(flower.emoji).font(.largeTitle) Text(flower.informationalText) } .frame(maxHeight: .infinity, alignment: .top) .padding() .presentationSizing( .page .fitted(horizontal: false, vertical: true) .sticky(horizontal: false, vertical: true)) } } }
See Also
Adapting a presentation size
Specifies how to adapt a presentation to horizontally and vertically compact size classes.
Specifies how to adapt a presentation to compact size classes.
struct PresentationAdaptation
Strategies for adapting a presentation to a different size class.
protocol PresentationSizing
A type that defines the size of the presentation content and how the presentation size adjusts to its content’s size changing.
struct PresentationSizingRoot
A proxy to a view provided to the presentation with a defined presentation size.
struct PresentationSizingContext
Contextual information about a presentation.
https://developer.apple.com/documentation/swiftui/presentationsizing
- SwiftUI
- PresentationSizing
Protocol
PresentationSizing
A type that defines the size of the presentation content and how the presentation size adjusts to its content’s size changing.
protocol PresentationSizing
Overview
You don’t need to define your own version of this protocol. The system implementations of form, page, and fitted are conveniences that automatically adapt to different device and screen sizes. If you do want to define your own sizing, first consider using the modifiers PresenationSizing/sticky(horizontal:vertical:) and fitted(horizontal:vertical:). For example, to define your own sizing that proposes a 400x400 square size:
protocol SquareSizing: PresentationSizing { func proposedSize( for subview: PresentationSizingRoot, context: PresentationSizingContext ) { .init(width: 400, height: 400) } }
extension PresentationSizing where Self == SquareSizing { public static var square: Self { SquareSizing() } }
Then, at the callsite, you can modify .square just like system sizings, for example, to fit its content vertically:
.presentationSizing(.square.fitted(horizontal: false, vertical: true))
Topics
Getting built-in presentation size
static var automatic: AutomaticPresentationSizing
The default presentation sizing, appropriate for the platform.
static var fitted: FittedPresentationSizing
The presentation sizing is dictated by the ideal size of the content
static var form: FormPresentationSizing
The size is appropriate for forms and slightly less wide than .page
static var page: PagePresentationSizing
The size is roughly the size of a page of paper, appropriate for informational or compositional content.
Creating custom presentation size
Required
Modifies self to be sticky in the specified dimensions — growing, but not shrinking.
Supporting types
struct AutomaticPresentationSizing
struct FittedPresentationSizing
The size of the presentation is dictated by the ideal size of the content.
struct FormPresentationSizing
struct PagePresentationSizing
Relationships
Conforming Types
AutomaticPresentationSizingFittedPresentationSizingFormPresentationSizingPagePresentationSizing
See Also
Adapting a presentation size
Specifies how to adapt a presentation to horizontally and vertically compact size classes.
Specifies how to adapt a presentation to compact size classes.
struct PresentationAdaptation
Strategies for adapting a presentation to a different size class.
Sets the sizing of the containing presentation.
struct PresentationSizingRoot
A proxy to a view provided to the presentation with a defined presentation size.
struct PresentationSizingContext
Contextual information about a presentation.
https://developer.apple.com/documentation/swiftui/presentationsizingroot
- SwiftUI
- PresentationSizingRoot
Structure
PresentationSizingRoot
A proxy to a view provided to the presentation with a defined presentation size.
struct PresentationSizingRoot
Topics
Instance Methods
Asks the subview for its size.
See Also
Adapting a presentation size
Specifies how to adapt a presentation to horizontally and vertically compact size classes.
Specifies how to adapt a presentation to compact size classes.
struct PresentationAdaptation
Strategies for adapting a presentation to a different size class.
Sets the sizing of the containing presentation.
protocol PresentationSizing
A type that defines the size of the presentation content and how the presentation size adjusts to its content’s size changing.
struct PresentationSizingContext
Contextual information about a presentation.
https://developer.apple.com/documentation/swiftui/presentationsizingcontext
- SwiftUI
- PresentationSizingContext
Structure
PresentationSizingContext
Contextual information about a presentation.
struct PresentationSizingContext
Overview
The properties of a PresentationSizingContext can influence what size is proposed to a presentation.
See Also
Adapting a presentation size
Specifies how to adapt a presentation to horizontally and vertically compact size classes.
Specifies how to adapt a presentation to compact size classes.
struct PresentationAdaptation
Strategies for adapting a presentation to a different size class.
Sets the sizing of the containing presentation.
protocol PresentationSizing
A type that defines the size of the presentation content and how the presentation size adjusts to its content’s size changing.
struct PresentationSizingRoot
A proxy to a view provided to the presentation with a defined presentation size.
https://developer.apple.com/documentation/swiftui/view/presentationdetents(_:)
#app-main)
- SwiftUI
- View
- presentationDetents(_:)
Instance Method
presentationDetents(_:)
Sets the available detents for the enclosing sheet.
nonisolated
Parameters
detents
A set of supported detents for the sheet. If you provide more that one detent, people can drag the sheet to resize it.
Discussion
By default, sheets support the large detent.
struct ContentView: View { @State private var showSettings = false
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView() .presentationDetents([.medium, .large]) } } }
See Also
Configuring a sheet’s height
Sets the available detents for the enclosing sheet, giving you programmatic control of the currently selected detent.
Configures the behavior of swipe gestures on a presentation.
Sets the visibility of the drag indicator on top of a sheet.
struct PresentationDetent
A type that represents a height where a sheet naturally rests.
protocol CustomPresentationDetent
The definition of a custom detent with a calculated height.
struct PresentationContentInteraction
A behavior that you can use to influence how a presentation responds to swipe gestures.
https://developer.apple.com/documentation/swiftui/view/presentationdetents(_:selection:)
#app-main)
- SwiftUI
- View
- presentationDetents(_:selection:)
Instance Method
presentationDetents(_:selection:)
Sets the available detents for the enclosing sheet, giving you programmatic control of the currently selected detent.
nonisolated func presentationDetents(
Parameters
detents
A set of supported detents for the sheet. If you provide more that one detent, people can drag the sheet to resize it.
selection
A Binding to the currently selected detent. Ensure that the value matches one of the detents that you provide for the detents parameter.
Discussion
By default, sheets support the large detent.
struct ContentView: View { @State private var showSettings = false @State private var settingsDetent = PresentationDetent.medium
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView() .presentationDetents( [.medium, .large], selection: $settingsDetent ) } } }
See Also
Configuring a sheet’s height
Sets the available detents for the enclosing sheet.
Configures the behavior of swipe gestures on a presentation.
Sets the visibility of the drag indicator on top of a sheet.
struct PresentationDetent
A type that represents a height where a sheet naturally rests.
protocol CustomPresentationDetent
The definition of a custom detent with a calculated height.
struct PresentationContentInteraction
A behavior that you can use to influence how a presentation responds to swipe gestures.
https://developer.apple.com/documentation/swiftui/view/presentationcontentinteraction(_:)
#app-main)
- SwiftUI
- View
- presentationContentInteraction(_:)
Instance Method
presentationContentInteraction(_:)
Configures the behavior of swipe gestures on a presentation.
nonisolated
Parameters
behavior
The requested behavior.
Discussion
By default, when a person swipes up on a scroll view in a resizable presentation, the presentation grows to the next detent. A scroll view embedded in the presentation only scrolls after the presentation reaches its largest size. Use this modifier to control which action takes precedence.
For example, you can request that swipe gestures scroll content first, resizing the sheet only after hitting the end of the scroll view, by passing the scrolls value to this modifier:
struct ContentView: View { @State private var showSettings = false
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView() .presentationDetents([.medium, .large]) .presentationContentInteraction(.scrolls) } } }
People can always resize your presentation using the drag indicator.
See Also
Configuring a sheet’s height
Sets the available detents for the enclosing sheet.
Sets the available detents for the enclosing sheet, giving you programmatic control of the currently selected detent.
Sets the visibility of the drag indicator on top of a sheet.
struct PresentationDetent
A type that represents a height where a sheet naturally rests.
protocol CustomPresentationDetent
The definition of a custom detent with a calculated height.
struct PresentationContentInteraction
A behavior that you can use to influence how a presentation responds to swipe gestures.
https://developer.apple.com/documentation/swiftui/view/presentationdragindicator(_:)
#app-main)
- SwiftUI
- View
- presentationDragIndicator(_:)
Instance Method
presentationDragIndicator(_:)
Sets the visibility of the drag indicator on top of a sheet.
nonisolated
Parameters
visibility
The preferred visibility of the drag indicator.
Discussion
You can show a drag indicator when it isn’t apparent that a sheet can resize or when the sheet can’t dismiss interactively.
struct ContentView: View { @State private var showSettings = false
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView() .presentationDetents([.medium, .large]) .presentationDragIndicator(.visible) } } }
See Also
Configuring a sheet’s height
Sets the available detents for the enclosing sheet.
Sets the available detents for the enclosing sheet, giving you programmatic control of the currently selected detent.
Configures the behavior of swipe gestures on a presentation.
struct PresentationDetent
A type that represents a height where a sheet naturally rests.
protocol CustomPresentationDetent
The definition of a custom detent with a calculated height.
struct PresentationContentInteraction
A behavior that you can use to influence how a presentation responds to swipe gestures.
https://developer.apple.com/documentation/swiftui/presentationdetent
- SwiftUI
- PresentationDetent
Structure
PresentationDetent
A type that represents a height where a sheet naturally rests.
struct PresentationDetent
Topics
Getting built-in detents
static let large: PresentationDetent
The system detent for a sheet at full height.
static let medium: PresentationDetent
The system detent for a sheet that’s approximately half the height of the screen, and is inactive in compact height.
Creating custom detents
A custom detent with a calculated height.
A custom detent with the specified fractional height.
A custom detent with the specified height.
struct Context
Information that you use to calculate the presentation’s height.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Configuring a sheet’s height
Sets the available detents for the enclosing sheet.
Sets the available detents for the enclosing sheet, giving you programmatic control of the currently selected detent.
Configures the behavior of swipe gestures on a presentation.
Sets the visibility of the drag indicator on top of a sheet.
protocol CustomPresentationDetent
The definition of a custom detent with a calculated height.
struct PresentationContentInteraction
A behavior that you can use to influence how a presentation responds to swipe gestures.
https://developer.apple.com/documentation/swiftui/custompresentationdetent
- SwiftUI
- CustomPresentationDetent
Protocol
CustomPresentationDetent
The definition of a custom detent with a calculated height.
protocol CustomPresentationDetent
Overview
You can create and use a custom detent with built-in detents.
extension PresentationDetent { static let bar = Self.custom(BarDetent.self) static let small = Self.height(100) static let extraLarge = Self.fraction(0.75) }
private struct BarDetent: CustomPresentationDetent {
max(44, context.maxDetentValue * 0.1) } }
struct ContentView: View { @State private var showSettings = false @State private var selectedDetent = PresentationDetent.bar
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView(selectedDetent: $selectedDetent) .presentationDetents( [.bar, .small, .medium, .large, .extraLarge], selection: $selectedDetent) } } }
Topics
Getting the height
Calculates and returns a height based on the context.
Required
typealias Context
Information that you can use to calculate the height of a custom detent.
See Also
Configuring a sheet’s height
Sets the available detents for the enclosing sheet.
Sets the available detents for the enclosing sheet, giving you programmatic control of the currently selected detent.
Configures the behavior of swipe gestures on a presentation.
Sets the visibility of the drag indicator on top of a sheet.
struct PresentationDetent
A type that represents a height where a sheet naturally rests.
struct PresentationContentInteraction
A behavior that you can use to influence how a presentation responds to swipe gestures.
https://developer.apple.com/documentation/swiftui/presentationcontentinteraction
- SwiftUI
- PresentationContentInteraction
Structure
PresentationContentInteraction
A behavior that you can use to influence how a presentation responds to swipe gestures.
struct PresentationContentInteraction
Overview
Use values of this type with the presentationContentInteraction(_:) modifier.
Topics
Getting interaction behaviors
static var automatic: PresentationContentInteraction
The default swipe behavior for the presentation.
static var resizes: PresentationContentInteraction
A behavior that prioritizes resizing a presentation when swiping, rather than scrolling the content of the presentation.
static var scrolls: PresentationContentInteraction
A behavior that prioritizes scrolling the content of a presentation when swiping, rather than resizing the presentation.
Relationships
Conforms To
EquatableSendableSendableMetatype
See Also
Configuring a sheet’s height
Sets the available detents for the enclosing sheet.
Sets the available detents for the enclosing sheet, giving you programmatic control of the currently selected detent.
Configures the behavior of swipe gestures on a presentation.
Sets the visibility of the drag indicator on top of a sheet.
struct PresentationDetent
A type that represents a height where a sheet naturally rests.
protocol CustomPresentationDetent
The definition of a custom detent with a calculated height.
https://developer.apple.com/documentation/swiftui/view/presentationcornerradius(_:)
#app-main)
- SwiftUI
- View
- presentationCornerRadius(_:)
Instance Method
presentationCornerRadius(_:)
Requests that the presentation have a specific corner radius.
nonisolated
Parameters
cornerRadius
The corner radius, or nil to use the system default.
Discussion
Use this modifier to change the corner radius of a presentation.
struct ContentView: View { @State private var showSettings = false
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView() .presentationDetents([.medium, .large]) .presentationCornerRadius(21) } } }
See Also
Styling a sheet and its background
Sets the presentation background of the enclosing sheet using a shape style.
Sets the presentation background of the enclosing sheet to a custom view.
Controls whether people can interact with the view behind a presentation.
struct PresentationBackgroundInteraction
The kinds of interaction available to views behind a presentation.
https://developer.apple.com/documentation/swiftui/view/presentationbackground(_:)
#app-main)
- SwiftUI
- View
- presentationBackground(_:)
Instance Method
presentationBackground(_:)
Sets the presentation background of the enclosing sheet using a shape style.
nonisolated
Parameters
style
The shape style to use as the presentation background.
Discussion
The following example uses the thick material as the sheet background:
struct ContentView: View { @State private var showSettings = false
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView() .presentationBackground(.thickMaterial) } } }
The presentationBackground(_:) modifier differs from the background(_:ignoresSafeAreaEdges:) modifier in several key ways. A presentation background:
-
Automatically fills the entire presentation.
-
Allows views behind the presentation to show through translucent styles on supported platforms.
See Also
Styling a sheet and its background
Requests that the presentation have a specific corner radius.
Sets the presentation background of the enclosing sheet to a custom view.
Controls whether people can interact with the view behind a presentation.
struct PresentationBackgroundInteraction
The kinds of interaction available to views behind a presentation.
https://developer.apple.com/documentation/swiftui/view/presentationbackground(alignment:content:)
#app-main)
- SwiftUI
- View
- presentationBackground(alignment:content:)
Instance Method
presentationBackground(alignment:content:)
Sets the presentation background of the enclosing sheet to a custom view.
nonisolated
alignment: Alignment = .center,
Parameters
alignment
The alignment that the modifier uses to position the implicit ZStack that groups the background views. The default is center.
content
The view to use as the background of the presentation.
Discussion
The following example uses a yellow view as the sheet background:
struct ContentView: View { @State private var showSettings = false
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView() .presentationBackground { Color.yellow } } } }
The presentationBackground(alignment:content:) modifier differs from the background(alignment:content:) modifier in several key ways. A presentation background:
-
Automatically fills the entire presentation.
-
Allows views behind the presentation to show through translucent areas of the
contenton supported platforms.
See Also
Styling a sheet and its background
Requests that the presentation have a specific corner radius.
Sets the presentation background of the enclosing sheet using a shape style.
Controls whether people can interact with the view behind a presentation.
struct PresentationBackgroundInteraction
The kinds of interaction available to views behind a presentation.
https://developer.apple.com/documentation/swiftui/view/presentationbackgroundinteraction(_:)
#app-main)
- SwiftUI
- View
- presentationBackgroundInteraction(_:)
Instance Method
presentationBackgroundInteraction(_:)
Controls whether people can interact with the view behind a presentation.
nonisolated
Parameters
interaction
A specification of how people can interact with the view behind a presentation.
Discussion
On many platforms, SwiftUI automatically disables the view behind a sheet that you present, so that people can’t interact with the backing view until they dismiss the sheet. Use this modifier if you want to enable interaction.
The following example enables people to interact with the view behind the sheet when the sheet is at the smallest detent, but not at the other detents:
struct ContentView: View { @State private var showSettings = false
var body: some View { Button("View Settings") { showSettings = true } .sheet(isPresented: $showSettings) { SettingsView() .presentationDetents( [.height(120), .medium, .large]) .presentationBackgroundInteraction( .enabled(upThrough: .height(120))) } } }
See Also
Styling a sheet and its background
Requests that the presentation have a specific corner radius.
Sets the presentation background of the enclosing sheet using a shape style.
Sets the presentation background of the enclosing sheet to a custom view.
struct PresentationBackgroundInteraction
The kinds of interaction available to views behind a presentation.
https://developer.apple.com/documentation/swiftui/presentationbackgroundinteraction
- SwiftUI
- PresentationBackgroundInteraction
Structure
PresentationBackgroundInteraction
The kinds of interaction available to views behind a presentation.
struct PresentationBackgroundInteraction
Overview
Use values of this type with the presentationBackgroundInteraction(_:) modifier.
Topics
Getting interaction types
static var automatic: PresentationBackgroundInteraction
The default background interaction for the presentation.
static var disabled: PresentationBackgroundInteraction
People can’t interact with the view behind a presentation.
static var enabled: PresentationBackgroundInteraction
People can interact with the view behind a presentation.
People can interact with the view behind a presentation up through a specified detent.
Relationships
Conforms To
SendableSendableMetatype
See Also
Styling a sheet and its background
Requests that the presentation have a specific corner radius.
Sets the presentation background of the enclosing sheet using a shape style.
Sets the presentation background of the enclosing sheet to a custom view.
Controls whether people can interact with the view behind a presentation.
https://developer.apple.com/documentation/swiftui/alertscene
- SwiftUI
- AlertScene
Structure
AlertScene
A scene that renders itself as a standalone alert dialog.
Overview
Alert scenes are not attached to any particular window, and present themselves in the center of the current display. The dialog must be dismissed before any further interaction with the app is permitted.
@main struct MyApp: App { @State var showLoginAlert = true @State var loggedIn = false
var body: some Scene { Window("Welcome User Window", id:"WelcomeWindow") { ... } .defaultLaunchBehavior(loggedIn ? .presented : .suppressed)
AlertScene("Login Required", isPresented: $showLoginAlert) { Button("OK") { ... } } } }
All actions present in the ViewBuilder will dismiss the alert. Like the alert modifier, you can determine the role of the buttons with .cancel or .destructive. If no actions are present, we will automatically include an OK button for dismissal.
Topics
Initializers
init(_:isPresented:actions:)
Creates an alert scene with a title and a set of actions.
init(_:isPresented:actions:message:)
Creates an alert scene with a title, a set of actions, and a message.
init(_:isPresented:presenting:actions:)
Creates an alert scene, using the given data to produce the alert’s content with a title, and a set of actions. Note that this creates a text view on your behalf.
init(_:isPresented:presenting:actions:message:)
Creates an alert scene, using the given data to produce the alert’s content with a title, a set of actions, and a message. Note that this creates a text view on your behalf.
Relationships
Conforms To
Scene
See Also
Presenting an alert
func alert(_:isPresented:actions:)
Presents an alert when a given condition is true, using a text view for the title.
func alert(_:isPresented:presenting:actions:)
Presents an alert using the given data to produce the alert’s content and a text view as a title.
Presents an alert when an error is present.
func alert(_:isPresented:actions:message:)
Presents an alert with a message when a given condition is true using a text view as a title.
func alert(_:isPresented:presenting:actions:message:)
Presents an alert with a message using the given data to produce the alert’s content and a text view for a title.
Presents an alert with a message when an error is present.
https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:actions:)
#app-main)
- SwiftUI
- View
- alert(_:isPresented:actions:)
Instance Method
alert(_:isPresented:actions:)
Presents an alert when a given condition is true, using a text view for the title.
nonisolated
_ title: Text,
Show all declarations
Parameters
title
The title of the alert.
isPresented
A binding to a Boolean value that determines whether to present the alert. When the user presses or taps one of the alert’s actions, the system sets this value to false and dismisses.
actions
A ViewBuilder returning the alert’s actions.
Discussion
In the example below, a login form conditionally presents an alert by setting the didFail state variable. When the form sets the value to to true, the system displays an alert with an “OK” action.
struct Login: View { @State private var didFail = false let alertTitle: String = "Login failed."
var body: some View { LoginForm(didFail: $didFail) .alert( Text(alertTitle), isPresented: $didFail ) { Button("OK") { // Handle the acknowledgement. } } } }
All actions in an alert dismiss the alert after the action runs. The default button is shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
If no actions are present, the system includes a standard “OK” action. No default cancel action is provided. If you want to show a cancel action, use a button with a role of cancel.
On iOS, tvOS, and watchOS, alerts only support controls with labels that are Text. Passing any other type of view results in the content being omitted.
See Also
Presenting an alert
struct AlertScene
A scene that renders itself as a standalone alert dialog.
func alert(_:isPresented:presenting:actions:)
Presents an alert using the given data to produce the alert’s content and a text view as a title.
Presents an alert when an error is present.
func alert(_:isPresented:actions:message:)
Presents an alert with a message when a given condition is true using a text view as a title.
func alert(_:isPresented:presenting:actions:message:)
Presents an alert with a message using the given data to produce the alert’s content and a text view for a title.
Presents an alert with a message when an error is present.
https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:)
#app-main)
- SwiftUI
- View
- alert(_:isPresented:presenting:actions:)
Instance Method
alert(_:isPresented:presenting:actions:)
Presents an alert using the given data to produce the alert’s content and a text view as a title.
nonisolated
_ title: Text,
presenting data: T?,
Show all declarations
Parameters
title
The title of the alert.
isPresented
A binding to a Boolean value that determines whether to present the alert. When the user presses or taps one of the alert’s actions, the system sets this value to false and dismisses.
data
An optional source of truth for the alert. The system passes the contents to the modifier’s closures. You use this data to populate the fields of an alert that you create that the system displays to the user.
actions
A ViewBuilder returning the alert’s actions given the currently available data.
Discussion
For the alert to appear, both isPresented must be true and data must not be nil. The data should not change after the presentation occurs. Any changes that you make after the presentation occurs are ignored.
Use this method when you need to populate the fields of an alert with content from a data source. The example below shows a custom data source, SaveDetails, that provides data to populate the alert:
struct SaveDetails: Identifiable { let name: String let error: String let id = UUID() }
struct SaveButton: View { @State private var didError = false @State private var details: SaveDetails? let alertTitle: String = "Save failed."
var body: some View { Button("Save") { details = model.save(didError: $didError) } .alert( Text(alertTitle), isPresented: $didError, presenting: details ) { details in Button(role: .destructive) { // Handle the deletion. } label: { Text("Delete (details.name)") } Button("Retry") { // Handle the retry action. } } } }
All actions in an alert dismiss the alert after the action runs. The default button is shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
If no actions are present, the system includes a standard “OK” action. No default cancel action is provided. If you want to show a cancel action, use a button with a role of cancel.
On iOS, tvOS, and watchOS, alerts only support controls with labels that are Text. Passing any other type of view results in the content being omitted.
See Also
Presenting an alert
struct AlertScene
A scene that renders itself as a standalone alert dialog.
func alert(_:isPresented:actions:)
Presents an alert when a given condition is true, using a text view for the title.
Presents an alert when an error is present.
func alert(_:isPresented:actions:message:)
Presents an alert with a message when a given condition is true using a text view as a title.
func alert(_:isPresented:presenting:actions:message:)
Presents an alert with a message using the given data to produce the alert’s content and a text view for a title.
Presents an alert with a message when an error is present.
https://developer.apple.com/documentation/swiftui/view/alert(ispresented:error:actions:)
#app-main)
- SwiftUI
- View
- alert(isPresented:error:actions:)
Instance Method
alert(isPresented:error:actions:)
Presents an alert when an error is present.
nonisolated
error: E?,
Parameters
isPresented
A binding to a Boolean value that determines whether to present the alert. When the user presses or taps one of the alert’s actions, the system sets this value to false and dismisses.
error
An optional localized Error that is used to generate the alert’s title. The system passes the contents to the modifier’s closures. You use this data to populate the fields of an alert that you create that the system displays to the user.
actions
A ViewBuilder returning the alert’s actions.
Discussion
In the example below, a form conditionally presents an alert depending upon the value of an error. When the error value isn’t nil, the system presents an alert with an “OK” action.
The title of the alert is inferred from the error’s errorDescription.
struct TicketPurchase: View { @State private var error: TicketPurchaseError? = nil @State private var showAlert = false
var body: some View { TicketForm(showAlert: $showAlert, error: $error) .alert(isPresented: $showAlert, error: error) { Button("OK") { // Handle acknowledgement. } } } }
All actions in an alert dismiss the alert after the action runs. The default button is shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
If no actions are present, the system includes a standard “OK” action. No default cancel action is provided. If you want to show a cancel action, use a button with a role of cancel.
On iOS, tvOS, and watchOS, alerts only support controls with labels that are Text. Passing any other type of view results in the content being omitted.
This modifier creates a Text view for the title on your behalf, and treats the localized key similar to init(_:tableName:bundle:comment:). See Text for more information about localizing strings.
See Also
Presenting an alert
struct AlertScene
A scene that renders itself as a standalone alert dialog.
func alert(_:isPresented:actions:)
Presents an alert when a given condition is true, using a text view for the title.
func alert(_:isPresented:presenting:actions:)
Presents an alert using the given data to produce the alert’s content and a text view as a title.
func alert(_:isPresented:actions:message:)
Presents an alert with a message when a given condition is true using a text view as a title.
func alert(_:isPresented:presenting:actions:message:)
Presents an alert with a message using the given data to produce the alert’s content and a text view for a title.
Presents an alert with a message when an error is present.
https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:actions:message:)
#app-main)
- SwiftUI
- View
- alert(_:isPresented:actions:message:)
Instance Method
alert(_:isPresented:actions:message:)
Presents an alert with a message when a given condition is true using a text view as a title.
nonisolated
_ title: Text,
Show all declarations
Parameters
title
The title of the alert.
isPresented
A binding to a Boolean value that determines whether to present the alert. When the user presses or taps one of the alert’s actions, the system sets this value to false and dismisses.
actions
A ViewBuilder returning the alert’s actions.
message
A ViewBuilder returning the message for the alert.
Discussion
In the example below, a login form conditionally presents an alert by setting the didFail state variable. When the form sets the value to to true, the system displays an alert with an “OK” action.
struct Login: View { @State private var didFail = false let alertTitle: String = "Login failed."
var body: some View { LoginForm(didFail: $didFail) .alert( Text(alertTitle), isPresented: $didFail ) { Button("OK") { // Handle the acknowledgement. } } message: { Text("Please check your credentials and try again.") } } }
All actions in an alert dismiss the alert after the action runs. The default button is shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
If no actions are present, the system includes a standard “OK” action. No default cancel action is provided. If you want to show a cancel action, use a button with a role of cancel.
On iOS, tvOS, and watchOS, alerts only support controls with labels that are Text. Passing any other type of view results in the content being omitted.
Only unstyled text is supported for the message.
See Also
Presenting an alert
struct AlertScene
A scene that renders itself as a standalone alert dialog.
func alert(_:isPresented:actions:)
Presents an alert when a given condition is true, using a text view for the title.
func alert(_:isPresented:presenting:actions:)
Presents an alert using the given data to produce the alert’s content and a text view as a title.
Presents an alert when an error is present.
func alert(_:isPresented:presenting:actions:message:)
Presents an alert with a message using the given data to produce the alert’s content and a text view for a title.
Presents an alert with a message when an error is present.
https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:message:)
#app-main)
- SwiftUI
- View
- alert(_:isPresented:presenting:actions:message:)
Instance Method
alert(_:isPresented:presenting:actions:message:)
Presents an alert with a message using the given data to produce the alert’s content and a text view for a title.
nonisolated
_ title: Text,
presenting data: T?,
Show all declarations
Parameters
title
The title of the alert.
isPresented
A binding to a Boolean value that determines whether to present the alert. When the user presses or taps one of the alert’s actions, the system sets this value to false and dismisses.
data
An optional source of truth for the alert. The system passes the contents to the modifier’s closures. You use this data to populate the fields of an alert that you create that the system displays to the user.
actions
A ViewBuilder returning the alert’s actions given the currently available data.
message
A ViewBuilder returning the message for the alert given the currently available data.
Discussion
For the alert to appear, both isPresented must be true and data must not be nil. The data should not change after the presentation occurs. Any changes that you make after the presentation occurs are ignored.
Use this method when you need to populate the fields of an alert with content from a data source. The example below shows a custom data source, SaveDetails, that provides data to populate the alert:
struct SaveDetails: Identifiable { let name: String let error: String let id = UUID() }
struct SaveButton: View { @State private var didError = false @State private var details: SaveDetails? let alertTitle: String = "Save failed."
var body: some View { Button("Save") { details = model.save(didError: $didError) } .alert( Text(alertTitle), isPresented: $didError, presenting: details ) { details in Button(role: .destructive) { // Handle the deletion. } label: { Text("Delete (details.name)") } Button("Retry") { // Handle the retry action. } } message: { details in Text(details.error) } } }
All actions in an alert dismiss the alert after the action runs. The default button is shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
If no actions are present, the system includes a standard “OK” action. No default cancel action is provided. If you want to show a cancel action, use a button with a role of cancel.
On iOS, tvOS, and watchOS, alerts only support controls with labels that are Text. Passing any other type of view results in the content being omitted.
Only unstyled text is supported for the message.
See Also
Presenting an alert
struct AlertScene
A scene that renders itself as a standalone alert dialog.
func alert(_:isPresented:actions:)
Presents an alert when a given condition is true, using a text view for the title.
func alert(_:isPresented:presenting:actions:)
Presents an alert using the given data to produce the alert’s content and a text view as a title.
Presents an alert when an error is present.
func alert(_:isPresented:actions:message:)
Presents an alert with a message when a given condition is true using a text view as a title.
Presents an alert with a message when an error is present.
https://developer.apple.com/documentation/swiftui/view/alert(ispresented:error:actions:message:)
#app-main)
- SwiftUI
- View
- alert(isPresented:error:actions:message:)
Instance Method
alert(isPresented:error:actions:message:)
Presents an alert with a message when an error is present.
nonisolated
error: E?,
Parameters
isPresented
A binding to a Boolean value that determines whether to present the alert. When the user presses or taps one of the alert’s actions, the system sets this value to false and dismisses.
error
An optional localized Error that is used to generate the alert’s title. The system passes the contents to the modifier’s closures. You use this data to populate the fields of an alert that you create that the system displays to the user.
actions
A ViewBuilder returning the alert’s actions.
message
A view builder returning the message for the alert given the current error.
Discussion
In the example below, a form conditionally presents an alert depending upon the value of an error. When the error value isn’t nil, the system presents an alert with an “OK” action.
The title of the alert is inferred from the error’s errorDescription.
struct TicketPurchase: View { @State private var error: TicketPurchaseError? = nil @State private var showAlert = false
var body: some View { TicketForm(showAlert: $showAlert, error: $error) .alert(isPresented: $showAlert, error: error) { _ in Button("OK") { // Handle acknowledgement. } } message: { error in Text(error.recoverySuggestion ?? "Try again later.") } } }
All actions in an alert dismiss the alert after the action runs. The default button is shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
If no actions are present, the system includes a standard “OK” action. No default cancel action is provided. If you want to show a cancel action, use a button with a role of cancel.
On iOS, tvOS, and watchOS, alerts only support controls with labels that are Text. Passing any other type of view results in the content being omitted.
This modifier creates a Text view for the title on your behalf, and treats the localized key similar to init(_:tableName:bundle:comment:). See Text for more information about localizing strings.
See Also
Presenting an alert
struct AlertScene
A scene that renders itself as a standalone alert dialog.
func alert(_:isPresented:actions:)
Presents an alert when a given condition is true, using a text view for the title.
func alert(_:isPresented:presenting:actions:)
Presents an alert using the given data to produce the alert’s content and a text view as a title.
Presents an alert when an error is present.
func alert(_:isPresented:actions:message:)
Presents an alert with a message when a given condition is true using a text view as a title.
func alert(_:isPresented:presenting:actions:message:)
Presents an alert with a message using the given data to produce the alert’s content and a text view for a title.
https://developer.apple.com/documentation/swiftui/view/confirmationdialog(_:ispresented:titlevisibility:actions:)
#app-main)
- SwiftUI
- View
- confirmationDialog(_:isPresented:titleVisibility:actions:)
Instance Method
confirmationDialog(_:isPresented:titleVisibility:actions:)
Presents a confirmation dialog when a given condition is true, using a text view for the title.
nonisolated
_ title: Text,
titleVisibility: Visibility = .automatic,
Show all declarations
Parameters
title
The title of the dialog.
isPresented
A binding to a Boolean value that determines whether to present the dialog. When the user presses or taps the dialog’s default action button, the system sets this value to false, dismissing the dialog.
titleVisibility
The visibility of the dialog’s title. The default value is Visibility.automatic.
actions
A view builder returning the dialog’s actions.
Discussion
In the example below, a button conditionally presents a confirmation dialog depending upon the value of a bound Boolean variable. When the Boolean value is set to true, the system displays a confirmation dialog with a cancel action and a destructive action.
struct ConfirmEraseItems: View { @State private var isShowingDialog = false var body: some View { Button("Empty Trash") { isShowingDialog = true } .confirmationDialog( Text("Permanently erase the items in the trash?"), isPresented: $isShowingDialog ) { Button("Empty Trash", role: .destructive) { // Handle empty trash action. } } } }
All actions in a confirmation dialog will dismiss the dialog after the action runs. The default button will be shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
Dialogs include a standard dismiss action by default. If you provide a button with a role of cancel, that button takes the place of the default dismiss action. You don’t have to dismiss the presentation with the cancel button’s action.
See Also
Getting confirmation for an action
func confirmationDialog(_:isPresented:titleVisibility:presenting:actions:)
Presents a confirmation dialog using data to produce the dialog’s content and a text view for the title.
func dismissalConfirmationDialog(_:shouldPresent:actions:)
Presents a confirmation dialog when a dismiss action has been triggered.
https://developer.apple.com/documentation/swiftui/view/confirmationdialog(_:ispresented:titlevisibility:presenting:actions:)
#app-main)
- SwiftUI
- View
- confirmationDialog(_:isPresented:titleVisibility:presenting:actions:)
Instance Method
confirmationDialog(_:isPresented:titleVisibility:presenting:actions:)
Presents a confirmation dialog using data to produce the dialog’s content and a text view for the title.
nonisolated
_ title: Text,
titleVisibility: Visibility = .automatic, presenting data: T?,
Show all declarations
Parameters
title
The title of the dialog.
isPresented
A binding to a Boolean value that determines whether to present the dialog. When the user presses or taps the dialog’s default action button, the system sets this value to false, dismissing the dialog.
titleVisibility
The visibility of the dialog’s title. The default value is Visibility.automatic.
data
An optional source of truth for the confirmation dialog. The system passes the contents to the modifier’s closures. You use this data to populate the fields of a confirmation dialog that you create that the system displays to the user.
actions
A view builder returning the dialog’s actions given the currently available data.
Discussion
In order for the interface to appear, both isPresented must be true and data must not be nil. data should not change after the presentation occurs. Any changes which occur after the presentation occurs will be ignored.
Use this method when you need to populate the fields of a confirmation dialog with content from a data source. The example below shows a custom data source, FileDetails, that provides data to populate the dialog:
struct FileDetails: Identifiable { var id: String { name } let name: String let fileType: UTType } struct ConfirmFileImport: View { @State private var isConfirming = false @State private var dialogDetail: FileDetails? var body: some View { Button("Import File") { dialogDetail = FileDetails( name: "MyImageFile.png", fileType: .png) isConfirming = true } .confirmationDialog( Text("Import New File?"), isPresented: $isConfirming, presenting: dialogDetail ) { detail in Button { // Handle import action. } label: { Text(""" Import (detail.name) File Type: (detail.fileType.description) """) } Button("Cancel", role: .cancel) { dialogDetail = nil } } } }
All actions in a confirmation dialog will dismiss the dialog after the action runs. The default button will be shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
Dialogs include a standard dismiss action by default. If you provide a button with a role of cancel, that button takes the place of the default dismiss action. You don’t have to dismiss the presentation with the cancel button’s action.
On iOS, tvOS, and watchOS, confirmation dialogs only support controls with labels that are Text. Passing any other type of view results in the content being omitted.
See Also
Getting confirmation for an action
func confirmationDialog(_:isPresented:titleVisibility:actions:)
Presents a confirmation dialog when a given condition is true, using a text view for the title.
func dismissalConfirmationDialog(_:shouldPresent:actions:)
Presents a confirmation dialog when a dismiss action has been triggered.
https://developer.apple.com/documentation/swiftui/view/dismissalconfirmationdialog(_:shouldpresent:actions:)
#app-main)
- SwiftUI
- View
- dismissalConfirmationDialog(_:shouldPresent:actions:)
Instance Method
dismissalConfirmationDialog(_:shouldPresent:actions:)
Presents a confirmation dialog when a dismiss action has been triggered.
nonisolated
_ title: Text, shouldPresent: Bool,
Show all declarations
Parameters
title
The title of the dialog.
shouldPresent
A a Boolean value that determines whether to present the dialog upon dismissal.
actions
A view builder returning the dialog’s actions.
Discussion
On macOS, the dialog will be presented when attempting to dismiss the window for this view.
For example, you could present a dialog asking to persist unsaved changes:
struct ComposeMessage: View { @State private var message = Message()
var body: some View {
MessageEditor(message: $message)
.dismissalConfirmationDialog(
"Save This Message As Draft?",
shouldPresent: message.hasUnsavedChanges
) {
Button("Save") {
message.save()
}
Button("Don't Save", role: .destructive) {
message.discard()
}
} message: {
Text(
"""
This message has not been sent and contains
unsaved changes.
""")
}
}
All actions in the dialog will dismiss the dialog after the action runs. The default button will be shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
Dismissal dialogs include a standard cancellation action by default. If you provide a button with a role of cancel, that button takes the place of the default cancellation action.
The cancellation action will always prevent the dismissal, while other actions will allow the dismiss to proceed.
See Also
Getting confirmation for an action
func confirmationDialog(_:isPresented:titleVisibility:actions:)
Presents a confirmation dialog when a given condition is true, using a text view for the title.
func confirmationDialog(_:isPresented:titleVisibility:presenting:actions:)
Presents a confirmation dialog using data to produce the dialog’s content and a text view for the title.
https://developer.apple.com/documentation/swiftui/view/confirmationdialog(_:ispresented:titlevisibility:actions:message:)
#app-main)
- SwiftUI
- View
- confirmationDialog(_:isPresented:titleVisibility:actions:message:)
Instance Method
confirmationDialog(_:isPresented:titleVisibility:actions:message:)
Presents a confirmation dialog with a message when a given condition is true, using a text view for the title.
nonisolated
_ title: Text,
titleVisibility: Visibility = .automatic,
Show all declarations
Parameters
title
The title of the dialog.
isPresented
A binding to a Boolean value that determines whether to present the dialog. When the user presses or taps the dialog’s default action button, the system sets this value to false, dismissing the dialog.
titleVisibility
The visibility of the dialog’s title. The default value is Visibility.automatic.
actions
A view builder returning the dialog’s actions.
message
A view builder returning the message for the dialog.
Discussion
In the example below, a button conditionally presents a confirmation dialog depending upon the value of a bound Boolean variable. When the Boolean value is set to true, the system displays a confirmation dialog with a cancel action and a destructive action.
struct ConfirmEraseItems: View { @State private var isShowingDialog = false var body: some View { Button("Empty Trash") { isShowingDialog = true } .confirmationDialog( Text("Permanently erase the items in the trash?"), isPresented: $isShowingDialog ) { Button("Empty Trash", role: .destructive) { // Handle empty trash action. } } message: { Text("You cannot undo this action.") } } }
All actions in a confirmation dialog will dismiss the dialog after the action runs. The default button will be shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
Dialogs include a standard dismiss action by default. If you provide a button with a role of cancel, that button takes the place of the default dismiss action. You don’t have to dismiss the presentation with the cancel button’s action.
See Also
Showing a confirmation dialog with a message
func confirmationDialog(_:isPresented:titleVisibility:presenting:actions:message:)
Presents a confirmation dialog with a message using data to produce the dialog’s content and a text view for the message.
func dismissalConfirmationDialog(_:shouldPresent:actions:message:)
Presents a confirmation dialog when a dismiss action has been triggered.
https://developer.apple.com/documentation/swiftui/view/confirmationdialog(_:ispresented:titlevisibility:presenting:actions:message:)
#app-main)
- SwiftUI
- View
- confirmationDialog(_:isPresented:titleVisibility:presenting:actions:message:)
Instance Method
confirmationDialog(_:isPresented:titleVisibility:presenting:actions:message:)
Presents a confirmation dialog with a message using data to produce the dialog’s content and a text view for the message.
nonisolated
_ title: Text,
titleVisibility: Visibility = .automatic, presenting data: T?,
Show all declarations
Parameters
title
The title of the dialog.
isPresented
A binding to a Boolean value that determines whether to present the dialog. When the user presses or taps the dialog’s default action button, the system sets this value to false, dismissing the dialog.
titleVisibility
The visibility of the dialog’s title. The default value is Visibility.automatic.
data
An optional source of truth for the confirmation dialog. The system passes the contents to the modifier’s closures. You use this data to populate the fields of a confirmation dialog that you create that the system displays to the user.
actions
A view builder returning the dialog’s actions given the currently available data.
message
A view builder returning the message for the dialog given the currently available data.
Discussion
In order for the interface to appear, both isPresented must be true and data must not be nil. data should not change after the presentation occurs. Any changes which occur after the presentation occurs will be ignored.
Use this method when you need to populate the fields of a confirmation dialog with content from a data source. The example below shows a custom data source, FileDetails, that provides data to populate the dialog:
struct FileDetails: Identifiable {
var id: String { name }
let name: String
let fileType: UTType
}
struct ConfirmFileImport: View {
@State private var isConfirming = false
@State private var dialogDetail: FileDetails?
var body: some View {
Button("Import File") {
dialogDetail = FileDetails(
name: "MyImageFile.png", fileType: .png)
isConfirming = true
}
.confirmationDialog(
Text("Import New File?"),
isPresented: $isConfirming, presenting: dialogDetail
) { detail in
Button {
// Handle import action.
} label: {
Text("Import (detail.name)")
}
Button("Cancel", role: .cancel) {
dialogDetail = nil
}
} message: { detail in
Text(
"""
This will add (detail.name).(detail.fileType)
to your library.
""")
}
}
}
All actions in a confirmation dialog will dismiss the dialog after the action runs. The default button will be shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
Dialogs include a standard dismiss action by default. If you provide a button with a role of cancel, that button takes the place of the default dismiss action. You don’t have to dismiss the presentation with the cancel button’s action.
On iOS, tvOS, and watchOS, confirmation dialogs only support controls with labels that are Text. Passing any other type of view results in the content being omitted.
See Also
Showing a confirmation dialog with a message
func confirmationDialog(_:isPresented:titleVisibility:actions:message:)
Presents a confirmation dialog with a message when a given condition is true, using a text view for the title.
func dismissalConfirmationDialog(_:shouldPresent:actions:message:)
Presents a confirmation dialog when a dismiss action has been triggered.
https://developer.apple.com/documentation/swiftui/view/dismissalconfirmationdialog(_:shouldpresent:actions:message:)
#app-main)
- SwiftUI
- View
- dismissalConfirmationDialog(_:shouldPresent:actions:message:)
Instance Method
dismissalConfirmationDialog(_:shouldPresent:actions:message:)
Presents a confirmation dialog when a dismiss action has been triggered.
nonisolated
_ title: Text, shouldPresent: Bool,
Show all declarations
Parameters
title
The title of the dialog.
shouldPresent
A a Boolean value that determines whether to present the dialog upon dismissal.
actions
A view builder returning the dialog’s actions.
message
A view builder returning the message for the dialog.
Discussion
On macOS, the dialog will be presented when attempting to dismiss the window for this view.
For example, you could present a dialog asking to persist unsaved changes:
struct ComposeMessage: View { @State private var message = Message()
var body: some View {
MessageEditor(message: $message)
.dismissalConfirmationDialog(
"Save This Message As Draft?",
shouldPresent: message.hasUnsavedChanges
) {
Button("Save") {
message.save()
}
Button("Don't Save", role: .destructive) {
message.discard()
}
} message: {
Text(
"""
This message has not been sent and contains
unsaved changes.
""")
}
}
All actions in the dialog will dismiss the dialog after the action runs. The default button will be shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.
The system may reorder the buttons based on their role and prominence.
Dismissal dialogs include a standard cancellation action by default. If you provide a button with a role of cancel, that button takes the place of the default cancellation action.
The cancellation action will always prevent the dismissal, while other actions will allow the dismiss to proceed.
See Also
Showing a confirmation dialog with a message
func confirmationDialog(_:isPresented:titleVisibility:actions:message:)
Presents a confirmation dialog with a message when a given condition is true, using a text view for the title.
func confirmationDialog(_:isPresented:titleVisibility:presenting:actions:message:)
Presents a confirmation dialog with a message using data to produce the dialog’s content and a text view for the message.
https://developer.apple.com/documentation/swiftui/view/dialogicon(_:)
#app-main)
- SwiftUI
- View
- dialogIcon(_:)
Instance Method
dialogIcon(_:)
Configures the icon used by dialogs within this view.
nonisolated
Parameters
icon
The custom icon to use for confirmation dialogs and alerts. Passing nil will use the default app icon.
Discussion
On macOS, this icon replaces the default icon of the app.
On watchOS, this icon will be shown in any dialogs presented.
This modifier has no effect on other platforms.
The following example configures a confirmationDialog with a custom image.
Button("Delete items") { isShowingDialog = true } .confirmationDialog( "Are you sure you want to erase these items?", isPresented: $isShowingDialog ) { Button("Erase", role: .destructive) { // Handle item deletion. } Button("Cancel", role: .cancel) { isShowingDialog = false } } .dialogIcon(Image(...))
See Also
Configuring a dialog
Configures the icon used by alerts.
Sets the severity for alerts.
Enables user suppression of dialogs and alerts presented within self, with a default suppression message on macOS. Unused on other platforms.
Enables user suppression of an alert with a custom suppression message.
func dialogSuppressionToggle(_:isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a custom suppression message on macOS. Unused on other platforms.
https://developer.apple.com/documentation/swiftui/scene/dialogicon(_:)
#app-main)
- SwiftUI
- Scene
- dialogIcon(_:)
Instance Method
dialogIcon(_:)
Configures the icon used by alerts.
nonisolated
Parameters
icon
The custom icon to use for the alert. Passing nil will use the default app icon.
Discussion
In macOS, this icon replaces the default icon of the app.
struct MyApp: App { @State private var isShowingDialog = false
var body: some Scene { Window(...) { Button("Delete items") { isShowingDialog = true } }
AlertScene( "Are you sure you want to erase these items?", isPresented: $isShowingDialog ) { Button("Erase", role: .destructive) { // Handle item deletion. } Button("Cancel", role: .cancel) { // Handle cancellation } } .dialogIcon(Image(Trash.png)) } }
See Also
Configuring a dialog
Configures the icon used by dialogs within this view.
Sets the severity for alerts.
Enables user suppression of dialogs and alerts presented within self, with a default suppression message on macOS. Unused on other platforms.
Enables user suppression of an alert with a custom suppression message.
func dialogSuppressionToggle(_:isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a custom suppression message on macOS. Unused on other platforms.
https://developer.apple.com/documentation/swiftui/view/dialogseverity(_:)
#app-main)
- SwiftUI
- View
- dialogSeverity(_:)
Instance Method
dialogSeverity(_:)
nonisolated
Parameters
severity
The severity to use for confirmation dialogs and alerts.
See Also
Configuring a dialog
Configures the icon used by dialogs within this view.
Configures the icon used by alerts.
Sets the severity for alerts.
Enables user suppression of dialogs and alerts presented within self, with a default suppression message on macOS. Unused on other platforms.
Enables user suppression of an alert with a custom suppression message.
func dialogSuppressionToggle(_:isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a custom suppression message on macOS. Unused on other platforms.
https://developer.apple.com/documentation/swiftui/scene/dialogseverity(_:)
#app-main)
- SwiftUI
- Scene
- dialogSeverity(_:)
Instance Method
dialogSeverity(_:)
Sets the severity for alerts.
nonisolated
Parameters
severity
The severity to use for alerts.
Discussion
The following example configures an alert for erasing some number of items. Since this operation is destructive and non-recoverable, a .critical severity is used.
struct MyApp: App { @State private var isShowingDialog = false
var body: some Scene { Window(...) { Button("Delete items") { isShowingDialog = true } }
AlertScene( "Are you sure you want to erase these items?", isPresented: $isShowingDialog ) { Button("Erase", role: .destructive) { // Handle item deletion. } Button("Cancel", role: .cancel) { // Handle cancellation } } .dialogSeverity(.critical) } }
See Also
Configuring a dialog
Configures the icon used by dialogs within this view.
Configures the icon used by alerts.
Enables user suppression of dialogs and alerts presented within self, with a default suppression message on macOS. Unused on other platforms.
Enables user suppression of an alert with a custom suppression message.
func dialogSuppressionToggle(_:isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a custom suppression message on macOS. Unused on other platforms.
https://developer.apple.com/documentation/swiftui/view/dialogsuppressiontoggle(issuppressed:)
#app-main)
- SwiftUI
- View
- dialogSuppressionToggle(isSuppressed:)
Instance Method
dialogSuppressionToggle(isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a default suppression message on macOS. Unused on other platforms.
nonisolated
Parameters
isSuppressed
Whether the suppression toggle is on or off in the dialog.
Discussion
Applying dialog suppression adds a toggle to dialogs on macOS, which allows the user to request the alert not be displayed again. Typically whether a dialog is suppressed is stored in AppStorage and used to decide whether to present the dialog in the future.
The following example configures a confirmationDialog with a suppression toggle. The toggle’s state is stored in AppStorage and used to determine whether or not to show the dialog when the “Delete Items” button is pressed.
struct ConfirmEraseItems: View { @State private var isShowingDialog = false
@AppStorage("suppressEraseItemAlert") private var suppressAlert = false
var body: some View { Button("Delete Items") { if !suppressAlert { isShowingDialog = true } else { // Handle item deletion. } } .confirmationDialog( "Are you sure you want to erase these items?", isPresented: $isShowingDialog ) { Button("Erase", role: .destructive) { // Handle item deletion. } Button("Cancel", role: .cancel) { isShowingDialog = false } } .dialogSuppressionToggle(isSuppressed: $suppressAlert) } }
See Also
Configuring a dialog
Configures the icon used by dialogs within this view.
Configures the icon used by alerts.
Sets the severity for alerts.
Enables user suppression of an alert with a custom suppression message.
func dialogSuppressionToggle(_:isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a custom suppression message on macOS. Unused on other platforms.
https://developer.apple.com/documentation/swiftui/scene/dialogsuppressiontoggle(issuppressed:)
#app-main)
- SwiftUI
- Scene
- dialogSuppressionToggle(isSuppressed:)
Instance Method
dialogSuppressionToggle(isSuppressed:)
Enables user suppression of an alert with a custom suppression message.
nonisolated
Parameters
isSuppressed
Whether the suppression toggle is on or off in the dialog.
Discussion
Applying dialog suppression adds a toggle to dialogs on macOS, which allows the user to request the alert not be displayed again. Typically whether a dialog is suppressed is stored in AppStorage and used to decide whether to present the dialog in the future.
The following example configures an alert with a suppression toggle. The toggle’s state is stored in AppStorage and used to determine whether or not to show the dialog when the “Delete Items” button is pressed.
struct MyApp: App { @State private var isShowingDialog = false @AppStorage("suppressEraseItemAlert") private var suppressAlert = false
var body: some Scene { Window(...) { Button("Delete items") { isShowingDialog = true } }
AlertScene( "Are you sure you want to erase these items?", isPresented: $isShowingDialog ) { Button("Erase", role: .destructive) { // Handle item deletion. } Button("Cancel", role: .cancel) { // Handle cancellation } } .dialogSuppressionToggle( "Do not ask about erasing items again", isSuppressed: $suppressAlert) } }
See Also
Configuring a dialog
Configures the icon used by dialogs within this view.
Configures the icon used by alerts.
Sets the severity for alerts.
Enables user suppression of dialogs and alerts presented within self, with a default suppression message on macOS. Unused on other platforms.
func dialogSuppressionToggle(_:isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a custom suppression message on macOS. Unused on other platforms.
https://developer.apple.com/documentation/swiftui/view/dialogsuppressiontoggle(_:issuppressed:)
#app-main)
- SwiftUI
- View
- dialogSuppressionToggle(_:isSuppressed:)
Instance Method
dialogSuppressionToggle(_:isSuppressed:)
Enables user suppression of dialogs and alerts presented within self, with a custom suppression message on macOS. Unused on other platforms.
nonisolated func dialogSuppressionToggle( _ label: Text,
Show all declarations
Parameters
label
The label of the suppression toggle in the dialog. This parameter can be elided to use the default suppression title.
isSuppressed
Whether the suppression toggle is on or off in the dialog.
Discussion
Applying dialog suppression adds a toggle to dialogs on macOS, which allows the user to request the alert not be displayed again. Typically whether a dialog is suppressed is stored in AppStorage and used to decide whether to present the dialog in the future.
The following example configures a confirmationDialog with a suppression toggle. The toggle’s state is stored in AppStorage and used to determine whether or not to show the dialog when the “Delete Items” button is pressed.
struct ConfirmEraseItems: View { @State private var isShowingDialog = false
@AppStorage("suppressEraseItemAlert") private var suppressAlert = false
var body: some View { Button("Delete Items") { if !suppressAlert { isShowingDialog = true } else { // Handle item deletion. } } .confirmationDialog( "Are you sure you want to erase these items?", isPresented: $isShowingDialog ) { Button("Erase", role: .destructive) { // Handle item deletion. } Button("Cancel", role: .cancel) { isShowingDialog = false } } .dialogSuppressionToggle( Text("Do not ask about erasing items again"), isSuppressed: $suppressAlert) } }
See Also
Configuring a dialog
Configures the icon used by dialogs within this view.
Configures the icon used by alerts.
Sets the severity for alerts.
Enables user suppression of dialogs and alerts presented within self, with a default suppression message on macOS. Unused on other platforms.
Enables user suppression of an alert with a custom suppression message.
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:document:contenttype:defaultfilename:oncompletion:)
#app-main)
- SwiftUI
- View
- fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)
Instance Method
fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)
Presents a system interface for exporting a document that’s stored in a value type, like a structure, to a file on disk.
nonisolated
document: D?, contentType: UTType, defaultFilename: String? = nil,
Show all declarations
Parameters
isPresented
A binding to whether the interface should be shown.
document
The in-memory document to export.
contentType
The content type to use for the exported file.
defaultFilename
If provided, the default name to use for the exported file, which will the user will have an opportunity to edit prior to the export.
onCompletion
A callback that will be invoked when the operation has has succeeded or failed.
Discussion
In order for the interface to appear, both isPresented must be true and document must not be nil. When the operation is finished, isPresented will be set to false before onCompletion is called. If the user cancels the operation, isPresented will be set to false and onCompletion will not be called.
The contentType provided must be included within the document type’s writableContentTypes, otherwise the first valid writable content type will be used instead.
See Also
Exporting to file
func fileExporter(isPresented:documents:contentType:onCompletion:)
Presents a system interface for exporting a collection of value type documents to files on disk.
func fileExporter(isPresented:document:contentTypes:defaultFilename:onCompletion:onCancellation:)
Presents a system interface for allowing the user to export a FileDocument to a file on disk.
func fileExporter(isPresented:documents:contentTypes:onCompletion:onCancellation:)
Presents a system dialog for allowing the user to export a collection of documents that conform to FileDocument to files on disk.
Presents a system interface allowing the user to export a Transferable item to file on disk.
Presents a system interface allowing the user to export a collection of items to files on disk.
func fileExporterFilenameLabel(_:)
On macOS, configures the fileExporter with a label for the file name field.
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:documents:contenttype:oncompletion:)
#app-main)
- SwiftUI
- View
- fileExporter(isPresented:documents:contentType:onCompletion:)
Instance Method
fileExporter(isPresented:documents:contentType:onCompletion:)
Presents a system interface for exporting a collection of value type documents to files on disk.
nonisolated
documents: C, contentType: UTType,
Show all declarations
Parameters
isPresented
A binding to whether the interface should be shown.
documents
The collection of in-memory documents to export.
contentType
The content type to use for the exported file.
onCompletion
A callback that will be invoked when the operation has has succeeded or failed.
Discussion
In order for the interface to appear, both isPresented must be true and documents must not be empty. When the operation is finished, isPresented will be set to false before onCompletion is called. If the user cancels the operation, isPresented will be set to false and onCompletion will not be called.
The contentType provided must be included within the document type’s writableContentTypes, otherwise the first valid writable content type will be used instead.
See Also
Exporting to file
func fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)
Presents a system interface for exporting a document that’s stored in a value type, like a structure, to a file on disk.
func fileExporter(isPresented:document:contentTypes:defaultFilename:onCompletion:onCancellation:)
Presents a system interface for allowing the user to export a FileDocument to a file on disk.
func fileExporter(isPresented:documents:contentTypes:onCompletion:onCancellation:)
Presents a system dialog for allowing the user to export a collection of documents that conform to FileDocument to files on disk.
Presents a system interface allowing the user to export a Transferable item to file on disk.
Presents a system interface allowing the user to export a collection of items to files on disk.
func fileExporterFilenameLabel(_:)
On macOS, configures the fileExporter with a label for the file name field.
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:document:contenttypes:defaultfilename:oncompletion:oncancellation:)
#app-main)
- SwiftUI
- View
- fileExporter(isPresented:document:contentTypes:defaultFilename:onCompletion:onCancellation:)
Instance Method
fileExporter(isPresented:document:contentTypes:defaultFilename:onCompletion:onCancellation:)
Presents a system interface for allowing the user to export a FileDocument to a file on disk.
nonisolated
document: D?, contentTypes: [UTType] = [], defaultFilename: String? = nil,
Show all declarations
Parameters
isPresented
A binding to whether the interface should be shown.
document
The in-memory document to export.
contentTypes
The list of supported content types which can be exported. If not provided, FileDocument.writableContentTypes are used.
defaultFilename
If provided, the default name to use for the exported file, which will the user will have an opportunity to edit prior to the export.
onCompletion
A callback that will be invoked when the operation has succeeded or failed. The result indicates whether the operation succeeded or failed.
onCancellation
A callback that will be invoked if the user cancels the operation.
Discussion
In order for the interface to appear, isPresented must be true. When the operation is finished, isPresented will be set to false before onCompletion is called. If the user cancels the operation, isPresented will be set to false and onCancellation will be called.
See Also
Exporting to file
func fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)
Presents a system interface for exporting a document that’s stored in a value type, like a structure, to a file on disk.
func fileExporter(isPresented:documents:contentType:onCompletion:)
Presents a system interface for exporting a collection of value type documents to files on disk.
func fileExporter(isPresented:documents:contentTypes:onCompletion:onCancellation:)
Presents a system dialog for allowing the user to export a collection of documents that conform to FileDocument to files on disk.
Presents a system interface allowing the user to export a Transferable item to file on disk.
Presents a system interface allowing the user to export a collection of items to files on disk.
func fileExporterFilenameLabel(_:)
On macOS, configures the fileExporter with a label for the file name field.
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:documents:contenttypes:oncompletion:oncancellation:)
#app-main)
- SwiftUI
- View
- fileExporter(isPresented:documents:contentTypes:onCompletion:onCancellation:)
Instance Method
fileExporter(isPresented:documents:contentTypes:onCompletion:onCancellation:)
Presents a system dialog for allowing the user to export a collection of documents that conform to FileDocument to files on disk.
nonisolated
documents: C, contentTypes: [UTType] = [],
Show all declarations
Parameters
isPresented
A binding to whether the dialog should be shown.
documents
The in-memory documents to export.
contentTypes
The list of supported content types which can be exported. If not provided, FileDocument.writableContentTypes are used.
onCompletion
A callback that will be invoked when the operation has succeeded or failed. The result indicates whether the operation succeeded or failed.
onCancellation
A callback that will be invoked if the user cancels the operation.
Discussion
In order for the dialog to appear, isPresented must be true. When the operation is finished, isPresented will be set to false before onCompletion is called. If the user cancels the operation, isPresented will be set to false and onCancellation will be called.
See Also
Exporting to file
func fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)
Presents a system interface for exporting a document that’s stored in a value type, like a structure, to a file on disk.
func fileExporter(isPresented:documents:contentType:onCompletion:)
Presents a system interface for exporting a collection of value type documents to files on disk.
func fileExporter(isPresented:document:contentTypes:defaultFilename:onCompletion:onCancellation:)
Presents a system interface for allowing the user to export a FileDocument to a file on disk.
Presents a system interface allowing the user to export a Transferable item to file on disk.
Presents a system interface allowing the user to export a collection of items to files on disk.
func fileExporterFilenameLabel(_:)
On macOS, configures the fileExporter with a label for the file name field.
https://developer.apple.com/documentation/swiftui/view/fileexporterfilenamelabel(_:)
#app-main)
- SwiftUI
- View
- fileExporterFilenameLabel(_:)
Instance Method
fileExporterFilenameLabel(_:)
On macOS, configures the fileExporter with a label for the file name field.
nonisolated
Show all declarations
Parameters
label
The localized string resource to display.
See Also
Exporting to file
func fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)
Presents a system interface for exporting a document that’s stored in a value type, like a structure, to a file on disk.
func fileExporter(isPresented:documents:contentType:onCompletion:)
Presents a system interface for exporting a collection of value type documents to files on disk.
func fileExporter(isPresented:document:contentTypes:defaultFilename:onCompletion:onCancellation:)
Presents a system interface for allowing the user to export a FileDocument to a file on disk.
func fileExporter(isPresented:documents:contentTypes:onCompletion:onCancellation:)
Presents a system dialog for allowing the user to export a collection of documents that conform to FileDocument to files on disk.
Presents a system interface allowing the user to export a Transferable item to file on disk.
Presents a system interface allowing the user to export a collection of items to files on disk.
https://developer.apple.com/documentation/swiftui/view/filemover(ispresented:file:oncompletion:)
#app-main)
- SwiftUI
- View
- fileMover(isPresented:file:onCompletion:)
Instance Method
fileMover(isPresented:file:onCompletion:)
Presents a system interface for allowing the user to move an existing file to a new location.
nonisolated func fileMover(
file: URL?,
Parameters
isPresented
A binding to whether the interface should be shown.
file
The URL of the file to be moved.
onCompletion
A callback that will be invoked when the operation has has succeeded or failed. To access the received URLs, call startAccessingSecurityScopedResource. When the access is no longer required, call stopAccessingSecurityScopedResource.
Discussion
In order for the interface to appear, both isPresented must be true and file must not be nil. When the operation is finished, isPresented will be set to false before onCompletion is called. If the user cancels the operation, isPresented will be set to false and onCompletion will not be called.
See Also
Moving a file
Presents a system interface for allowing the user to move a collection of existing files to a new location.
Presents a system dialog for allowing the user to move an existing file to a new location.
Presents a system dialog for allowing the user to move a collection of existing files to a new location.
https://developer.apple.com/documentation/swiftui/view/filemover(ispresented:file:oncompletion:oncancellation:)
#app-main)
- SwiftUI
- View
- fileMover(isPresented:file:onCompletion:onCancellation:)
Instance Method
fileMover(isPresented:file:onCompletion:onCancellation:)
Presents a system dialog for allowing the user to move an existing file to a new location.
nonisolated func fileMover(
file: URL?,
Parameters
isPresented
A binding to whether the dialog should be shown.
file
The URL of the file to be moved.
onCompletion
A callback that will be invoked when the operation has succeeded or failed. The result indicates whether the operation succeeded or failed. To access the received URLs, call startAccessingSecurityScopedResource. When the access is no longer required, call stopAccessingSecurityScopedResource.
onCancellation
A callback that will be invoked if the user cancels the operation.
Discussion
For example, a button that allows the user to move a file might look like this:
struct MoveFileButton: View { @State private var showFileMover = false var file: URL
var body: some View { Button { showFileMover = true } label: { Label("Choose destination", systemImage: "folder.circle") } .fileMover(isPresented: $showFileMover, file: file) { result in switch result { case .success(let url): guard url.startAccessingSecurityScopedResource() else { return } onCompletion(url) url.stopAccessingSecurityScopedResource() case .failure(let error): print(error) // handle error } } onCancellation: { onCancellation?() } } }
See Also
Moving a file
Presents a system interface for allowing the user to move an existing file to a new location.
Presents a system interface for allowing the user to move a collection of existing files to a new location.
Presents a system dialog for allowing the user to move a collection of existing files to a new location.
https://developer.apple.com/documentation/swiftui/view/filedialogbrowseroptions(_:)
#app-main)
- SwiftUI
- View
- fileDialogBrowserOptions(_:)
Instance Method
fileDialogBrowserOptions(_:)
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
nonisolated
Parameters
options
The search options to apply to a given file dialog.
See Also
Configuring a file dialog
func fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
func fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
struct FileDialogBrowserOptions
The way that file dialogs present the file system.
https://developer.apple.com/documentation/swiftui/view/filedialogconfirmationlabel(_:)
#app-main)
- SwiftUI
- View
- fileDialogConfirmationLabel(_:)
Instance Method
fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
nonisolated
Show all declarations
Parameters
label
The localized string resource to display.
See Also
Configuring a file dialog
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
func fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
struct FileDialogBrowserOptions
The way that file dialogs present the file system.
https://developer.apple.com/documentation/swiftui/view/filedialogcustomizationid(_:)
#app-main)
- SwiftUI
- View
- fileDialogCustomizationID(_:)
Instance Method
fileDialogCustomizationID(_:)
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
nonisolated
Parameters
id
An identifier of the configuration.
Discussion
Among other parameters, it stores the current directory, view style (e.g., Icons, List, Columns), recent places, and expanded window size. It enables a refined user experience; for example, when importing an image, the user might switch to the Icons view, but the List view could be more convenient in another context. The file dialog stores these settings and applies them every time before presenting the panel. If not provided, on every launch, the file dialog uses the default configuration.
See Also
Configuring a file dialog
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
func fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
func fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
struct FileDialogBrowserOptions
The way that file dialogs present the file system.
https://developer.apple.com/documentation/swiftui/view/filedialogdefaultdirectory(_:)
#app-main)
- SwiftUI
- View
- fileDialogDefaultDirectory(_:)
Instance Method
fileDialogDefaultDirectory(_:)
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
nonisolated
Parameters
defaultDirectory
The directory to show when the system file dialog launches. If the given file dialog has a fileDialogCustomizationID if stores the user-chosen directory and subsequently opens with it, ignoring the default value provided in this modifier.
See Also
Configuring a file dialog
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
func fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
func fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
struct FileDialogBrowserOptions
The way that file dialogs present the file system.
https://developer.apple.com/documentation/swiftui/view/filedialogimportsunresolvedaliases(_:)
#app-main)
- SwiftUI
- View
- fileDialogImportsUnresolvedAliases(_:)
Instance Method
fileDialogImportsUnresolvedAliases(_:)
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
nonisolated
Parameters
imports
A Boolean value that indicates if the application receives unresolved or resolved URLs when a user chooses aliases.
Discussion
By default, file dialogs resolve aliases and provide the URL of the item referred to by the chosen alias. This modifier allows control of this behavior: pass true if the application doesn’t want file dialog to resolve aliases.
See Also
Configuring a file dialog
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
func fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
func fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
struct FileDialogBrowserOptions
The way that file dialogs present the file system.
https://developer.apple.com/documentation/swiftui/view/filedialogmessage(_:)
#app-main)
- SwiftUI
- View
- fileDialogMessage(_:)
Instance Method
fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
nonisolated
Show all declarations
Parameters
message
The optional text to use as the file dialog message.
See Also
Configuring a file dialog
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
func fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
struct FileDialogBrowserOptions
The way that file dialogs present the file system.
https://developer.apple.com/documentation/swiftui/view/filedialogurlenabled(_:)
#app-main)
- SwiftUI
- View
- fileDialogURLEnabled(_:)
Instance Method
fileDialogURLEnabled(_:)
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
nonisolated
Parameters
predicate
The predicate that evaluates the URLs presented to the user to conditionally disable them. The implementation is expected to have constant complexity and should not access the files contents or metadata. A common use case is inspecting the path or the file name.
See Also
Configuring a file dialog
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
func fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
func fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
struct FileDialogBrowserOptions
The way that file dialogs present the file system.
https://developer.apple.com/documentation/swiftui/filedialogbrowseroptions
- SwiftUI
- FileDialogBrowserOptions
Structure
FileDialogBrowserOptions
The way that file dialogs present the file system.
struct FileDialogBrowserOptions
Overview
Apply the options using the fileDialogBrowserOptions(_:) modifier.
Topics
Getting browser options
static let displayFileExtensions: FileDialogBrowserOptions
On iOS, configures the fileExporter, fileImporter, or fileMover to show or hide file extensions. Default behavior is to hide them. On macOS, this option has no effect.
static let enumeratePackages: FileDialogBrowserOptions
Allows enumerating packages contents in contrast to the default behavior when packages are represented flatly, similar to files.
static let includeHiddenFiles: FileDialogBrowserOptions
Displays the files that are hidden by default.
Relationships
Conforms To
EquatableExpressibleByArrayLiteralOptionSetRawRepresentableSendableSendableMetatypeSetAlgebra
See Also
Configuring a file dialog
On macOS, configures the fileExporter, fileImporter, or fileMover to provide a refined URL search experience: include or exclude hidden files, allow searching by tag, etc.
func fileDialogConfirmationLabel(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom confirmation button label.
On macOS, configures the fileExporter, fileImporter, or fileMover to persist and restore the file dialog configuration.
Configures the fileExporter, fileImporter, or fileMover to open with the specified default directory.
On macOS, configures the fileExporter, fileImporter, or fileMover behavior when a user chooses an alias.
func fileDialogMessage(_:)
On macOS, configures the the fileExporter, fileImporter, or fileMover with a custom text that is presented to the user, similar to a title.
On macOS, configures the the fileImporter or fileMover to conditionally disable presented URLs.
https://developer.apple.com/documentation/swiftui/view/inspector(ispresented:content:)
#app-main)
- SwiftUI
- View
- inspector(isPresented:content:)
Instance Method
inspector(isPresented:content:)
Inserts an inspector at the applied position in the view hierarchy.
nonisolated
Parameters
isPresented
A binding to Bool controlling the presented state.
content
The inspector content.
Discussion
Apply this modifier to declare an inspector with a context-dependent presentation. For example, an inspector can present as a trailing column in a horizontally regular size class, but adapt to a sheet in a horizontally compact size class.
struct ShapeEditor: View { @State var presented: Bool = false var body: some View { MyEditorView() .inspector(isPresented: $presented) { TextTraitsInspectorView() } } }
See Also
Presenting an inspector
Sets a fixed, preferred width for the inspector containing this view when presented as a trailing column.
Sets a flexible, preferred width for the inspector in a trailing-column presentation.
https://developer.apple.com/documentation/swiftui/view/inspectorcolumnwidth(_:)
#app-main)
- SwiftUI
- View
- inspectorColumnWidth(_:)
Instance Method
inspectorColumnWidth(_:)
Sets a fixed, preferred width for the inspector containing this view when presented as a trailing column.
nonisolated
Parameters
width
The preferred fixed width for the inspector if presented as a trailing column.
Discussion
Apply this modifier on the content of a inspector(isPresented:content:) to specify a fixed preferred width for the trailing column. Use inspectorColumnWidth(min:ideal:max:) if you need to specify a flexible width.
The following example shows an editor interface with an inspector, which when presented as a trailing-column, has a fixed width of 225 points. The example also uses interactiveDismissDisabled(_:) to prevent the inspector from being collapsed by user action like dragging a divider.
MyEditorView() .inspector { TextTraitsInspectorView() .inspectorColumnWidth(225) .interactiveDismissDisabled() }
See Also
Presenting an inspector
Inserts an inspector at the applied position in the view hierarchy.
Sets a flexible, preferred width for the inspector in a trailing-column presentation.
https://developer.apple.com/documentation/swiftui/view/inspectorcolumnwidth(min:ideal:max:)
#app-main)
- SwiftUI
- View
- inspectorColumnWidth(min:ideal:max:)
Instance Method
inspectorColumnWidth(min:ideal:max:)
Sets a flexible, preferred width for the inspector in a trailing-column presentation.
nonisolated func inspectorColumnWidth( min: CGFloat? = nil, ideal: CGFloat, max: CGFloat? = nil
Parameters
min
The minimum allowed width for the trailing column inspector
ideal
The initial width of the inspector in the absence of state restoration. ideal influences the resulting width on macOS when a user double-clicks the divider on the leading edge of the inspector. clicks a divider to readjust
max
The maximum allowed width for the trailing column inspector
Discussion
Apply this modifier on the content of a inspector(isPresented:content:) to specify a preferred flexible width for the column. Use inspectorColumnWidth(_:) if you need to specify a fixed width.
The following example shows an editor interface with an inspector, which when presented as a trailing-column, has a preferred width of 225 points, maximum of 400, and a minimum of 150 at which point it will collapse, if allowed.
MyEditorView() .inspector { TextTraitsInspectorView() .inspectorColumnWidth(min: 150, ideal: 225, max: 400) }
Only some platforms enable flexible inspector columns. If you specify a width that the current presentation environment doesn’t support, SwiftUI may use a different width for your column.
See Also
Presenting an inspector
Inserts an inspector at the applied position in the view hierarchy.
Sets a fixed, preferred width for the inspector containing this view when presented as a trailing column.
https://developer.apple.com/documentation/swiftui/environmentvalues/ispresented
- SwiftUI
- EnvironmentValues
- isPresented
Instance Property
isPresented
A Boolean value that indicates whether the view associated with this environment is currently presented.
var isPresented: Bool { get }
Discussion
You can read this value like any of the other EnvironmentValues by creating a property with the Environment property wrapper:
@Environment(.isPresented) private var isPresented
Read the value inside a view if you need to know when SwiftUI presents that view. For example, you can take an action when SwiftUI presents a view by using the onChange(of:initial:_:) modifier:
.onChange(of: isPresented) { _, isPresented in if isPresented { // Do something when first presented. } }
This behaves differently than onAppear(perform:), which SwiftUI can call more than once for a given presentation, like when you navigate .
See Also
Dismissing a presentation
var dismiss: DismissAction
An action that dismisses the current presentation.
struct DismissAction
An action that dismisses a presentation.
Conditionally prevents interactive dismissal of presentations like popovers, sheets, and inspectors.
https://developer.apple.com/documentation/swiftui/view/interactivedismissdisabled(_:)
#app-main)
- SwiftUI
- View
- interactiveDismissDisabled(_:)
Instance Method
interactiveDismissDisabled(_:)
Conditionally prevents interactive dismissal of presentations like popovers, sheets, and inspectors.
nonisolated
Parameters
isDisabled
A Boolean value that indicates whether to prevent nonprogrammatic dismissal of the containing view hierarchy when presented in a sheet or popover.
Discussion
Users can dismiss certain kinds of presentations using built-in gestures. In particular, a user can dismiss a sheet by dragging it down, or a popover by clicking or tapping outside of the presented view. Use the interactiveDismissDisabled(_:) modifier to conditionally prevent this kind of dismissal. You typically do this to prevent the user from dismissing a presentation before providing needed data or completing a required action.
For instance, suppose you have a view that displays a licensing agreement that the user must acknowledge before continuing:
struct TermsOfService: View { @Binding var areTermsAccepted: Bool @Environment(.dismiss) private var dismiss
var body: some View { Form { Text("License Agreement") .font(.title) Text("Terms and conditions go here.") Button("Accept") { areTermsAccepted = true dismiss() } } } }
If you present this view in a sheet, the user can dismiss it by either tapping the button — which calls dismiss from its action closure — or by dragging the sheet down. To ensure that the user accepts the terms by tapping the button, disable interactive dismissal, conditioned on the areTermsAccepted property:
struct ContentView: View { @State private var isSheetPresented = false @State private var areTermsAccepted = false
var body: some View { Button("Use Service") { isSheetPresented = true } .sheet(isPresented: $isSheetPresented) { TermsOfService() .interactiveDismissDisabled(!areTermsAccepted) } } }
You can apply the modifier to any view in the sheet’s view hierarchy, including to the sheet’s top level view, as the example demonstrates, or to any child view, like the Form or the Accept Button.
The modifier has no effect on programmatic dismissal, which you can invoke by updating the Binding that controls the presentation, or by calling the environment’s dismiss action. On macOS, disabling interactive dismissal in a popover makes the popover nontransient.
See Also
Dismissing a presentation
var isPresented: Bool
A Boolean value that indicates whether the view associated with this environment is currently presented.
var dismiss: DismissAction
An action that dismisses the current presentation.
struct DismissAction
An action that dismisses a presentation.
https://developer.apple.com/documentation/swiftui/alert
- SwiftUI
- Alert Deprecated
Structure
Alert
A representation of an alert presentation.
iOS 13.0–26.0DeprecatediPadOS 13.0–26.0DeprecatedMac Catalyst 13.0–26.0DeprecatedmacOS 10.15–26.0DeprecatedtvOS 13.0–26.0DeprecatedvisionOS 1.0–26.0DeprecatedwatchOS 6.0–26.0Deprecated
struct Alert
Overview
Use an alert when you want the user to act in response to the state of the app or system. If you want the user to make a choice in response to their action, use an ActionSheet instead.
You show an alert by using the alert(isPresented:content:) view modifier to create an alert, which then appears whenever the bound isPresented value is true. The content closure you provide to this modifer produces a customized instance of the Alert type.
In the following example, a button presents a simple alert when tapped, by updating a local showAlert property that binds to the alert.
@State private var showAlert = false var body: some View { Button("Tap to show alert") { showAlert = true } .alert(isPresented: $showAlert) { Alert( title: Text("Current Location Not Available"), message: Text("Your current location can’t be " + "determined at this time.") ) } }
To customize the alert, add instances of the Alert.Button type, which provides standardized buttons for common tasks like canceling and performing destructive actions. The following example uses two buttons: a default button labeled “Try Again” that calls a saveWorkoutData method, and a “Delete” button that calls a destructive deleteWorkoutData method.
@State private var showAlert = false var body: some View { Button("Tap to show alert") { showAlert = true } .alert(isPresented: $showAlert) { Alert( title: Text("Unable to Save Workout Data"), message: Text("The connection to the server was lost."), primaryButton: .default( Text("Try Again"), action: saveWorkoutData ), secondaryButton: .destructive( Text("Delete"), action: deleteWorkoutData ) ) } }
The alert handles its own dismissal when the user taps one of the buttons in the alert, by setting the bound isPresented value
Creating an alert
init(title: Text, message: Text?, dismissButton: Alert.Button?)
Creates an alert with one button.
init(title: Text, message: Text?, primaryButton: Alert.Button, secondaryButton: Alert.Button)
Creates an alert with two buttons.
Creates a side by side button alert.
Specifying the button type
struct Button
A button that represents an operation of an alert presentation.
See Also
Deprecated modal presentations
struct ActionSheet
A representation of an action sheet presentation.
Deprecated
https://developer.apple.com/documentation/swiftui/actionsheet
- SwiftUI
- ActionSheet Deprecated
Structure
ActionSheet
A representation of an action sheet presentation.
iOS 13.0–26.0DeprecatediPadOS 13.0–26.0DeprecatedMac Catalyst 13.0–26.0DeprecatedtvOS 13.0–26.0DeprecatedvisionOS 1.0–26.0DeprecatedwatchOS 6.0–26.0Deprecated
struct ActionSheet
Overview
Use an action sheet when you want the user to make a choice between two or more options, in response to their own action. If you want the user to act in response to the state of the app or the system, rather than a user action, use an Alert instead.
You show an action sheet by using the actionSheet(isPresented:content:) view modifier to create an action sheet, which then appears whenever the bound isPresented value is true. The content closure you provide to this modifier produces a customized instance of the ActionSheet type. To supply the options, create instances of ActionSheet.Button to distinguish between ordinary options, destructive options, and cancellation of the user’s original action.
The action sheet handles its dismissal by setting the bound isPresented value ,
action: appendWorkout
)
]
)
}
}
The system may interpret the order of items as they appear in the buttons array to accommodate platform conventions. In this example, the Cancel button is the first member of the array, but the action sheet puts it in its standard position at the bottom of the sheet.
Topics
Creating an action sheet
init(title: Text, message: Text?, buttons: [ActionSheet.Button])
Creates an action sheet with the provided buttons.
Specifying the button type
typealias Button
A button representing an operation of an action sheet presentation.
See Also
Deprecated modal presentations
struct Alert
A representation of an alert presentation.
Deprecated
https://developer.apple.com/documentation/swiftui/dialogseverity)
https://developer.apple.com/documentation/swiftui/view/sheet(ispresented:ondismiss:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/sheet(item:ondismiss:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fullscreencover(ispresented:ondismiss:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fullscreencover(item:ondismiss:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/popover(item:attachmentanchor:arrowedge:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/popover(ispresented:attachmentanchor:arrowedge:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/popoverattachmentanchor)
https://developer.apple.com/documentation/swiftui/view/presentationcompactadaptation(horizontal:vertical:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/presentationcompactadaptation(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/presentationadaptation)
https://developer.apple.com/documentation/swiftui/view/presentationsizing(_:))
https://developer.apple.com/documentation/swiftui/presentationsizing)
https://developer.apple.com/documentation/swiftui/presentationsizingroot)
https://developer.apple.com/documentation/swiftui/presentationsizingcontext)
https://developer.apple.com/documentation/swiftui/view/presentationdetents(_:))
https://developer.apple.com/documentation/swiftui/view/presentationdetents(_:selection:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/presentationcontentinteraction(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/presentationdragindicator(_:))
https://developer.apple.com/documentation/swiftui/presentationdetent)
https://developer.apple.com/documentation/swiftui/custompresentationdetent)
https://developer.apple.com/documentation/swiftui/presentationcontentinteraction)
https://developer.apple.com/documentation/swiftui/view/presentationcornerradius(_:))
https://developer.apple.com/documentation/swiftui/view/presentationbackground(_:))
https://developer.apple.com/documentation/swiftui/view/presentationbackground(alignment:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/presentationbackgroundinteraction(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/presentationbackgroundinteraction)
https://developer.apple.com/documentation/swiftui/alertscene)
https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:actions:))
https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/alert(ispresented:error:actions:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:actions:message:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:message:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/alert(ispresented:error:actions:message:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/confirmationdialog(_:ispresented:titlevisibility:actions:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/confirmationdialog(_:ispresented:titlevisibility:presenting:actions:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/dismissalconfirmationdialog(_:shouldpresent:actions:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/confirmationdialog(_:ispresented:titlevisibility:actions:message:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/confirmationdialog(_:ispresented:titlevisibility:presenting:actions:message:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/dismissalconfirmationdialog(_:shouldpresent:actions:message:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/dialogicon(_:))
https://developer.apple.com/documentation/swiftui/scene/dialogicon(_:))
https://developer.apple.com/documentation/swiftui/view/dialogseverity(_:))
https://developer.apple.com/documentation/swiftui/scene/dialogseverity(_:))
https://developer.apple.com/documentation/swiftui/view/dialogsuppressiontoggle(issuppressed:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/scene/dialogsuppressiontoggle(issuppressed:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/dialogsuppressiontoggle(_:issuppressed:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:document:contenttype:defaultfilename:oncompletion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:documents:contenttype:oncompletion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:document:contenttypes:defaultfilename:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:documents:contenttypes:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:item:contenttypes:defaultfilename:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:items:contenttypes:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fileexporterfilenamelabel(_:))
https://developer.apple.com/documentation/swiftui/view/fileimporter(ispresented:allowedcontenttypes:allowsmultipleselection:oncompletion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fileimporter(ispresented:allowedcontenttypes:oncompletion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/fileimporter(ispresented:allowedcontenttypes:allowsmultipleselection:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/filemover(ispresented:file:oncompletion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/filemover(ispresented:files:oncompletion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/filemover(ispresented:file:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/filemover(ispresented:files:oncompletion:oncancellation:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/filedialogbrowseroptions(_:))
https://developer.apple.com/documentation/swiftui/view/filedialogconfirmationlabel(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/filedialogcustomizationid(_:))
https://developer.apple.com/documentation/swiftui/view/filedialogdefaultdirectory(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/filedialogimportsunresolvedaliases(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/filedialogmessage(_:))
https://developer.apple.com/documentation/swiftui/view/filedialogurlenabled(_:))
https://developer.apple.com/documentation/swiftui/filedialogbrowseroptions)
https://developer.apple.com/documentation/swiftui/view/inspector(ispresented:content:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/inspectorcolumnwidth(_:))
https://developer.apple.com/documentation/swiftui/view/inspectorcolumnwidth(min:ideal:max:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/environmentvalues/ispresented)
https://developer.apple.com/documentation/swiftui/view/interactivedismissdisabled(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/alert)
https://developer.apple.com/documentation/swiftui/actionsheet)
https://developer.apple.com/documentation/swiftui/view/toolbar(content:)
#app-main)
- SwiftUI
- View
- toolbar(content:)
Instance Method
toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
nonisolated
Show all declarations
Parameters
content
The items representing the content of the toolbar.
Discussion
Use this method to populate a toolbar with a collection of views that you provide to a toolbar view builder.
The toolbar modifier expects a collection of toolbar items which you can provide either by supplying a collection of views with each view wrapped in a ToolbarItem, or by providing a collection of views as a ToolbarItemGroup. The example below uses a collection of ToolbarItem views to create a macOS toolbar that supports text editing features:
struct StructToolbarItemGroupView: View { @State private var text = "" @State private var bold = false @State private var italic = false @State private var fontSize = 12.0
var displayFont: Font { let font = Font.system(size: CGFloat(fontSize), weight: bold == true ? .bold : .regular) return italic == true ? font.italic() : font }
var body: some View { TextEditor(text: $text) .font(displayFont) .toolbar { ToolbarItemGroup { Slider( value: $fontSize, in: 8...120, minimumValueLabel: Text("A").font(.system(size: 8)), maximumValueLabel: Text("A").font(.system(size: 16)) ) { Text("Font Size ((Int(fontSize)))") } .frame(width: 150) Toggle(isOn: $bold) { Image(systemName: "bold") } Toggle(isOn: $italic) { Image(systemName: "italic") } } } .navigationTitle("My Note") } }
Although it’s not mandatory, wrapping a related group of toolbar items together in a ToolbarItemGroup provides a one-to-one mapping between controls and toolbar items which results in the correct layout and spacing on each platform. For design guidance on toolbars, see Toolbars in the Human Interface Guidelines.
See Also
Populating a toolbar
struct ToolbarItem
A model that represents an item which can be placed in the toolbar or navigation bar.
struct ToolbarItemGroup
A model that represents a group of ToolbarItem s which can be placed in the toolbar or navigation bar.
struct ToolbarItemPlacement
A structure that defines the placement of a toolbar item.
protocol ToolbarContent
Conforming types represent items that can be placed in various locations in a toolbar.
struct ToolbarContentBuilder
Constructs a toolbar item set from multi-expression closures.
struct ToolbarSpacer
A standard space item in toolbars.
Beta
struct DefaultToolbarItem
A toolbar item that represents a system component.
https://developer.apple.com/documentation/swiftui/view/toolbar(_:for:)
#app-main)
- SwiftUI
- View
- toolbar(_:for:)
Instance Method
toolbar(_:for:)
Specifies the visibility of a bar managed by SwiftUI.
iOS 16.0–26.0DeprecatediPadOS 16.0–26.0DeprecatedMac Catalyst 16.0–26.0DeprecatedmacOS 13.0–26.0DeprecatedtvOS 16.0–26.0DeprecatedwatchOS 9.0–26.0Deprecated
nonisolated func toolbar( _ visibility: Visibility, for bars: ToolbarPlacement...
Parameters
visibility
The preferred visibility of the bar.
bars
The bars to update the visibility of or automatic if empty.
Discussion
The preferred visibility flows up to the nearest container that renders a bar. This could be a NavigationView or TabView in iOS, or the root view of a WindowGroup in macOS.
This examples shows a view that hides the navigation bar on iOS, or the window toolbar items on macOS.
NavigationView { ContentView() .toolbar(.hidden) }
To hide the entire titlebar on macOS, use this modifier with windowToolbar placement.
NavigationView { ContentView() .toolbar(.hidden, for: .windowToolbar) }
You can provide multiple ToolbarPlacement instances to hide multiple bars at once.
TabView { NavigationView { ContentView() .toolbar( .hidden, for: .navigationBar, .tabBar) } }
Depending on the specified bars, the requested visibility may not be able to be fulfilled.
See Also
Setting toolbar visibility
Specifies the preferred visibility of backgrounds on a bar managed by SwiftUI.
struct ToolbarPlacement
The placement of a toolbar.
struct ContentToolbarPlacement
https://developer.apple.com/documentation/swiftui/toolbaritem
- SwiftUI
- ToolbarItem
Structure
ToolbarItem
A model that represents an item which can be placed in the toolbar or navigation bar.
Topics
Creating a toolbar item
Creates a toolbar item with the specified placement and content.
Creates a toolbar item with the specified placement and content, which allows for user customization.
Deprecated
Relationships
Conforms To
-
Copyable -
CustomizableToolbarContentConforms whenIDisStringandContentconforms toView. -
Identifiable -
ToolbarContent
See Also
Populating a toolbar
func toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
struct ToolbarItemGroup
A model that represents a group of ToolbarItem s which can be placed in the toolbar or navigation bar.
struct ToolbarItemPlacement
A structure that defines the placement of a toolbar item.
protocol ToolbarContent
Conforming types represent items that can be placed in various locations in a toolbar.
struct ToolbarContentBuilder
Constructs a toolbar item set from multi-expression closures.
struct ToolbarSpacer
A standard space item in toolbars.
Beta
struct DefaultToolbarItem
A toolbar item that represents a system component.
https://developer.apple.com/documentation/swiftui/toolbaritemgroup
- SwiftUI
- ToolbarItemGroup
Structure
ToolbarItemGroup
A model that represents a group of ToolbarItem s which can be placed in the toolbar or navigation bar.
Topics
Creating a toolbar item group
Creates a toolbar item group with a specified placement and content.
Creates a toolbar item group with the specified placement, content, and a label describing that content.
Supporting types
struct LabeledToolbarItemGroupContent
A view that represents the view of a toolbar item group with a specified label.
Relationships
Conforms To
ToolbarContent
See Also
Populating a toolbar
func toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
struct ToolbarItem
A model that represents an item which can be placed in the toolbar or navigation bar.
struct ToolbarItemPlacement
A structure that defines the placement of a toolbar item.
protocol ToolbarContent
Conforming types represent items that can be placed in various locations in a toolbar.
struct ToolbarContentBuilder
Constructs a toolbar item set from multi-expression closures.
struct ToolbarSpacer
A standard space item in toolbars.
Beta
struct DefaultToolbarItem
A toolbar item that represents a system component.
https://developer.apple.com/documentation/swiftui/toolbaritemplacement
- SwiftUI
- ToolbarItemPlacement
Structure
ToolbarItemPlacement
A structure that defines the placement of a toolbar item.
struct ToolbarItemPlacement
Overview
There are two types of placements:
-
Semantic placements, such as
principalandnavigation, denote the intent of the item being added. SwiftUI determines the appropriate placement for the item based on this intent and its surrounding context, like the current platform. -
Positional placements, such as
navigationBarLeading, denote a precise placement for the item, usually for a particular platform.
In iOS, iPadOS, and macOS, the system uses the space available to the toolbar when determining how many items to render in the toolbar. If not all items fit in the available space, an overflow menu may be created and remaining items placed in that menu.
Topics
Getting semantic placement
static let automatic: ToolbarItemPlacement
The system places the item automatically, depending on many factors including the platform, size class, or presence of other items.
static let principal: ToolbarItemPlacement
The system places the item in the principal item section.
static let status: ToolbarItemPlacement
The item represents a change in status for the current context.
Getting placement for specific actions
static let primaryAction: ToolbarItemPlacement
The item represents a primary action.
static let secondaryAction: ToolbarItemPlacement
The item represents a secondary action.
static let confirmationAction: ToolbarItemPlacement
The item represents a confirmation action for a modal interface.
static let cancellationAction: ToolbarItemPlacement
The item represents a cancellation action for a modal interface.
static let destructiveAction: ToolbarItemPlacement
The item represents a destructive action for a modal interface.
static let navigation: ToolbarItemPlacement
The item represents a navigation action.
Getting explicit placement
static var topBarLeading: ToolbarItemPlacement
Places the item in the leading edge of the top bar.
static var topBarTrailing: ToolbarItemPlacement
Places the item in the trailing edge of the top bar.
static let bottomBar: ToolbarItemPlacement
Places the item in the bottom toolbar.
static let bottomOrnament: ToolbarItemPlacement
Places the item in an ornament under the window.
static let keyboard: ToolbarItemPlacement
The item is placed in the keyboard section.
Creates a unique accessory bar placement.
Deprecated symbols
Creates a custom accessory bar item placement.
Deprecated
static let navigationBarLeading: ToolbarItemPlacement
Places the item in the leading edge of the navigation bar.
static let navigationBarTrailing: ToolbarItemPlacement
Places the item in the trailing edge of the navigation bar.
Type Properties
static let largeSubtitle: ToolbarItemPlacement
Places the item in the subtitle area of the navigation bar.
Beta
static let largeTitle: ToolbarItemPlacement
Places the item in the title area of the navigation bar.
static let subtitle: ToolbarItemPlacement
static var title: ToolbarItemPlacement
See Also
Populating a toolbar
func toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
struct ToolbarItem
A model that represents an item which can be placed in the toolbar or navigation bar.
struct ToolbarItemGroup
A model that represents a group of ToolbarItem s which can be placed in the toolbar or navigation bar.
protocol ToolbarContent
Conforming types represent items that can be placed in various locations in a toolbar.
struct ToolbarContentBuilder
Constructs a toolbar item set from multi-expression closures.
struct ToolbarSpacer
A standard space item in toolbars.
struct DefaultToolbarItem
A toolbar item that represents a system component.
https://developer.apple.com/documentation/swiftui/toolbarcontent
- SwiftUI
- ToolbarContent
Protocol
ToolbarContent
Conforming types represent items that can be placed in various locations in a toolbar.
@MainActor @preconcurrency protocol ToolbarContent
Overview
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is included in the type’s base declaration:
struct MyCustomType: Transition {
// @preconcurrency @MainActor isolation by default
}
Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt out of main actor isolation:
extension MyCustomType: Transition {
// nonisolated by default
}
Topics
Implementing toolbar content
var body: Self.Body
The composition of content that comprise the toolbar content.
Required
associatedtype Body : ToolbarContent
The type of content representing the body of this toolbar content.
Instance Methods
Hides a toolbar item within its toolbar.
Identifies this toolbar content as the source of a navigation transition, such as a zoom transition.
Beta
Controls the visibility of the glass background effect on items in the toolbar. In certain contexts, such as the navigation bar on iOS and the window toolbar on macOS, toolbar items will be given a glass background effect that is shared with other items in the same logical grouping.
Relationships
Inherited By
CustomizableToolbarContent
Conforming Types
-
DefaultToolbarItem -
GroupConforms whenContentconforms toToolbarContent. -
ToolbarItem -
ToolbarItemGroup -
ToolbarSpacer -
ToolbarTitleMenu
See Also
Populating a toolbar
func toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
struct ToolbarItem
A model that represents an item which can be placed in the toolbar or navigation bar.
struct ToolbarItemGroup
A model that represents a group of ToolbarItem s which can be placed in the toolbar or navigation bar.
struct ToolbarItemPlacement
A structure that defines the placement of a toolbar item.
struct ToolbarContentBuilder
Constructs a toolbar item set from multi-expression closures.
struct ToolbarSpacer
A standard space item in toolbars.
struct DefaultToolbarItem
A toolbar item that represents a system component.
https://developer.apple.com/documentation/swiftui/toolbarcontentbuilder
- SwiftUI
- ToolbarContentBuilder
Structure
ToolbarContentBuilder
Constructs a toolbar item set from multi-expression closures.
@resultBuilder struct ToolbarContentBuilder
Topics
Building toolbar content
static buildBlock(_:)
static buildBlock(_:_:)
static buildBlock(_:_:_:)
static buildBlock(_:_:_:_:)
static buildBlock(_:_:_:_:_:)
static buildBlock(_:_:_:_:_:_:)
static buildBlock(_:_:_:_:_:_:_:)
static buildBlock(_:_:_:_:_:_:_:_:)
static buildBlock(_:_:_:_:_:_:_:_:_:)
static buildBlock(_:_:_:_:_:_:_:_:_:_:)
Building conditional toolbar content
static buildIf(_:)
static buildEither(first:)
static buildEither(second:)
static buildExpression(_:)
Builds an expression within the builder.
static buildLimitedAvailability(_:)
See Also
Populating a toolbar
func toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
struct ToolbarItem
A model that represents an item which can be placed in the toolbar or navigation bar.
struct ToolbarItemGroup
A model that represents a group of ToolbarItem s which can be placed in the toolbar or navigation bar.
struct ToolbarItemPlacement
A structure that defines the placement of a toolbar item.
protocol ToolbarContent
Conforming types represent items that can be placed in various locations in a toolbar.
struct ToolbarSpacer
A standard space item in toolbars.
Beta
struct DefaultToolbarItem
A toolbar item that represents a system component.
https://developer.apple.com/documentation/swiftui/toolbarspacer
- SwiftUI
- ToolbarSpacer Beta
Structure
ToolbarSpacer
A standard space item in toolbars.
struct ToolbarSpacer
Overview
A space item creates visual breaks in the toolbar between items. Spacers can have a standard fixed size or be flexible and push items apart.
Spacers can also be used in customizable toolbars:
ContentView() .toolbar(id: "main-toolbar") { ToolbarItem(id: "tag") { TagButton() } ToolbarItem(id: "share") { ShareButton() } ToolbarSpacer(.fixed) ToolbarItem(id: "more") { MoreButton() } }
Space items are customizable and can be added, removed, and rearranged by users. If a customizable toolbar supports a spacer of a given type, users can also add in multiple copies of that spacer from the customization panel.
Topics
Initializers
init(SpacerSizing, placement: ToolbarItemPlacement)
Creates a toolbar spacer item with the specified sizing behavior and placement.
Relationships
Conforms To
CustomizableToolbarContentToolbarContent
See Also
Populating a toolbar
func toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
struct ToolbarItem
A model that represents an item which can be placed in the toolbar or navigation bar.
struct ToolbarItemGroup
A model that represents a group of ToolbarItem s which can be placed in the toolbar or navigation bar.
struct ToolbarItemPlacement
A structure that defines the placement of a toolbar item.
protocol ToolbarContent
Conforming types represent items that can be placed in various locations in a toolbar.
struct ToolbarContentBuilder
Constructs a toolbar item set from multi-expression closures.
struct DefaultToolbarItem
A toolbar item that represents a system component.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/defaulttoolbaritem
- SwiftUI
- DefaultToolbarItem Beta
Structure
DefaultToolbarItem
A toolbar item that represents a system component.
struct DefaultToolbarItem
Overview
Place this item in your toolbar to control where the system-provided item, like search, will be positioned.
Topics
Initializers
init(kind: ToolbarDefaultItemKind, placement: ToolbarItemPlacement)
Creates a system-defined toolbar item from a ToolbarDefaultItemKind at the given placement.
Relationships
Conforms To
ToolbarContent
See Also
Populating a toolbar
func toolbar(content:)
Populates the toolbar or navigation bar with the specified items.
struct ToolbarItem
A model that represents an item which can be placed in the toolbar or navigation bar.
struct ToolbarItemGroup
A model that represents a group of ToolbarItem s which can be placed in the toolbar or navigation bar.
struct ToolbarItemPlacement
A structure that defines the placement of a toolbar item.
protocol ToolbarContent
Conforming types represent items that can be placed in various locations in a toolbar.
struct ToolbarContentBuilder
Constructs a toolbar item set from multi-expression closures.
struct ToolbarSpacer
A standard space item in toolbars.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/toolbar(id:content:)
https://developer.apple.com/documentation/swiftui/customizabletoolbarcontent
- SwiftUI
- CustomizableToolbarContent
Protocol
CustomizableToolbarContent
Conforming types represent items that can be placed in various locations in a customizable toolbar.
protocol CustomizableToolbarContent : ToolbarContent where Self.Body : CustomizableToolbarContent
Topics
Using default options
Configures customizable toolbar content with the default visibility and options.
Deprecated
Configures the way customizable toolbar items with the default behavior behave.
Customizing the behavior
Configures the customization behavior of customizable toolbar content.
Instance Methods
Hides a toolbar item within its toolbar.
Identifies this toolbar content as the source of a navigation transition, such as a zoom transition.
Beta
Controls the visibility of the glass background effect on items in the toolbar. In certain contexts, such as the navigation bar on iOS and the window toolbar on macOS, toolbar items will be given a glass background effect that is shared with other items in the same logical grouping.
Relationships
Inherits From
ToolbarContent
Conforming Types
-
GroupConforms whenContentconforms toCustomizableToolbarContent. -
ToolbarItemConforms whenIDisStringandContentconforms toView. -
ToolbarSpacer -
ToolbarTitleMenu
See Also
Populating a customizable toolbar
Populates the toolbar or navigation bar with the specified items, allowing for user customization.
struct ToolbarCustomizationBehavior
The customization behavior of customizable toolbar content.
struct ToolbarCustomizationOptions
Options that influence the default customization behavior of customizable toolbar content.
struct SearchToolbarBehavior
The behavior of a search field in a toolbar.
https://developer.apple.com/documentation/swiftui/toolbarcustomizationbehavior
- SwiftUI
- ToolbarCustomizationBehavior
Structure
ToolbarCustomizationBehavior
The customization behavior of customizable toolbar content.
struct ToolbarCustomizationBehavior
Overview
Customizable toolbar content support different types of customization behaviors. For example, some customizable content may not be removed by the user. Some content may be placed in a toolbar that supports customization overall, but not for that particular content.
Use this type in conjunction with the customizationBehavior(_:) modifier.
Topics
Getting customization behaviors
static var `default`: ToolbarCustomizationBehavior
The default customization behavior.
static var disabled: ToolbarCustomizationBehavior
The disabled customization behavior.
static var reorderable: ToolbarCustomizationBehavior
The reorderable customization behavior.
Relationships
Conforms To
SendableSendableMetatype
See Also
Populating a customizable toolbar
Populates the toolbar or navigation bar with the specified items, allowing for user customization.
protocol CustomizableToolbarContent
Conforming types represent items that can be placed in various locations in a customizable toolbar.
struct ToolbarCustomizationOptions
Options that influence the default customization behavior of customizable toolbar content.
struct SearchToolbarBehavior
The behavior of a search field in a toolbar.
Beta
https://developer.apple.com/documentation/swiftui/toolbarcustomizationoptions
https://developer.apple.com/documentation/swiftui/searchtoolbarbehavior
- SwiftUI
- SearchToolbarBehavior Beta
Structure
SearchToolbarBehavior
The behavior of a search field in a toolbar.
struct SearchToolbarBehavior
Overview
Use this type in combination with the searchToolbarBehavior(_:) modifier.
Topics
Type Properties
static var automatic: SearchToolbarBehavior
The automatic behavior.
static var minimize: SearchToolbarBehavior
A search toolbar behavior that prefers rendering a search field as a button-like control.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Populating a customizable toolbar
Populates the toolbar or navigation bar with the specified items, allowing for user customization.
protocol CustomizableToolbarContent
Conforming types represent items that can be placed in various locations in a customizable toolbar.
struct ToolbarCustomizationBehavior
The customization behavior of customizable toolbar content.
struct ToolbarCustomizationOptions
Options that influence the default customization behavior of customizable toolbar content.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/toolbar(removing:)
https://developer.apple.com/documentation/swiftui/toolbardefaultitemkind
https://developer.apple.com/documentation/swiftui/view/toolbarvisibility(_:for:)
#app-main)
- SwiftUI
- View
- toolbarVisibility(_:for:)
Instance Method
toolbarVisibility(_:for:)
Specifies the visibility of a bar managed by SwiftUI.
nonisolated func toolbarVisibility( _ visibility: Visibility, for bars: ToolbarPlacement...
Parameters
visibility
The preferred visibility of the bar.
bars
The bars to update the visibility of or automatic if empty.
Discussion
The preferred visibility flows up to the nearest container that renders a bar. This could be a NavigationView or TabView in iOS, or the root view of a WindowGroup in macOS.
This examples shows a view that hides the navigation bar on iOS, or the window toolbar items on macOS.
NavigationView { ContentView() .toolbarVisibility(.hidden) }
To hide the entire titlebar on macOS, use this modifier with windowToolbar placement.
NavigationView { ContentView() .toolbarVisibility(.hidden, for: .windowToolbar) }
You can provide multiple ToolbarPlacement instances to hide multiple bars at once.
TabView { NavigationView { ContentView() .toolbarVisibility( .hidden, for: .navigationBar, .tabBar) } }
Depending on the specified bars, the requested visibility may not be able to be fulfilled.
See Also
Setting toolbar visibility
Specifies the preferred visibility of backgrounds on a bar managed by SwiftUI.
struct ToolbarPlacement
The placement of a toolbar.
struct ContentToolbarPlacement
https://developer.apple.com/documentation/swiftui/view/toolbarbackgroundvisibility(_:for:)
#app-main)
- SwiftUI
- View
- toolbarBackgroundVisibility(_:for:)
Instance Method
toolbarBackgroundVisibility(_:for:)
Specifies the preferred visibility of backgrounds on a bar managed by SwiftUI.
nonisolated func toolbarBackgroundVisibility( _ visibility: Visibility, for bars: ToolbarPlacement...
Parameters
visibility
The preferred visibility of the background of the bar.
bars
The bars to update the color scheme of or automatic if empty.
Discussion
The preferred visibility flows up to the nearest container that renders a bar. This could be a NavigationView or TabView in iOS, or the root view of a WindowGroup in macOS.
In iOS, a value of automatic makes the visibility of a tab bar or navigation bar background depend on where a List or ScrollView settles. For example, when aligned to the bottom edge of of a scroll view’s content, the background of a tab bar becomes transparent.
Specify a value of Visibility.visible to ensure that the background of a bar remains visible regardless of where any scroll view or list stops scrolling.
This example shows a view that prefers to always have the tab bar visible when the middle tab is selected:
TabView { FirstTab() MiddleTab() .toolbarBackgroundVisibility(.visible, for: .tabBar) LastTab() }
You can provide multiple placements to customize multiple bars at once, as in the following example:
TabView { NavigationView { ContentView() .toolbarBackgroundVisibility( .visible, for: .navigationBar, .tabBar) } }
See Also
Setting toolbar visibility
Specifies the visibility of a bar managed by SwiftUI.
struct ToolbarPlacement
The placement of a toolbar.
struct ContentToolbarPlacement
https://developer.apple.com/documentation/swiftui/toolbarplacement
- SwiftUI
- ToolbarPlacement
Structure
ToolbarPlacement
The placement of a toolbar.
struct ToolbarPlacement
Overview
Use this type in conjunction with modifiers like toolbarBackground(_:for:) and toolbar(_:for:) to customize the appearance of different bars managed by SwiftUI. Not all bars support all types of customizations.
See ToolbarItemPlacement to learn about the different regions of these toolbars that you can place your own controls into.
Topics
Getting placements
static var automatic: ToolbarPlacement
The primary toolbar.
Creates a unique accessory bar placement.
static var bottomBar: ToolbarPlacement
The bottom toolbar of an app.
static var bottomOrnament: ToolbarPlacement
The bottom ornament of an app.
static var navigationBar: ToolbarPlacement
The navigation bar of an app.
static var tabBar: ToolbarPlacement
The tab bar of an app.
static var windowToolbar: ToolbarPlacement
The placement for the containing window’s toolbar, sometimes referred to as the titlebar.
Deprecated symbols
Creates a custom accessory bar placement.
Deprecated
See Also
Setting toolbar visibility
Specifies the visibility of a bar managed by SwiftUI.
Specifies the preferred visibility of backgrounds on a bar managed by SwiftUI.
struct ContentToolbarPlacement
https://developer.apple.com/documentation/swiftui/contenttoolbarplacement
- SwiftUI
- ContentToolbarPlacement
Structure
ContentToolbarPlacement
struct ContentToolbarPlacement
Topics
Type Properties
static let tabViewSidebar: ContentToolbarPlacement
The tab view sidebar. This is present on certain platforms when using the .sidebarAdaptable tab view style.
Relationships
Conforms To
EquatableHashableSendableSendableMetatype
See Also
Setting toolbar visibility
Specifies the visibility of a bar managed by SwiftUI.
Specifies the preferred visibility of backgrounds on a bar managed by SwiftUI.
struct ToolbarPlacement
The placement of a toolbar.
https://developer.apple.com/documentation/swiftui/view/toolbarrole(_:)
#app-main)
- SwiftUI
- View
- toolbarRole(_:)
Instance Method
toolbarRole(_:)
Configures the semantic role for the content populating the toolbar.
nonisolated
Parameters
role
The role of the toolbar.
Discussion
Use this modifier to configure the semantic role for content populating your app’s toolbar. SwiftUI uses this role when rendering the content of your app’s toolbar.
ContentView() .navigationTitle("Browser") .toolbarRole(.browser) .toolbar { ToolbarItem(placement: .primaryAction) { AddButton() } }
See Also
Specifying the role of toolbar content
struct ToolbarRole
The purpose of content that populates the toolbar.
https://developer.apple.com/documentation/swiftui/toolbarrole
- SwiftUI
- ToolbarRole
Structure
ToolbarRole
The purpose of content that populates the toolbar.
struct ToolbarRole
Overview
A toolbar role provides a description of the purpose of content that populates the toolbar. The purpose of the content influences how a toolbar renders its content. For example, a browser will automatically leading align the title of a toolbar in iPadOS.
Provide this type to the toolbarRole(_:) modifier:
ContentView() .navigationTitle("Browser") .toolbarRole(.browser) .toolbar { ToolbarItem(placement: .primaryAction) { AddButton() } }
Topics
Behavior-specific roles
static var browser: ToolbarRole
The browser role.
static var editor: ToolbarRole
The editor role.
static var navigationStack: ToolbarRole
The navigationStack role.
Automatic roles
static var automatic: ToolbarRole
The automatic role.
Relationships
Conforms To
SendableSendableMetatype
See Also
Specifying the role of toolbar content
Configures the semantic role for the content populating the toolbar.
https://developer.apple.com/documentation/swiftui/view/toolbarbackground(_:for:)
#app-main)
- SwiftUI
- View
- toolbarBackground(_:for:)
Instance Method
toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
nonisolated
_ style: S, for bars: ToolbarPlacement...
Show all declarations
Parameters
style
The style to display as the background of the bar.
bars
The bars to use the style for or automatic if empty.
Discussion
The preferred style flows up to the nearest container that renders a bar. This could be a NavigationView or TabView in iOS, or the root view of a WindowGroup in macOS. This example shows a view that renders the navigation bar with a blue background and dark color scheme.
NavigationView { ContentView() .toolbarBackground(.white) .toolbarColorScheme(.dark) }
You can provide multiple ToolbarPlacement instances to customize multiple bars at once.
TabView { NavigationView { ContentView() .toolbarBackground( .blue, for: .navigationBar, .tabBar) .toolbarColorScheme( .dark, for: .navigationBar, .tabBar) } }
When used within a TabView, the specified style will be preferred while the tab is currently active. You can use a Group to specify the same preferred background for every tab.
TabView { Group { MainView() SettingsView() } .toolbarBackground(.blue, for: .tabBar) }
Depending on the specified bars, the requested style may not be able to be fullfilled.
See Also
Styling a toolbar
Specifies the preferred color scheme of a bar managed by SwiftUI.
Specifies the preferred foreground style of bars managed by SwiftUI.
Sets the style for the toolbar defined within this scene.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
var toolbarLabelStyle: ToolbarLabelStyle?
The label style to apply to controls within a toolbar.
struct ToolbarLabelStyle
The label style of a toolbar.
struct SpacerSizing
A type which defines how spacers should size themselves.
Beta
https://developer.apple.com/documentation/swiftui/view/toolbarcolorscheme(_:for:)
#app-main)
- SwiftUI
- View
- toolbarColorScheme(_:for:)
Instance Method
toolbarColorScheme(_:for:)
Specifies the preferred color scheme of a bar managed by SwiftUI.
nonisolated func toolbarColorScheme( _ colorScheme: ColorScheme?, for bars: ToolbarPlacement...
Parameters
colorScheme
The preferred color scheme of the background of the bar.
bars
The bars to update the color scheme of or automatic if empty.
Discussion
The preferred color scheme flows up to the nearest container that renders a bar. This could be a NavigationView or TabView in iOS, or the root view of a WindowGroup in macOS. Pass in a value of nil to match the current system’s color scheme.
This examples shows a view that renders the navigation bar with a blue background and dark color scheme:
TabView { NavigationView { ContentView() .toolbarBackground(.blue) .toolbarColorScheme(.dark) } // other tabs... }
You can provide multiple ToolbarPlacement instances to customize multiple bars at once.
TabView { NavigationView { ContentView() .toolbarBackground( .blue, for: .navigationBar, .tabBar) .toolbarColorScheme( .dark, for: .navigationBar, .tabBar) } }
Note that the provided color scheme is only respected while a background is visible in the requested bar. As the background becomes visible, the bar transitions from the color scheme of the app to the requested color scheme. You can ensure that the color scheme is always respected by specifying that the background of the bar always be visible.
NavigationView { ContentView() .toolbarBackground(.visible) .toolbarColorScheme(.dark) }
Depending on the specified bars, the requested color scheme may not be able to be fullfilled.
See Also
Styling a toolbar
func toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
Specifies the preferred foreground style of bars managed by SwiftUI.
Sets the style for the toolbar defined within this scene.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
var toolbarLabelStyle: ToolbarLabelStyle?
The label style to apply to controls within a toolbar.
struct ToolbarLabelStyle
The label style of a toolbar.
struct SpacerSizing
A type which defines how spacers should size themselves.
Beta
https://developer.apple.com/documentation/swiftui/view/toolbarforegroundstyle(_:for:)
#app-main)
- SwiftUI
- View
- toolbarForegroundStyle(_:for:)
Instance Method
toolbarForegroundStyle(_:for:)
Specifies the preferred foreground style of bars managed by SwiftUI.
nonisolated
_ style: S, for bars: ToolbarPlacement...
Discussion
This examples shows a view that renders the navigation bar with a blue foreground color.
NavigationStack { ContentView() .navigationTitle("Blue") .toolbarForegroundStyle( .blue, for: .navigationBar) }
See Also
Styling a toolbar
func toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
Specifies the preferred color scheme of a bar managed by SwiftUI.
Sets the style for the toolbar defined within this scene.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
var toolbarLabelStyle: ToolbarLabelStyle?
The label style to apply to controls within a toolbar.
struct ToolbarLabelStyle
The label style of a toolbar.
struct SpacerSizing
A type which defines how spacers should size themselves.
Beta
https://developer.apple.com/documentation/swiftui/environmentvalues/toolbarlabelstyle
- SwiftUI
- EnvironmentValues
- toolbarLabelStyle
Instance Property
toolbarLabelStyle
The label style to apply to controls within a toolbar.
var toolbarLabelStyle: ToolbarLabelStyle? { get }
Discussion
The default is nil for items outside the window toolbar.
See Also
Styling a toolbar
func toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
Specifies the preferred color scheme of a bar managed by SwiftUI.
Specifies the preferred foreground style of bars managed by SwiftUI.
Sets the style for the toolbar defined within this scene.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
struct ToolbarLabelStyle
The label style of a toolbar.
struct SpacerSizing
A type which defines how spacers should size themselves.
Beta
https://developer.apple.com/documentation/swiftui/toolbarlabelstyle
- SwiftUI
- ToolbarLabelStyle
Structure
ToolbarLabelStyle
The label style of a toolbar.
struct ToolbarLabelStyle
Overview
Use this type in conjunction with modifiers like windowToolbarLabelStyle(fixed:) and windowToolbarLabelStyle(_:) to customize the appearance of window toolbars managed by SwiftUI.
Topics
Type Properties
static var automatic: ToolbarLabelStyle
The automatic label style. The toolbar will use a labelStyle that best fits the Scene it is applied to.
static var iconOnly: ToolbarLabelStyle
The icon only label style. The toolbar contents will only display the control
static var titleAndIcon: ToolbarLabelStyle
The title and icon label style. The toolbar contents will display both a control and title
static var titleOnly: ToolbarLabelStyle
The title only label style. The toolbar contents will only display the title
Relationships
Conforms To
EquatableSendableSendableMetatype
See Also
Styling a toolbar
func toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
Specifies the preferred color scheme of a bar managed by SwiftUI.
Specifies the preferred foreground style of bars managed by SwiftUI.
Sets the style for the toolbar defined within this scene.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
var toolbarLabelStyle: ToolbarLabelStyle?
The label style to apply to controls within a toolbar.
struct SpacerSizing
A type which defines how spacers should size themselves.
Beta
https://developer.apple.com/documentation/swiftui/spacersizing
- SwiftUI
- SpacerSizing Beta
Structure
SpacerSizing
A type which defines how spacers should size themselves.
struct SpacerSizing
Overview
Use this type in coordination with the ToolbarSpacer type to define if the spacer should be a flexible size, or a fixed size using system-defined sizing rules.
For example, the following adds a fixed-size toolbar spacer between the share and more buttons in the toolbar:
ContentView() .toolbar(id: "main-toolbar") { ToolbarItem(id: "tag") { TagButton() } ToolbarItem(id: "share") { ShareButton() } ToolbarSpacer(.fixed) ToolbarItem(id: "more") { MoreButton() } }
Topics
Type Properties
static let fixed: SpacerSizing
The fixed spacer sizing behavior. The spacer will use a pre-defined size determined by the system and the context in which the spacer is used.
static let flexible: SpacerSizing
The flexible spacer sizing behavior. The spacer will expand to accommodate as much space as it is given in the current context.
Relationships
Conforms To
SendableSendableMetatype
See Also
Styling a toolbar
func toolbarBackground(_:for:)
Specifies the preferred shape style of the background of a bar managed by SwiftUI.
Specifies the preferred color scheme of a bar managed by SwiftUI.
Specifies the preferred foreground style of bars managed by SwiftUI.
Sets the style for the toolbar defined within this scene.
protocol WindowToolbarStyle
A specification for the appearance and behavior of a window’s toolbar.
var toolbarLabelStyle: ToolbarLabelStyle?
The label style to apply to controls within a toolbar.
struct ToolbarLabelStyle
The label style of a toolbar.
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/toolbartitledisplaymode(_:)
#app-main)
- SwiftUI
- View
- toolbarTitleDisplayMode(_:)
Instance Method
toolbarTitleDisplayMode(_:)
Configures the toolbar title display mode for this view.
nonisolated
Discussion
Use this modifier to override the default toolbar title display mode.
NavigationStack { ContentView() .toolbarTitleDisplayMode(.inlineLarge) }
See ToolbarTitleDisplayMode for more information on the different kinds of display modes. This modifier has no effect on macOS.
See Also
Configuring the toolbar title display mode
struct ToolbarTitleDisplayMode
A type that defines the behavior of title of a toolbar.
https://developer.apple.com/documentation/swiftui/toolbartitledisplaymode
https://developer.apple.com/documentation/swiftui/view/toolbartitlemenu(content:)
#app-main)
- SwiftUI
- View
- toolbarTitleMenu(content:)
Instance Method
toolbarTitleMenu(content:)
Configure the title menu of a toolbar.
nonisolated
Parameters
content
The content associated to the toolbar title menu.
Discussion
A title menu represent common functionality that can be done on the content represented by your app’s toolbar or navigation title. This menu may be populated from your app’s commands like saveItem or printItem.
ContentView() .toolbar { ToolbarTitleMenu() }
You can provide your own set of actions to override this behavior.
ContentView() .toolbarTitleMenu { DuplicateButton() PrintButton() }
In iOS and iPadOS, this will construct a menu that can be presented by tapping the navigation title in the app’s navigation bar.
See Also
Setting the toolbar title menu
struct ToolbarTitleMenu
The title menu of a toolbar.
https://developer.apple.com/documentation/swiftui/toolbartitlemenu
- SwiftUI
- ToolbarTitleMenu
Structure
ToolbarTitleMenu
The title menu of a toolbar.
Overview
A title menu represents common functionality that can be done on the content represented by your app’s toolbar or navigation title. This menu may be populated from your app’s commands like saveItem or printItem.
ContentView() .toolbar { ToolbarTitleMenu() }
You can provide your own set of actions to override this behavior.
ContentView() .toolbar { ToolbarTitleMenu { DuplicateButton() PrintButton() } }
In iOS and iPadOS, this will construct a menu that can be presented by tapping the navigation title in the app’s navigation bar.
Topics
Creating a toolbar title menu
init()
Creates a toolbar title menu where actions are inferred from your apps commands.
Creates a toolbar title menu.
Relationships
Conforms To
CustomizableToolbarContentToolbarContent
See Also
Setting the toolbar title menu
Configure the title menu of a toolbar.
https://developer.apple.com/documentation/swiftui/view/ornament(visibility:attachmentanchor:contentalignment:ornament:)
#app-main)
- SwiftUI
- View
- ornament(visibility:attachmentAnchor:contentAlignment:ornament:)
Instance Method
ornament(visibility:attachmentAnchor:contentAlignment:ornament:)
Presents an ornament.
nonisolated
visibility: Visibility = .automatic, attachmentAnchor: OrnamentAttachmentAnchor, contentAlignment: Alignment = .center,
Show all declarations
Parameters
visibility
The visibility of the ornament.
attachmentAnchor
The positioning anchor that defines the attachment point of the ornament.
contentAlignment
The alignment of the ornament with its attachment anchor.
Discussion
Use this method to show an ornament at the specified position. The example below displays an ornament below the window:
Text("A view with an ornament") .ornament(attachmentAnchor: .scene(.bottom)) { OrnamentContent() }
See Also
Creating an ornament
struct OrnamentAttachmentAnchor
An attachment anchor for an ornament.
https://developer.apple.com/documentation/swiftui/ornamentattachmentanchor
- SwiftUI
- OrnamentAttachmentAnchor
Structure
OrnamentAttachmentAnchor
An attachment anchor for an ornament.
struct OrnamentAttachmentAnchor
Topics
Getting an anchor
static scene(_:)
The anchor point for the ornament expressed as a unit point relative to the scene.
Type Methods
The anchor point for the ornament expressed as a 3D unit point relative to its parent.
Beta
Relationships
Conforms To
SendableSendableMetatype
See Also
Creating an ornament
func ornament(visibility:attachmentAnchor:contentAlignment:ornament:)
Presents an ornament.
https://developer.apple.com/documentation/swiftui/view/toolbar(content:))
https://developer.apple.com/documentation/swiftui/view/toolbar(_:for:))
https://developer.apple.com/documentation/swiftui/toolbaritem)
https://developer.apple.com/documentation/swiftui/toolbaritemgroup)
https://developer.apple.com/documentation/swiftui/toolbaritemplacement)
https://developer.apple.com/documentation/swiftui/toolbarcontent)
https://developer.apple.com/documentation/swiftui/toolbarcontentbuilder)
https://developer.apple.com/documentation/swiftui/toolbarspacer)
https://developer.apple.com/documentation/swiftui/defaulttoolbaritem)
https://developer.apple.com/documentation/swiftui/view/toolbar(id:content:))
https://developer.apple.com/documentation/swiftui/customizabletoolbarcontent)
https://developer.apple.com/documentation/swiftui/toolbarcustomizationbehavior)
https://developer.apple.com/documentation/swiftui/toolbarcustomizationoptions)
https://developer.apple.com/documentation/swiftui/searchtoolbarbehavior)
https://developer.apple.com/documentation/swiftui/view/toolbar(removing:))
https://developer.apple.com/documentation/swiftui/toolbardefaultitemkind)
https://developer.apple.com/documentation/swiftui/view/toolbarvisibility(_:for:))
https://developer.apple.com/documentation/swiftui/view/toolbarbackgroundvisibility(_:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/toolbarplacement)
https://developer.apple.com/documentation/swiftui/contenttoolbarplacement)
https://developer.apple.com/documentation/swiftui/view/toolbarrole(_:))
https://developer.apple.com/documentation/swiftui/toolbarrole)
https://developer.apple.com/documentation/swiftui/view/toolbarbackground(_:for:))
https://developer.apple.com/documentation/swiftui/view/toolbarcolorscheme(_:for:))
https://developer.apple.com/documentation/swiftui/view/toolbarforegroundstyle(_:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/environmentvalues/toolbarlabelstyle)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/toolbarlabelstyle)
https://developer.apple.com/documentation/swiftui/spacersizing)
https://developer.apple.com/documentation/swiftui/view/toolbartitledisplaymode(_:))
https://developer.apple.com/documentation/swiftui/toolbartitledisplaymode)
https://developer.apple.com/documentation/swiftui/view/toolbartitlemenu(content:))
https://developer.apple.com/documentation/swiftui/toolbartitlemenu)
https://developer.apple.com/documentation/swiftui/view/ornament(visibility:attachmentanchor:contentalignment:ornament:))
https://developer.apple.com/documentation/swiftui/ornamentattachmentanchor)
https://developer.apple.com/documentation/swiftui/viewmodifier
- SwiftUI
- ViewModifier
Protocol
ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
@MainActor @preconcurrency protocol ViewModifier
Mentioned in
Reducing view modifier maintenance
Overview
Adopt the ViewModifier protocol when you want to create a reusable modifier that you can apply to any view. The example below combines several modifiers to create a new modifier that you can use to create blue caption text surrounded by a rounded rectangle:
struct BorderedCaption: ViewModifier {
content .font(.caption2) .padding(10) .overlay( RoundedRectangle(cornerRadius: 15) .stroke(lineWidth: 1) ) .foregroundColor(Color.blue) } }
You can apply modifier(_:) directly to a view, but a more common and idiomatic approach uses modifier(_:) to define an extension to View itself that incorporates the view modifier:
extension View {
modifier(BorderedCaption()) } }
You can then apply the bordered caption to any view, similar to this:
Image(systemName: "bus") .resizable() .frame(width:50, height:50) Text("Downtown Bus") .borderedCaption()
A type conforming to this protocol inherits @preconcurrency @MainActor isolation from the protocol if the conformance is included in the type’s base declaration:
struct MyCustomType: Transition {
// @preconcurrency @MainActor isolation by default
}
Isolation to the main actor is the default, but it’s not required. Declare the conformance in an extension to opt out of main actor isolation:
extension MyCustomType: Transition {
// nonisolated by default
}
Topics
Creating a view modifier
Gets the current body of the caller.
Required Default implementation provided.
associatedtype Body : View
The type of view representing the body.
Required
typealias Content
The content view type passed to body().
Adding animations to a view
Returns a new version of the modifier that will apply animation to all animatable values within the modifier.
Returns a new modifier that is the result of concatenating self with modifier.
Handling view taps and gestures
Returns a new version of the modifier that will apply the transaction mutation function transform to all transactions within the modifier.
Relationships
Inherited By
AnimatableModifierEnvironmentalModifierGeometryEffect
Conforming Types
AccessibilityAttachmentModifierEmptyModifierLayoutRotationUnaryLayoutManipulableModifierManipulableResponderModifierManipulableTransformBindingModifierManipulationGeometryModifierManipulationGestureModifierManipulationUsingGestureStateModifierModifiedContentConforms whenContentconforms toViewModifierandModifierconforms toViewModifier.
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
https://developer.apple.com/documentation/swiftui/emptymodifier
- SwiftUI
- EmptyModifier
Structure
EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
@frozen struct EmptyModifier
Overview
Use the empty modifier to switch modifiers at compile time during development. In the example below, in a debug build the Text view inside ContentView has a yellow background and a red border. A non-debug build reflects the default system, or container supplied appearance.
struct EmphasizedLayout: ViewModifier {
content .background(Color.yellow) .border(Color.red) } }
struct ContentView: View { var body: some View { Text("Hello, World!") .modifier(modifier) }
var modifier: some ViewModifier { #if DEBUG return EmphasizedLayout() #else return EmptyModifier() #endif } }
Topics
Creating an empty modifier
init()
Getting the identity modifier
static let identity: EmptyModifier
Relationships
Conforms To
BitwiseCopyableCopyableSendableSendableMetatypeViewModifier
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
https://developer.apple.com/documentation/swiftui/environmentalmodifier
- SwiftUI
- EnvironmentalModifier
Protocol
EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
protocol EnvironmentalModifier : ViewModifier where Self.Body == Never
Topics
Resolving a modifier
Resolve to a concrete modifier in the given environment.
Required
associatedtype ResolvedModifier : ViewModifier
The type of modifier to use after being resolved.
Relationships
Inherits From
ViewModifier
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
https://developer.apple.com/documentation/swiftui/manipulablemodifier
- SwiftUI
- ManipulableModifier Beta
Structure
ManipulableModifier
nonisolated struct ManipulableModifier
Relationships
Conforms To
ViewModifier
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/manipulablerespondermodifier
- SwiftUI
- ManipulableResponderModifier Beta
Structure
ManipulableResponderModifier
nonisolated struct ManipulableResponderModifier
Relationships
Conforms To
CopyableViewModifier
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/manipulabletransformbindingmodifier
- SwiftUI
- ManipulableTransformBindingModifier Beta
Structure
ManipulableTransformBindingModifier
nonisolated struct ManipulableTransformBindingModifier
Relationships
Conforms To
ViewModifier
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/manipulationgeometrymodifier
- SwiftUI
- ManipulationGeometryModifier Beta
Structure
ManipulationGeometryModifier
@MainActor @preconcurrency struct ManipulationGeometryModifier
Relationships
Conforms To
CopyableViewModifier
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/manipulationgesturemodifier
- SwiftUI
- ManipulationGestureModifier Beta
Structure
ManipulationGestureModifier
nonisolated struct ManipulationGestureModifier
Relationships
Conforms To
ViewModifier
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationUsingGestureStateModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/manipulationusinggesturestatemodifier
- SwiftUI
- ManipulationUsingGestureStateModifier Beta
Structure
ManipulationUsingGestureStateModifier
nonisolated struct ManipulationUsingGestureStateModifier
Relationships
Conforms To
ViewModifier
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
enum Manipulable
A namespace for various manipulable related types.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/manipulable
- SwiftUI
- Manipulable Beta
Enumeration
Manipulable
A namespace for various manipulable related types.
enum Manipulable
Topics
Structures
struct Event
Describes an event generated during a manipulation gesture.
struct GestureState
Describes the state of a manipulation gesture.
struct Inertia
Describes inertia of a view that defines how much a view resists being manipulated.
struct InputDevice
Describes an input device like a hand or a trackpad.
struct Operation
Describes an operation applied to a view when a person is manipulating a view.
Relationships
Conforms To
SendableSendableMetatype
See Also
Modifying a view
Configuring views
Adjust the characteristics of a view by applying view modifiers.
Reducing view modifier maintenance
Bundle view modifiers that you regularly reuse into a custom view modifier.
Applies a modifier to a view and returns a new view.
protocol ViewModifier
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
struct EmptyModifier
An empty, or identity, modifier, used during development to switch modifiers at compile time.
struct ModifiedContent
A value with a modifier applied to it.
protocol EnvironmentalModifier
A modifier that must resolve to a concrete modifier in an environment before use.
struct ManipulableModifier Beta
struct ManipulableResponderModifier Beta
struct ManipulableTransformBindingModifier Beta
struct ManipulationGeometryModifier Beta
struct ManipulationGestureModifier Beta
struct ManipulationUsingGestureStateModifier Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/swiftui/view/onappear(perform:)
#app-main)
- SwiftUI
- View
- onAppear(perform:)
Instance Method
onAppear(perform:)
Adds an action to perform before this view appears.
nonisolated
Parameters
action
The action to perform. If action is nil, the call has no effect.
Return Value
A view that triggers action before it appears.
Mentioned in
Understanding the navigation stack
Discussion
The exact moment that SwiftUI calls this method depends on the specific view type that you apply it to, but the action closure completes before the first rendered frame appears.
See Also
Responding to view life cycle updates
Adds an action to perform after this view disappears.
Adds an asynchronous task to perform before this view appears.
Adds a task to perform before this view appears or when a specified value changes.
https://developer.apple.com/documentation/swiftui/view/ondisappear(perform:)
#app-main)
- SwiftUI
- View
- onDisappear(perform:)
Instance Method
onDisappear(perform:)
Adds an action to perform after this view disappears.
nonisolated
Parameters
action
The action to perform. If action is nil, the call has no effect.
Return Value
A view that triggers action after it disappears.
Discussion
The exact moment that SwiftUI calls this method depends on the specific view type that you apply it to, but the action closure doesn’t execute until the view disappears from the interface.
See Also
Responding to view life cycle updates
Adds an action to perform before this view appears.
Adds an asynchronous task to perform before this view appears.
Adds a task to perform before this view appears or when a specified value changes.
https://developer.apple.com/documentation/swiftui/view/task(priority:_:)
#app-main)
- SwiftUI
- View
- task(priority:_:)
Instance Method
task(priority:_:)
Adds an asynchronous task to perform before this view appears.
nonisolated func task( priority: TaskPriority = .userInitiated,
Parameters
priority
The task priority to use when creating the asynchronous task. The default priority is userInitiated.
action
A closure that SwiftUI calls as an asynchronous task before the view appears. SwiftUI will automatically cancel the task at some point after the view disappears before the action completes.
Return Value
A view that runs the specified action asynchronously before the view appears.
Mentioned in
Understanding the navigation stack
Discussion
Use this modifier to perform an asynchronous task with a lifetime that matches that of the modified view. If the task doesn’t finish before SwiftUI removes the view or the view changes identity, SwiftUI cancels the task.
Use the await keyword inside the task to wait for an asynchronous call to complete, or to wait on the values of an AsyncSequence instance. For example, you can modify a Text view to start a task that loads content from a remote resource:
let url = URL(string: "https://example.com")! @State private var message = "Loading..."
var body: some View { Text(message) .task { do { var receivedLines = String for try await line in url.lines { receivedLines.append(line) message = "Received (receivedLines.count) lines" } } catch { message = "Failed to load" } } }
This example uses the lines method to get the content stored at the specified URL as an asynchronous sequence of strings. When each new line arrives, the body of the for- await- in loop stores the line in an array of strings and updates the content of the text view to report the latest line count.
See Also
Responding to view life cycle updates
Adds an action to perform before this view appears.
Adds an action to perform after this view disappears.
Adds a task to perform before this view appears or when a specified value changes.
https://developer.apple.com/documentation/swiftui/view/task(id:priority:_:)
#app-main)
- SwiftUI
- View
- task(id:priority:_:)
Instance Method
task(id:priority:_:)
Adds a task to perform before this view appears or when a specified value changes.
nonisolated
id value: T, priority: TaskPriority = .userInitiated,
Parameters
priority
The task priority to use when creating the asynchronous task. The default priority is userInitiated.
action
A closure that SwiftUI calls as an asynchronous task before the view appears. SwiftUI can automatically cancel the task after the view disappears before the action completes. If the id value changes, SwiftUI cancels and restarts the task.
Return Value
A view that runs the specified action asynchronously before the view appears, or restarts the task when the id value changes.
Discussion
This method behaves like task(priority:_:), except that it also cancels and recreates the task when a specified value changes. To detect a change, the modifier tests whether a new value for the id parameter equals the previous value. For this to work, the value’s type must conform to the Equatable protocol.
For example, if you define an equatable Server type that posts custom notifications whenever its state changes — for example, from signed out to signed in — you can use the task modifier to update the contents of a Text view to reflect the state of the currently selected server:
Text(status ?? "Signed Out") .task(id: server) { let sequence = NotificationCenter.default.notifications( named: .didUpdateStatus, object: server ).compactMap { $0.userInfo?["status"] as? String } for await value in sequence { status = value } }
This example uses the notifications(named:object:) method to create an asynchronous sequence of notifications, given by an AsyncSequence instance. The example then maps the notification sequence to a sequence of strings that correspond to values stored with each notification.
Elsewhere, the server defines a custom didUpdateStatus notification:
extension NSNotification.Name { static var didUpdateStatus: NSNotification.Name { NSNotification.Name("didUpdateStatus") } }
Whenever the server status changes, like after the user signs in, the server posts a notification of this custom type:
let notification = Notification( name: .didUpdateStatus, object: self, userInfo: ["status": "Signed In"]) NotificationCenter.default.post(notification)
The task attached to the Text view gets and displays the status value from the notification’s user information dictionary. When the user chooses a different server, SwiftUI cancels the task and creates a new one, which then waits for notifications from the new server.
See Also
Responding to view life cycle updates
Adds an action to perform before this view appears.
Adds an action to perform after this view disappears.
Adds an asynchronous task to perform before this view appears.
https://developer.apple.com/documentation/swiftui/view/id(_:)
#app-main)
- SwiftUI
- View
- id(_:)
Instance Method
id(_:)
Binds a view’s identity to the given proxy value.
nonisolated
Discussion
When the proxy value specified by the id parameter changes, the identity of the view — for example, its state — is reset.
See Also
Managing the view hierarchy
Sets the unique tag value of this view.
Prevents the view from updating its child view when its new value is the same as its old value.
https://developer.apple.com/documentation/swiftui/view/tag(_:includeoptional:)
#app-main)
- SwiftUI
- View
- tag(_:includeOptional:)
Instance Method
tag(_:includeOptional:)
Sets the unique tag value of this view.
nonisolated
_ tag: V, includeOptional: Bool = true
Parameters
tag
A Hashable value to use as the view’s tag.
includeOptional
Return Value
A view with the specified tag set.
Discussion
Use this modifier to differentiate among certain selectable views, like the possible values of a Picker or the tabs of a TabView. Tag values can be of any type that conforms to the Hashable protocol.
In the example below, the ForEach loop in the Picker view builder iterates over the Flavor enumeration. It extracts the string value of each enumeration element for use in constructing the row label, and uses the enumeration value as input to the tag(_:) modifier.
struct FlavorPicker: View { enum Flavor: String, CaseIterable, Identifiable { case chocolate, vanilla, strawberry var id: Self { self } }
@State private var selectedFlavor: Flavor? = nil
var body: some View { Picker("Flavor", selection: $selectedFlavor) { ForEach(Flavor.allCases) { flavor in Text(flavor.rawValue) .tag(flavor) } } } }
A ForEach automatically applies a default tag to each enumerated view using the id parameter of the corresponding element. If the element’s id parameter and the picker’s selection input have exactly the same type, or the same type but optional, you can omit the explicit tag modifier.
To see examples that don’t require an explicit tag, see Picker.
See Also
Managing the view hierarchy
Binds a view’s identity to the given proxy value.
Prevents the view from updating its child view when its new value is the same as its old value.
https://developer.apple.com/documentation/swiftui/view/equatable()
https://developer.apple.com/documentation/swiftui/viewmodifier)
https://developer.apple.com/documentation/swiftui/emptymodifier)
https://developer.apple.com/documentation/swiftui/environmentalmodifier)
https://developer.apple.com/documentation/swiftui/manipulablemodifier)
https://developer.apple.com/documentation/swiftui/manipulablerespondermodifier)
https://developer.apple.com/documentation/swiftui/manipulabletransformbindingmodifier)
https://developer.apple.com/documentation/swiftui/manipulationgeometrymodifier)
https://developer.apple.com/documentation/swiftui/manipulationgesturemodifier)
https://developer.apple.com/documentation/swiftui/manipulationusinggesturestatemodifier)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/manipulable)
https://developer.apple.com/documentation/swiftui/view/onappear(perform:))
https://developer.apple.com/documentation/swiftui/view/ondisappear(perform:))
https://developer.apple.com/documentation/swiftui/view/task(priority:_:))
https://developer.apple.com/documentation/swiftui/view/task(id:priority:_:))
https://developer.apple.com/documentation/swiftui/view/id(_:))
https://developer.apple.com/documentation/swiftui/view/tag(_:includeoptional:))
https://developer.apple.com/documentation/swiftui/view/equatable())
https://developer.apple.com/documentation/swiftui/fetchrequest
- SwiftUI
- FetchRequest
Structure
FetchRequest
A property wrapper type that retrieves entities from a Core Data persistent store.
@MainActor @propertyWrapper @preconcurrency
Overview
Use a FetchRequest property wrapper to declare a FetchedResults property that provides a collection of Core Data managed objects to a SwiftUI view. The request infers the entity type from the Result placeholder type that you specify. Condition the request with an optional predicate and sort descriptors. For example, you can create a request to list all Quake managed objects that the Loading and Displaying a Large Data Feed sample code project defines to store earthquake data, sorted by their time property:
@FetchRequest(sortDescriptors: [SortDescriptor(.time, order: .reverse)])
Alternatively, when you need more flexibility, you can initialize the request with a configured NSFetchRequest instance:
@FetchRequest(fetchRequest: request)
Always declare properties that have a fetch request wrapper as private. This lets the compiler help you avoid accidentally setting the property from the memberwise initializer of the enclosing view.
The fetch request and its results use the managed object context stored in the environment, which you can access using the managedObjectContext environment value. To support user interface activity, you typically rely on the viewContext property of a shared NSPersistentContainer instance. For example, you can set a context on your top level content view using a shared container that you define as part of your model:
ContentView() .environment( .managedObjectContext, QuakesProvider.shared.container.viewContext)
When you need to dynamically change the predicate or sort descriptors, access the request’s FetchRequest.Configuration structure. To create a request that groups the fetched results according to a characteristic that they share, use SectionedFetchRequest instead.
Topics
Creating a fetch request
init(sortDescriptors:predicate:animation:)
Creates a fetch request based on a predicate and reference type sort parameters.
Creates a fetch request for a specified entity description, based on a predicate and sort parameters.
Creating a fully configured fetch request
Creates a fully configured fetch request that uses the specified animation when updating results.
Creates a fully configured fetch request that uses the specified transaction when updating results.
Configuring a request dynamically
struct Configuration
The request’s configurable properties.
A binding to the request’s mutable configuration properties.
Getting the fetched results
func update()
Updates the fetched results.
The fetched results of the fetch request.
Relationships
Conforms To
-
Copyable -
DynamicPropertyConforms whenResultconforms toNSFetchRequestResult. -
Sendable -
SendableMetatype
See Also
Accessing Core Data
Loading and Displaying a Large Data Feed
Consume data in the background, and lower memory use by batching imports and preventing duplicate records.
var managedObjectContext: NSManagedObjectContext
struct FetchedResults
A collection of results retrieved from a Core Data store.
struct SectionedFetchRequest
A property wrapper type that retrieves entities, grouped into sections, from a Core Data persistent store.
struct SectionedFetchResults
A collection of results retrieved from a Core Data persistent store, grouped into sections.
https://developer.apple.com/documentation/swiftui/fetchedresults
- SwiftUI
- FetchedResults
Structure
FetchedResults
A collection of results retrieved from a Core Data store.
@MainActor @preconcurrency
Overview
Use a FetchedResults instance to show or edit Core Data managed objects in your app’s user interface. You request a particular set of results by specifying a Result type as the entity type, and annotating the fetched results property declaration with a FetchRequest property wrapper. For example, you can create a request to list all Quake managed objects that the Loading and Displaying a Large Data Feed sample code project defines to store earthquake data, sorted by their time property:
@FetchRequest(sortDescriptors: [SortDescriptor(.time, order: .reverse)])
The results instance conforms to RandomAccessCollection, so you access it like any other collection. For example, you can create a List that iterates over all the results:
List(quakes) { quake in NavigationLink(destination: QuakeDetail(quake: quake)) { QuakeRow(quake: quake) } }
When you need to dynamically change the request’s predicate or sort descriptors, set the result instance’s nsPredicate and sortDescriptors or nsSortDescriptors properties, respectively.
The fetch request and its results use the managed object context stored in the environment, which you can access using the managedObjectContext environment value. To support user interface activity, you typically rely on the viewContext property of a shared NSPersistentContainer instance. For example, you can set a context on your top level content view using a container that you define as part of your model:
ContentView() .environment( .managedObjectContext, QuakesProvider.shared.container.viewContext)
Topics
Configuring the associated fetch request
var nsPredicate: NSPredicate?
The request’s predicate.
The request’s sort descriptors, accessed as value types.
var nsSortDescriptors: [NSSortDescriptor]
The request’s sort descriptors, accessed as reference types.
Getting indices
var startIndex: Int
The index of the first entity in the results collection.
var endIndex: Int
The index that’s one greater than the last valid subscript argument.
Getting results
Gets the entity at the specified index.
Relationships
Conforms To
BidirectionalCollectionCollectionRandomAccessCollectionSendableSendableMetatypeSequence
See Also
Accessing Core Data
Loading and Displaying a Large Data Feed
Consume data in the background, and lower memory use by batching imports and preventing duplicate records.
var managedObjectContext: NSManagedObjectContext
struct FetchRequest
A property wrapper type that retrieves entities from a Core Data persistent store.
struct SectionedFetchRequest
A property wrapper type that retrieves entities, grouped into sections, from a Core Data persistent store.
struct SectionedFetchResults
A collection of results retrieved from a Core Data persistent store, grouped into sections.
https://developer.apple.com/documentation/swiftui/restoring_your_app_s_state_with_swiftui
- SwiftUI
- Restoring Your App’s State with SwiftUI
Sample Code
Restoring Your App’s State with SwiftUI
Provide app continuity for users by preserving their current activities.
Download
Xcode 12.0+
Overview
This SwiftUI sample project demonstrates how to preserve your appʼs state information and restore the app to that previous state on subsequent launches. During a subsequent launch, restoring your interface to the previous interaction point provides continuity for the user, and lets them finish active tasks quickly.
When using your app, the user performs actions that affect the user interface. For example, the user might view a specific page of information, and after the user leaves the app, the operating system might terminate it to free up the resources it holds. The user can
In Xcode, select your development team on the iOS target’s Signing and Capabilities tab.
Enable State Preservation and Restoration
This sample code project uses SwiftUI’s Scene to manage the app’s user interface with its life cycle managed by the system. On iOS, state restoration is especially important at the window or scene level, because windows come and go frequently. It’s necessary to save and restore state associated with each one. On the iPad, it’s especially important because an app in the switcher is not necessarily running. Scene-level state restoration preserves the illusion they are running.
To support state preservation and restoration, this sample uses NSUserActivity objects. For each user activity, the app must supply an activity type defined in its Info.plist.
Use Scene Storage
SwiftUI has the concept of “storing scene data” or SceneStorage. Operating similar to State, scene storage is a property wrapper type that consists of a key/value pair. The key makes it possible for the system to save and restore the value correctly. The value is required to be of a plist type, so the system can save and restore it correctly. iOS ingests this scene storage using the key/value and then reads and writes to persisted, per-scene storage. The OS manages saving and restoring scene storage on the user’s behalf. The underlying data that backs scene storage is not directly available, so the app must access it via @SceneStorage property wrapper. The OS makes no guarantees as to when and how often the data will be persisted. The data in scene storage is not necessarily equivalent to an application’s data model. Scene storage is intended to be used with the data model. Ultimately, consider scene storage a “state scoped to a scene”. Don’t use scene storage with sensitive data.
Each view that needs its own state preservation implements a @SceneStorage property wrapper. For example ContentView uses one to restore the selected product:
@SceneStorage("ContentView.selectedProduct") private var selectedProduct: String?
DetailView uses one to restore its current selected tab:
@SceneStorage("DetailView.selectedTab") private var selectedTab = Tabs.detail
Restore the App State with an Activity Object
An NSUserActivity object captures the app’s state at the current moment in time. For example, include information about the data the app is currently displaying. The system saves the provided object and returns it to the app the next time it launches. The sample creates a new NSUserActivity object when the user closes the app or the app enters the background.
Each SwiftUI view that wants to advertise an NSUserActivity for handoff, Spotlight, etc. must specify a userActivity(_:isActive:_:) view modifier to advertise the NSUserActivity. The activityType parameter is the user activity’s type, the isActive parameter indicates whether a user activity of the specified type is advertised (this parameter defaults to true), and whether it uses the specified handler to fill in the user-activity contents. The scope of the user activity applies only to the scene or window in which the view is. Multiple views can advertise the same activity type, and the handlers can all contribute to the contents of the user activity. Note that handlers are only called for userActivity view modifiers where the isActive parameter is true. If none of the userActivity view modifiers specify isActive as true, the user activity will not be advertised by iOS.
Each SwiftUI view that wants to handle incoming NSUserActivities must specify a onContinueUserActivity(_:perform:) view modifier. This takes the NSUserActivity type and a handler to invoke when the view receives the specified activity type for the scene or window in which the view is.
.onContinueUserActivity(DetailView.productUserActivityType) { userActivity in if let product = try? userActivity.typedPayload(Product.self) { selectedProduct = product.id.uuidString } }
Test State Restoration
This sample restores the following user interface:
-
Detail View Controller — Tap a product in the collection view to open its detail information. The app restores the selected product and selected tab.
-
Detail View Controller’s Edit State — In the detail view, tap Edit. The app restores the edit view and its content.
-
Secondary Window — (iPad only) Drag a product from the collection view over to the left or right of the device screen to create a second scene window. The app restores that scene and its product.
State restoration can be tested both on the device and Simulator. When debugging the sample project, the system automatically deletes its preserved state when the user force quits the app. Deleting the preserved state information is a safety precaution. In addition, the system also deletes the preserved state if this app crashes at launch time.
To test the sample app’s ability to restore the sample’s state, don’t use the app switcher to force quit it during debugging. Instead, use Xcode to stop the app or stop the app programmatically. Another technique is to suspend the sample app using the Home button, and then stop the debugger in Xcode. Launch the sample app again using Xcode, and SwiftUI initiates the state restoration process.
To use Spotlight with Handoff, follow these steps:
-
In Xcode set a breakpoint in
DetailView.swiftatonContinueUserActivityclosure. -
Run the sample project.
-
Tap a product (“Cherries”) in the collection view to navigate to its detail information.
-
Pull down the system sheet from the top of the screen (to force Spotlight to update its index and request the activity). Note that the
DetailViewuserActivityclosure is called by iOS. -
Go
Interface restoration
Restoring your app’s state
Provide continuity for the user by preserving current activities.
Return your app to its previous state after the system terminates it.
protocol UIViewControllerRestoration
The methods that objects adopt so that they can act as a restoration class for view controllers during state restoration.
protocol UIObjectRestoration
The interface that restoration classes use to restore preserved objects.
protocol UIStateRestoring
Methods for adding objects to your state restoration archives.
Restoring Your App’s State
https://developer.apple.com/documentation/swiftui/view/defaultappstorage(_:)
#app-main)
- SwiftUI
- View
- defaultAppStorage(_:)
Instance Method
defaultAppStorage(_:)
The default store used by AppStorage contained within the view.
nonisolated
Parameters
store
The user defaults to use as the default store for AppStorage.
Discussion
If unspecified, the default store for a view hierarchy is UserDefaults.standard, but can be set a to a custom one. For example, sharing defaults between an app and an extension can override the default store to one created with UserDefaults.init(suiteName:_).
See Also
Saving state across app launches
Restoring Your App’s State with SwiftUI
Provide app continuity for users by preserving their current activities.
struct AppStorage
A property wrapper type that reflects a value from UserDefaults and invalidates a view on a change in value in that user default.
struct SceneStorage
A property wrapper type that reads and writes to persisted, per-scene storage.
https://developer.apple.com/documentation/swiftui/appstorage
https://developer.apple.com/documentation/swiftui/scenestorage
- SwiftUI
- SceneStorage
Structure
SceneStorage
A property wrapper type that reads and writes to persisted, per-scene storage.
@frozen @propertyWrapper
Overview
You use SceneStorage when you need automatic state restoration of the value. SceneStorage works very similar to State, except its initial value is restored by the system if it was previously saved, and the value is shared with other SceneStorage variables in the same scene.
The system manages the saving and restoring of SceneStorage on your behalf. The underlying data that backs SceneStorage is not available to you, so you must access it via the SceneStorage property wrapper. The system makes no guarantees as to when and how often the data will be persisted.
Each Scene has its own notion of SceneStorage, so data is not shared between scenes.
Ensure that the data you use with SceneStorage is lightweight. Data of a large size, such as model data, should not be stored in SceneStorage, as poor performance may result.
If the Scene is explicitly destroyed (e.g. the switcher snapshot is destroyed on iPadOS or the window is closed on macOS), the data is also destroyed. Do not use SceneStorage with sensitive data.
Topics
Storing a value
init(wrappedValue:_:)
Creates a property that can save and restore an integer, transforming it to a RawRepresentable data type.
init(_:)
Creates a property that can save and restore an Optional boolean.
Getting the value
var wrappedValue: Value
The underlying value referenced by the state variable.
A binding to the state value.
Initializers
init(wrappedValue: Value, String, store: UserDefaults?)
Creates a property that can save and restore tab sidebar customizations.
Relationships
Conforms To
DynamicPropertySendableSendableMetatype
See Also
Saving state across app launches
Restoring Your App’s State with SwiftUI
Provide app continuity for users by preserving their current activities.
The default store used by AppStorage contained within the view.
struct AppStorage
A property wrapper type that reflects a value from UserDefaults and invalidates a view on a change in value in that user default.
https://developer.apple.com/documentation/swiftui/loading_and_displaying_a_large_data_feed
- SwiftUI
- Loading and Displaying a Large Data Feed
Sample Code
Loading and Displaying a Large Data Feed
Consume data in the background, and lower memory use by batching imports and preventing duplicate records.
Download
Xcode 13.0+
Overview
This sample creates an app that shows a list of earthquakes recorded in the United States in the past 30 days by consuming a U. S. Geological Survey (USGS) real-time data feed.
To load the USGS JSON feed, perform either of the following:
-
On iOS, pull to refresh the
List. -
On both iOS and macOS, press the refresh button (⌘R).
The app will load the requested data on the default delegate queue of URLSession, which is an operation queue that runs in the background. After the feed is downloaded and the session data task completes, the app continues working on this queue to import the large number of feed elements to the store without blocking the main queue.
Import Data in the Background
To import data in the background, apps may use one or two managed object contexts. The sample uses two ( NSManagedObjectContext) instances:
-
A main queue context to provide data to the user interface.
-
A private queue context to perform the import on a background queue.
Both contexts are connected to the same persistentStoreCoordinator. This configuration is more efficient than using a nested context.
The sample creates a main queue context by setting up a Core Data stack using NSPersistentContainer, which initializes a main queue context in its viewContext property.
let container = NSPersistentContainer(name: "Earthquakes")
Create a private queue context by calling the persistent container’s newBackgroundContext() method.
let taskContext = container.newBackgroundContext()
When the feed download finishes, the sample uses the task context to consume the feed in the background. In Core Data, every queue-based context has its own serial queue, and apps must serialize the tasks that manipulate the context with the queue by wrapping the code with a perform(_:) — with or without the await keyword — or performAndWait(_:) closure.
try await taskContext.perform {
For more information about working with concurrency, see NSManagedObjectContext.
To efficiently handle large data sets, the sample uses NSBatchInsertRequest which accesses the store directly — without interacting with the context, triggering any key value observation, or allocating managed objects. The closure-style initializer of NSBatchInsertRequest allows apps to provide one record at a time when Core Data calls the dictionaryHandler closure, which helps apps keep their memory footprint low because they do not need to prepare a buffer for all records.
let batchInsertRequest = self.newBatchInsertRequest(with: propertiesList) if let fetchResult = try? taskContext.execute(batchInsertRequest), let batchInsertResult = fetchResult as? NSBatchInsertResult, let success = batchInsertResult.result as? Bool, success { return }
Merge Changes and Update the User Interface
Because NSBatchInsertRequest bypasses the context and doesn’t trigger a NSManagedObjectContextDidSave notification, apps that need to update the UI with the changes have two options:
-
Extract the relevant changes by parsing the store’s Persistent history, then merge them into the view context. For more information on persistent history tracking, see Consuming relevant store changes.
-
Re-fetch the data from the store. However, if the view context is pinned to a query generation, the context will need to be reset before fetching data. For more information on query generations, see Accessing data when the store changes.
This sample uses persistent store remote change notifications and persistent history tracking to update the UI, because:
-
The data model contains a single entity, so all changes are relevant to the
Listand do not require parsing specific changes within the history. -
FetchRequestfetches and retrieves results directly from the store, and theListrefreshes its contents automatically. -
SwiftUI is only concerned about the view context, so
QuakesProviderobserves theNSPersistentStoreRemoteChangenotification to merge changes from the background context, performing the batch operations, into the view context.
Enable remote change notifications for a persistent store by setting the NSPersistentStoreRemoteChangeNotificationPostOptionKey option on the store description to true.
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
Enable persistent history tracking for a persistent store by setting the NSPersistentHistoryTrackingKey option to true as well.
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
Whenever changes occur within a persistent store, including writes by other processes, the store posts a remote change notification. When the sample receives the notification, it fetches the persistent history transactions and changes occurring after a given token. After the persistent history change request retrieves the history, the sample merges each transaction’s objectIDNotification() into the view context via mergeChanges(fromContextDidSave:).
let changeRequest = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastToken) let historyResult = try taskContext.execute(changeRequest) as? NSPersistentHistoryResult if let history = historyResult?.result as? [NSPersistentHistoryTransaction], !history.isEmpty { self.mergePersistentHistoryChanges(from: history) return }
After executing each NSBatchInsertRequest or NSBatchDeleteRequest, the sample dispatches any UI updates
When apps fetch or create objects in a context, Core Data caches the object to avoid a round trip to the store file when the app uses those objects again. However, that approach grows the memory footprint of an app as it processes more and more objects, and can eventually lead to low-memory warnings or app termination on iOS. NSBatchInsertRequest doesn’t obviously increase an app’s memory footprint because it doesn’t load data into memory.
The sample sets the viewContext’s automaticallyMergesChangesFromParent property to false to prevent Core Data from automatically merging changes every time the background context is saved.
container.viewContext.automaticallyMergesChangesFromParent = false
Prevent Duplicate Data in the Store
Every time the sample app reloads the JSON feed, the parsed data contains all earthquake records for the past month, so it can have many duplicates of already imported data. To avoid creating duplicate records, the app constrains an attribute, or combination of attributes, to be unique across all instances.
The code attribute uniquely identifies an earthquake record, so constraining the Quake entity on code ensures that no two stored records have the same code value.
Select the Quake entity in the data model editor. In the data model inspector, add a new constraint by clicking the + button under the Constraints list. A constraint placeholder appears.
comma, separated, properties
Double-click the placeholder to edit it. Enter the name of the attribute, or comma-separated list of attributes, to serve as unique constraints on the entity.
code
When saving a new record, the store now checks whether any record already exists with the same value for the constrained attribute. In the case of a conflict, an NSMergeByPropertyObjectTrumpMergePolicy policy comes into play, and the new record overwrites all fields in the existing record.
See Also
Background tasks
Using Core Data in the background
Use Core Data in both a single-threaded and multithreaded app.
Detect and resolve conflicts that occur when data is changed on multiple threads.
Use batch processes to manage large data changes.
https://developer.apple.com/documentation/swiftui/environmentvalues/managedobjectcontext
- SwiftUI
- EnvironmentValues
- managedObjectContext
Instance Property
managedObjectContext
var managedObjectContext: NSManagedObjectContext { get set }
See Also
Accessing Core Data
Loading and Displaying a Large Data Feed
Consume data in the background, and lower memory use by batching imports and preventing duplicate records.
struct FetchRequest
A property wrapper type that retrieves entities from a Core Data persistent store.
struct FetchedResults
A collection of results retrieved from a Core Data store.
struct SectionedFetchRequest
A property wrapper type that retrieves entities, grouped into sections, from a Core Data persistent store.
struct SectionedFetchResults
A collection of results retrieved from a Core Data persistent store, grouped into sections.
https://developer.apple.com/documentation/swiftui/sectionedfetchrequest
- SwiftUI
- SectionedFetchRequest
Structure
SectionedFetchRequest
A property wrapper type that retrieves entities, grouped into sections, from a Core Data persistent store.
@MainActor @propertyWrapper @preconcurrency
Overview
Use a SectionedFetchRequest property wrapper to declare a SectionedFetchResults property that provides a grouped collection of Core Data managed objects to a SwiftUI view. If you don’t need sectioning, use FetchRequest instead.
Configure a sectioned fetch request with an optional predicate and sort descriptors, and include a sectionIdentifier parameter to indicate how to group the fetched results. Be sure that you choose sorting and sectioning that work together to avoid discontiguous sections. For example, you can request a list of earthquakes, composed of Quake managed objects that the Loading and Displaying a Large Data Feed sample code project defines to store earthquake data, sorted by time and grouped by date:
sectionIdentifier: .day, sortDescriptors: [SortDescriptor(.time, order: .reverse)] )
Always declare properties that have a sectioned fetch request wrapper as private. This lets the compiler help you avoid accidentally setting the property from the memberwise initializer of the enclosing view.
The request infers the entity type from the Result type that you specify, which is Quake in the example above. Indicate a SectionIdentifier type to declare the type found at the fetched object’s sectionIdentifier key path. The section identifier type must conform to the Hashable protocol.
The example above depends on the Quake type having a day property that’s either a stored or computed string. Be sure to mark any computed property with the @objc attribute for it to function as a section identifier. For best performance with large data sets, use stored properties.
The sectioned fetch request and its results use the managed object context stored in the environment, which you can access using the managedObjectContext environment value. To support user interface activity, you typically rely on the viewContext property of a shared NSPersistentContainer instance. For example, you can set a context on your top-level content view using a shared container that you define as part of your model:
ContentView() .environment( .managedObjectContext, QuakesProvider.shared.container.viewContext)
When you need to dynamically change the section identifier, predicate, or sort descriptors, access the request’s SectionedFetchRequest.Configuration structure, either directly or with a binding.
Topics
Creating a fetch request
init(sectionIdentifier:sortDescriptors:predicate:animation:)
Creates a sectioned fetch request based on a section identifier, a predicate, and reference type sort parameters.
Creates a sectioned fetch request for a specified entity description, based on a section identifier, a predicate, and sort parameters.
Creating a fully configured fetch request
Creates a fully configured sectioned fetch request that uses the specified animation when updating results.
Creates a fully configured sectioned fetch request that uses the specified transaction when updating results.
Configuring a request dynamically
struct Configuration
The request’s configurable properties.
A binding to the request’s mutable configuration properties.
Getting the fetched results
func update()
Updates the fetched results.
The fetched results of the fetch request.
Relationships
Conforms To
CopyableDynamicPropertyConforms whenSectionIdentifierconforms toHashableandResultconforms toNSFetchRequestResult.
See Also
Accessing Core Data
Loading and Displaying a Large Data Feed
Consume data in the background, and lower memory use by batching imports and preventing duplicate records.
var managedObjectContext: NSManagedObjectContext
struct FetchRequest
A property wrapper type that retrieves entities from a Core Data persistent store.
struct FetchedResults
A collection of results retrieved from a Core Data store.
struct SectionedFetchResults
A collection of results retrieved from a Core Data persistent store, grouped into sections.
https://developer.apple.com/documentation/swiftui/sectionedfetchresults
- SwiftUI
- SectionedFetchResults
Structure
SectionedFetchResults
A collection of results retrieved from a Core Data persistent store, grouped into sections.
@MainActor @preconcurrency
Overview
Use a SectionedFetchResults instance to show or edit Core Data managed objects, grouped into sections, in your app’s user interface. If you don’t need sectioning, use FetchedResults instead.
You request a particular set of results by annotating the fetched results property declaration with a SectionedFetchRequest property wrapper. Indicate the type of the fetched entities with a Results type, and the type of the identifier that distinguishes the sections with a SectionIdentifier type. For example, you can create a request to list all Quake managed objects that the Loading and Displaying a Large Data Feed sample code project defines to store earthquake data, sorted by their time property and grouped by a string that represents the days when earthquakes occurred:
sectionIdentifier: .day, sortDescriptors: [SortDescriptor(.time, order: .reverse)] )
The quakes property acts as a collection of SectionedFetchResults.Section instances, each containing a collection of Quake instances. The example above depends on the Quake model object declaring both time and day properties, either stored or computed. For best performance with large data sets, use stored properties.
The collection of sections, as well as the collection of managed objects in each section, conforms to the RandomAccessCollection protocol, so you can access them as you would any other collection. For example, you can create nested ForEach loops inside a List to iterate over the results:
List { ForEach(quakes) { section in Section(header: Text(section.id)) { ForEach(section) { quake in QuakeRow(quake: quake) // Displays information about a quake. } } } }
Don’t confuse the Section view that you use to create a hierarchical display with the SectionedFetchResults.Section instances that hold the fetched results.
When you need to dynamically change the request’s section identifier, predicate, or sort descriptors, set the result instance’s sectionIdentifier, nsPredicate, and sortDescriptors or nsSortDescriptors properties, respectively. Be sure that the sorting and sectioning work together to avoid discontinguous sections.
The fetch request and its results use the managed object context stored in the environment, which you can access using the managedObjectContext environment value. To support user interface activity, you typically rely on the viewContext property of a shared NSPersistentContainer instance. For example, you can set a context on your top-level content view using a container that you define as part of your model:
ContentView() .environment( .managedObjectContext, QuakesProvider.shared.container.viewContext)
Topics
Configuring the associated sectioned fetch request
var nsPredicate: NSPredicate?
The request’s predicate.
The request’s sort descriptors, accessed as value types.
var nsSortDescriptors: [NSSortDescriptor]
The request’s sort descriptors, accessed as reference types.
The key path that the system uses to group fetched results into sections.
struct Section
A collection of fetched results that share a specified identifier.
Getting indices
var startIndex: Int
The index of the first section in the results collection.
var endIndex: Int
The index that’s one greater than that of the last section.
Getting results
Gets the section at the specified index.
Relationships
Conforms To
BidirectionalCollectionCollectionRandomAccessCollectionSendableSendableMetatypeSequence
See Also
Accessing Core Data
Loading and Displaying a Large Data Feed
Consume data in the background, and lower memory use by batching imports and preventing duplicate records.
var managedObjectContext: NSManagedObjectContext
struct FetchRequest
A property wrapper type that retrieves entities from a Core Data persistent store.
struct FetchedResults
A collection of results retrieved from a Core Data store.
struct SectionedFetchRequest
A property wrapper type that retrieves entities, grouped into sections, from a Core Data persistent store.
https://developer.apple.com/documentation/swiftui/fetchrequest)
https://developer.apple.com/documentation/swiftui/fetchedresults)
https://developer.apple.com/documentation/swiftui/restoring_your_app_s_state_with_swiftui)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/view/defaultappstorage(_:))
https://developer.apple.com/documentation/swiftui/appstorage)
https://developer.apple.com/documentation/swiftui/scenestorage)
https://developer.apple.com/documentation/swiftui/loading_and_displaying_a_large_data_feed)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/environmentvalues/managedobjectcontext)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/swiftui/sectionedfetchrequest)
https://developer.apple.com/documentation/swiftui/sectionedfetchresults)
https://developer.apple.com/documentation/swiftui/view/contextmenu(menuitems:)
#app-main)
- SwiftUI
- View
- contextMenu(menuItems:)
Instance Method
contextMenu(menuItems:)
Adds a context menu to a view.
watchOS 6.0–7.0Deprecated
nonisolated
Parameters
menuItems
A closure that produces the menu’s contents. You can deactivate the context menu by returning nothing from the closure.
Return Value
A view that can display a context menu.
Discussion
Use this modifier to add a context menu to a view in your app’s user interface. Compose the menu by returning controls like Button, Toggle, and Picker from the menuItems closure. You can also use Menu to define submenus or Section to group items.
The following example creates a Text view that has a context menu with two buttons:
Text("Turtle Rock") .padding() .contextMenu { Button { // Add this item to a list of favorites. } label: { Label("Add to Favorites", systemImage: "heart") } Button { // Open Maps and center it on this item. } label: { Label("Show in Maps", systemImage: "mappin") } }
When someone activates the context menu with an action like touch and hold in iOS or iPadOS, the system displays the menu next to the content:
The system dismisses the menu if someone makes a selection, or taps or clicks outside the menu.
To customize the default preview, apply a contentShape(_:_:eoFill:) with a contextMenuPreview kind. For example, you can change the preview’s corner radius or use a nested view as the preview.
If you want to show a different preview, you can use contextMenu(menuItems:preview:). To add a context menu to a container that supports selection, like a List or a Table, and to distinguish between menu activation on a selection and activation in an empty area of the container, use contextMenu(forSelectionType:menu:primaryAction:).
See Also
Creating context menus
Adds a context menu with a custom preview to a view.
Adds an item-based context menu to a view.
https://developer.apple.com/documentation/swiftui/populating-swiftui-menus-with-adaptive-controls
https://developer.apple.com/documentation/swiftui/view/menustyle(_:)
#app-main)
- SwiftUI
- View
- menuStyle(_:)
Instance Method
menuStyle(_:)
Sets the style for menus within this view.
nonisolated
Discussion
To set a specific style for all menu instances within a view, use the menuStyle(_:) modifier:
Menu("PDF") { Button("Open in Preview", action: openInPreview) Button("Save as PDF", action: saveAsPDF) } .menuStyle(ButtonMenuStyle())
See Also
Creating a menu
Populating SwiftUI menus with adaptive controls
Improve your app by populating menus with controls and organizing your content intuitively.
struct Menu
A control for presenting a menu of actions.
https://developer.apple.com/documentation/swiftui/view/contextmenu(menuitems:preview:)
#app-main)
- SwiftUI
- View
- contextMenu(menuItems:preview:)
Instance Method
contextMenu(menuItems:preview:)
Adds a context menu with a custom preview to a view.
nonisolated
Parameters
menuItems
A closure that produces the menu’s contents. You can deactivate the context menu by returning nothing from the closure.
preview
A view that the system displays along with the menu.
Return Value
A view that can display a context menu with a preview.
Discussion
When you use this modifer to add a context menu to a view in your app’s user interface, the system displays the custom preview beside the menu. Compose the menu by returning controls like Button, Toggle, and Picker from the menuItems closure. You can also use Menu to define submenus or Section to group items.
Define the custom preview by returning a view from the preview closure. The system sizes the preview to match the size of its content. For example, you can add a two button context menu to a Text view, and use an Image as the preview:
Text("Turtle Rock") .padding() .contextMenu { Button { // Add this item to a list of favorites. } label: { Label("Add to Favorites", systemImage: "heart") } Button { // Open Maps and center it on this item. } label: { Label("Show in Maps", systemImage: "mappin") } } preview: { Image("turtlerock") // Loads the image from an asset catalog. }
When someone activates the context menu with an action like touch and hold in iOS or iPadOS, the system displays the image and the menu:
To customize the lift preview, shown while the system transitions to show your custom preview, apply a contentShape(_:_:eoFill:) with a contextMenuPreview kind. For example, you can change the lift preview’s corner radius or use a nested view as the lift preview.
If you don’t need a preview, use contextMenu(menuItems:) instead. If you want to add a context menu to a container that supports selection, like a List or a Table, and you want to distinguish between menu activation on a selection and activation in an empty area of the container, use contextMenu(forSelectionType:menu:primaryAction:).
See Also
Creating context menus
Adds a context menu to a view.
Adds an item-based context menu to a view.
https://developer.apple.com/documentation/swiftui/view/contextmenu(forselectiontype:menu:primaryaction:)
https://developer.apple.com/documentation/swiftui/scene/commandsremoved()
#app-main)
- SwiftUI
- Scene
- commandsRemoved()
Instance Method
commandsRemoved()
Removes all commands defined by the modified scene.
nonisolated
Return Value
A scene that excludes any commands defined by its children.
Discussion
WindowGroup, Window, and other scene types all have an associated set of commands that they include by default. Apply this modifier to a scene to exclude those commands.
@main struct Example: App { var body: some Scene { ...
WindowGroup("Note", id: "note", for: Note.ID.self) { NoteDetailView(id: $0) } .commandsRemoved() } }
See Also
Defining commands
Adds commands to the scene.
Replaces all commands defined by the modified scene with the commands from the builder.
protocol Commands
Conforming types represent a group of related commands that can be exposed to the user via the main menu on macOS and key commands on iOS.
struct CommandMenu
Command menus are stand-alone, top-level containers for controls that perform related, app-specific commands.
struct CommandGroup
Groups of controls that you can add to existing command menus.
struct CommandsBuilder
Constructs command sets from multi-expression closures. Like ViewBuilder, it supports up to ten expressions in the closure body.
struct CommandGroupPlacement
The standard locations that you can place new command groups relative to.
https://developer.apple.com/documentation/swiftui/scene/commandsreplaced(content:)
#app-main)
- SwiftUI
- Scene
- commandsReplaced(content:)
Instance Method
commandsReplaced(content:)
Replaces all commands defined by the modified scene with the commands from the builder.
nonisolated
Parameters
content
A Commands builder whose output will be used to replace the commands normally provided by the modified scene.
Return Value
A scene that replaces any commands defined by its children with alternative content.
Discussion
WindowGroup, Window, and other scene types all have an associated set of commands that they include by default. Apply this modifier to a scene to replace those commands with the output from the given builder.
@main struct Example: App { @Environment(.openWindow) var openWindow
var body: some Scene { ...
Window("Clipboard", id: "clipboard") { ClipboardContentView() } .commandsReplaced { CommandGroup(after: .pasteboard) { Section { Button("Show Clipboard") { openWindow(id: "clipboard") } } } } } }
See Also
Defining commands
Adds commands to the scene.
Removes all commands defined by the modified scene.
protocol Commands
Conforming types represent a group of related commands that can be exposed to the user via the main menu on macOS and key commands on iOS.
struct CommandMenu
Command menus are stand-alone, top-level containers for controls that perform related, app-specific commands.
struct CommandGroup
Groups of controls that you can add to existing command menus.
struct CommandsBuilder
Constructs command sets from multi-expression closures. Like ViewBuilder, it supports up to ten expressions in the closure body.
struct CommandGroupPlacement
The standard locations that you can place new command groups relative to.
https://developer.apple.com/documentation/swiftui/commands
https://developer.apple.com/documentation/swiftui/commandmenu
- SwiftUI
- CommandMenu
Structure
CommandMenu
Command menus are stand-alone, top-level containers for controls that perform related, app-specific commands.
Mentioned in
Grouping data with lazy stack views
Building and customizing the menu bar with SwiftUI
Overview
Command menus are realized as menu bar menus on macOS, inserted between the built-in View and Window menus in order of declaration. On iOS, iPadOS, and tvOS, SwiftUI creates key commands for each of a menu’s commands that has a keyboard shortcut.
Topics
Creating a command menu
init(_:content:)
Creates a new menu with a localized name for a collection of app- specific commands, inserted in the standard location for app menus (after the View menu, in order with other menus declared without an explicit location).
Relationships
Conforms To
Commands
See Also
Defining commands
Adds commands to the scene.
Removes all commands defined by the modified scene.
Replaces all commands defined by the modified scene with the commands from the builder.
protocol Commands
Conforming types represent a group of related commands that can be exposed to the user via the main menu on macOS and key commands on iOS.
struct CommandGroup
Groups of controls that you can add to existing command menus.
struct CommandsBuilder
Constructs command sets from multi-expression closures. Like ViewBuilder, it supports up to ten expressions in the closure body.
struct CommandGroupPlacement
The standard locations that you can place new command groups relative to.