跳转至
Protocol

View

A type that represents part of your app's user interface and provides modifiers that you use to configure views.

Declaration

protocol View

Overview

Conform to this protocol in order to organize an app's UI into customizable, related parts.

View Conformance

You create custom views by declaring types that conform to the View protocol.

Requirements

Implement the required body computed property to provide the content for your custom view.

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
    }
}
A custom view that reads "Hello, World!" in the center of the screen.

Using View

Assemble the view's body by combining one or more of the primitive views provided by SwiftUI, like the Text instance in the example above, plus other custom views that you define, into a hierarchy of views.

Default Implementations

The View protocol provides a large set of modifiers, defined as protocol methods with default implementations, that you use to position and configure views in the layout of your app. Modifiers typically work by wrapping the view instance on which you call them in another view with the specified characteristics. For example, adding the opacity(_:) modifier to a text view returns a new view with some amount of transparency:

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .opacity(0.5) // Display partially transparent text.
    }
}
A custom view that reads "Hello, World!" in the center of the screen with an opacity modifier applied to make the text a lighter grey color, rather than black.

The effects of a modifier typically propagate to any child views that don't explicitly override the modifier. For example, a VStack instance on its own acts only to vertically stack other views, and has no text to display. Therefore, a font(_:) modifier that you apply to the stack has no effect on the stack itself. Yet the font modifier does apply to any of the stack's child views, some of which might display text. On the other hand, you can locally override the stack's modifier by adding another to a specific child view:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Title")
                .font(.headline) // Override the font of this one view.
            Text("First body line.")
            Text("Second body line.")
        }
        .font(.body) // Set a default for text in the stack.
    }
}
A screenshot of three text views in a VStack, where the second and third are displayed in body font, but the first has a modifier applied directly to render it in headline font.

You commonly chain modifiers, each wrapping the result of the previous one. 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:

struct ContentView: View {
    var body: some View {
        Text("Title")
            .frame(width: 100)
            .border(Color.gray)
    }
}
A screenshot of a text view displaying the string "Title", outlined by a gray rectangle that's wider than the string it encloses, leaving empty space inside the rectangle on either side of the string.

The order in which you apply modifiers matters. For example, the border that results from the above code outlines the full width of the frame. If you instead apply the border first, it outlines the text view, which never takes more space than it needs to render its contents. Wrapping that view in another invisible one with a fixed 100 point width affects the layout of the composite view, but has no effect on the border.

struct ContentView: View {
    var body: some View {
        Text("Title")
            .border(Color.gray) //apply the border first this time
            .frame(width: 100)
    }
}
A screenshot of a text view displaying the string "Title", outlined by a gray rectangle that properly contains it, leaving no empty space inside the rectangle on either side of the string.

Availability

iOS 13.0+

macOS 10.15+

tvOS 13.0+

watchOS 6.0+

Topics


Instance Method

accentColor(_:) A view modifier that sets the accent color for this view and the views it contains.

accessibility(activationPoint:) Specifies the point where activations occur in the view.

accessibility(activationPoint:) Specifies the unit point where activations occur in the view.

accessibility(addTraits:) Adds the given traits to the view.

accessibility(hidden:) Specifies whether to hide this view from system accessibility features.

accessibility(hint:) Communicates to the user what happens after performing the view's action.

accessibility(identifier:) Uses the specified string to identify the view.

accessibility(inputLabels:) Sets alternate input labels with which users identify a view.

accessibility(label:) Adds a label to the view that describes its contents.

accessibility(removeTraits:) Removes the given traits from this view.

accessibility(selectionIdentifier:) Sets a selection identifier for this view's accessibility element.

accessibility(sortPriority:) Sets the sort priority order for this view's accessibility element, relative to other elements at the same level.

accessibility(value:) Adds a textual description of the value that the view contains.

accessibilityAction(_:_:) Adds an accessibility action to this view.

accessibilityAction(named:_:) Adds a custom accessibility action to the view and all subviews.

accessibilityAction(named:_:) Adds a custom accessibility action to the view and all subviews.

accessibilityAction(named:_:) Adds a custom accessibility action to the view and all subviews.

accessibilityActivationPoint(_:) Specifies the point where activations occur in the view.

accessibilityActivationPoint(_:) Specifies the unit point where activations occur in the view.

accessibilityAddTraits(_:) Adds the given traits to the view.

accessibilityAdjustableAction(_:) Adds an accessibility adjustable action to the view.

accessibilityElement(children:) Wraps this view as a new accessibility element.

accessibilityHidden(_:) Specifies whether to hide this view from system accessibility features.

accessibilityHint(_:) Communicates to the user what happens after performing the view's action.

accessibilityHint(_:) Communicates to the user what happens after performing the view's action.

accessibilityHint(_:) Communicates to the user what happens after performing the view's action.

accessibilityIdentifier(_:) Uses the specified string to identify the view.

accessibilityIgnoresInvertColors(_:) Sets whether this view should ignore the system Smart Invert setting.

accessibilityInputLabels(_:) Sets alternate input labels with which users identify a view.

accessibilityInputLabels(_:) Sets alternate input labels with which users identify a view.

accessibilityInputLabels(_:) Sets alternate input labels with which users identify a view.

accessibilityLabel(_:) Adds a label to the view that describes its contents.

accessibilityLabel(_:) Adds a label to the view that describes its contents.

accessibilityLabel(_:) Adds a label to the view that describes its contents.

accessibilityLabeledPair(role:id:in:) Pairs two views, where one is the content and one is the label, for accessibility purposes.

accessibilityLinkedGroup(id:in:) 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.

accessibilityRemoveTraits(_:) Removes the given traits from this view.

accessibilityScrollAction(_:) Adds an accessibility scroll action to the view.

accessibilitySortPriority(_:) Sets the sort priority order for this view's accessibility element, relative to other elements at the same level.

accessibilityValue(_:) Adds a textual description of the value that the view contains.

accessibilityValue(_:) Adds a textual description of the value that the view contains.

accessibilityValue(_:) Adds a textual description of the value that the view contains.

actionSheet(isPresented:content:) A view modifier that presents an action sheet when a given condition is true.

actionSheet(item:content:) A view modifier that presents an action sheet that is passed a value.

alert(isPresented:content:) A view modifier that presents an alert when a given condition is true.

alert(item:content:) A view modifier that presents an alert when a given value is not nil.

alignmentGuide(_:computeValue:) Sets the view's vertical alignment.

alignmentGuide(_:computeValue:) Sets the view's horizontal alignment.

allowsHitTesting(_:) A view modifier that enables/disables user interaction.

allowsTightening(_:) A view modifier whether text in this view can compress the space between characters when necessary to fit text in a line.

anchorPreference(key:value:transform:) A view modifier that sets the value of a preference for a specified anchor.

animation(_:) Applies the given animation to all animatable values within this view.

animation(_:value:) A view modifier that applies the given animation to this view when the specified value changes.

aspectRatio(_:contentMode:) A view modifier that constrains this view's dimensions to the aspect ratio of the given size.

aspectRatio(_:contentMode:) A view modifier that constrains this view's dimensions to the specified aspect ratio.

autocapitalization(_:) A view modifier that sets whether to apply auto-capitalization to this view.

background(_:alignment:) Places a view behind the current view.

backgroundPreferenceValue(_:_:) Places a new view in the background of the first view, using the values from the preferences.

blendMode(_:) A view modifier that sets the blend mode for compositing this view with overlapping views.

blur(radius:opaque:) A view modifier that applies a Gaussian blur to this view.

border(_:width:) A view modifier that adds a border to the view with the specified style and width.

brightness(_:) Brighten the view by the specified amount.

buttonStyle(_:) Sets the style for buttons within this view to a button style with a custom appearance and standard interaction behavior.

buttonStyle(_:) Sets the style for buttons within this view to a button style with a custom appearance and custom interaction behavior.

clipped(antialiased:) A view modifier that clips this view to its bounding rectangular frame.

clipShape(_:style:) A view modifier that sets a clipping shape for this view.

colorInvert() A view modifier that inverts the colors in this view.

colorMultiply(_:) A view modifier that adds a color multiplication effect to this view.

colorScheme(_:) A view modifier that sets this view's color scheme.

compositingGroup() A view modifier that wraps this view in a compositing group.

contentShape(_:eoFill:) Changes the tappable area of a content shape for hit testing.

contextMenu(_:) A deprecated view modifier that attaches a context menu and its children to the view.

contextMenu(menuItems:) A view modifier that provides right click (macOS) or long hold (iOS) menu items.

contrast(_:) A view modifier that sets the contrast and separation between similar colors in this view.

coordinateSpace(name:) 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.

cornerRadius(_:antialiased:) A view modifier that clips this view to its bounding frame, with the specified corner radius.

datePickerStyle(_:) A view modifier to change a date picker style.

defaultAppStorage(_:) Use this modifier to change a scene's default storage for the @AppStorage property wrapper.

deleteDisabled(_:) Disable a list item's delete action.

disableAutocorrection(_:) A view modifier that disables autocorrection.

disabled(_:) Prevent view interaction.

drawingGroup(opaque:colorMode:) A view modifier that composites this view's contents into an offscreen image before final display.

edgesIgnoringSafeArea(_:) Changes the view's proposed area to extend outside the screen's safe

environment(_:_:) A view modifier that sets the environment value of the specified key path to the given value.

environmentObject(_:) Supplies an ObservableObject to a view subhierachy.

equatable() A view modifier that prevents the view from updating its child view when its new value is the same as its old value.

fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:) Presents a system interface for allowing the user to export an in-memory document to a file on disk.

fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:) Presents a system interface for allowing the user to export an in-memory document to a file on disk.

fileExporter(isPresented:documents:contentType:onCompletion:) Presents a system interface for allowing the user to export a collection of in-memory documents to files on disk.

fileExporter(isPresented:documents:contentType:onCompletion:) Presents a system interface for allowing the user to export a collection of in-memory documents to files on disk.

fileImporter(isPresented:allowedContentTypes:allowsMultipleSelection:onCompletion:) A view modifier that presents a system interface for allowing the user to import multiple files.

fileImporter(isPresented:allowedContentTypes:onCompletion:) A view modifier that presents a system interface for allowing the user to import an existing file.

fileMover(isPresented:file:onCompletion:) Presents a system interface for allowing the user to move an existing file to a new location.

fileMover(isPresented:files:onCompletion:) Presents a system interface for allowing the user to move a collection of existing files to a new location.

fixedSize() A view modifier that fixes this view at its ideal size.

fixedSize(horizontal:vertical:) A view modifier that fixes this view at its ideal size in the specified dimensions.

flipsForRightToLeftLayoutDirection(_:) A view modifier that sets whether this view flips its contents horizontally when the layout direction is right-to-left.

focusedValue(_:_:) Modifies this view by injecting a value that you provide for use by other views whose state depends on the focused view hierarchy.

font(_:) A view modifier that sets the default font for text in this view.

foregroundColor(_:) Sets the color primary color of a view.

frame() Positions this view within an invisible frame.

frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:) A view modifier that positions this view within an invisible frame having the specified size constraints.

frame(width:height:alignment:) A view modifier that positions this view within an invisible frame with the specified size.

fullScreenCover(isPresented:onDismiss:content:) A view modifier that presents a sheet overlaid over the full screen without a custom parameter.

fullScreenCover(item:onDismiss:content:) A view modifier that presents a sheet overlaid over the full screen.

gesture(_:including:) A view modifier that connects a gesture to the view, with lower priority than existing gestures.

grayscale(_:) A view modifier that adds a grayscale effect to this view.

groupBoxStyle(_:) A view modifier that sets the style for group boxes within this view.

handlesExternalEvents(preferring:allowing:) Specifies a modifier indicating the Scene this View is in can handle matching incoming External Events.

help(_:) Adds help text to a view using a text view that you provide.

help(_:) Adds help text to a view using a string that you provide.

help(_:) Adds help text to a view using a localized string that you provide.

hidden() A view modifier that hides this view unconditionally.

highPriorityGesture(_:including:) A view modifier that connects a gesture to the view, with higher priority than existing gestures.

hoverEffect(_:) A view modifier that adds a pointer hover effect to the view.

hueRotation(_:) Applies a hue rotation effect.

id(_:) Binds a view's identity to the given proxy value.

ignoresSafeArea(_:edges:) A view modifier that expands the view out of its safe area.

imageScale(_:) A view modifier that scales images within the view according to one of the relative sizes available including small, medium, and large images sizes.

indexViewStyle(_:) A view modifier that sets the tab view page dots style.

itemProvider(_:) A view modifier that sets the item provider used for drag and drop.

keyboardShortcut(_:) A view modifier that assigns a keyboard shortcut to the modified control.

keyboardShortcut(_:modifiers:) A view modifier that defines a keyboard shortcut and assigns it to the modified control.

keyboardType(_:) A view modifier that sets the keyboard type for this view.

labelsHidden() A view modifier that hides the labels of any controls contained within this view.

labelStyle(_:) Sets the style for labels within this view.

layoutPriority(_:) Sets the priority by which a parent layout should apportion space to this child.

lineLimit(_:) A view modifier that sets the maximum number of lines that text can occupy in this view.

lineSpacing(_:) A view modifier that sets the amount of space between lines of text in this view.

listItemTint(_:) Sets a fixed tint color associated with specific content in a list.

listItemTint(_:) Sets the tint effect associated with specific content in a list.

listRowBackground(_:) Places a custom background view behind a list row item.

listRowInsets(_:) A view modifier that applies an inset to the rows in a list.

listStyle(_:) Sets the style for lists within this view.

luminanceToAlpha() A view modifier that adds a luminance to alpha effect to this view.

mask(_:) Mask one view on top of another.

matchedGeometryEffect(id:in:properties:anchor:isSource:) Defines a group of views with synchronized geometry using an identifier and namespace that you provide.

menuStyle(_:) A view modifier that sets the style for menus.

minimumScaleFactor(_:) A view modifier that sets the minimum amount that text in this view scales down to fit in the available space.

modifier(_:) A view modifier that applies a modifier to a view and returns a new view.

moveDisabled(_:) Disable a list item's "move" action.

multilineTextAlignment(_:) A view modifier that sets the alignment of multiline text in this view.

navigationBarBackButtonHidden(_:) A view modifier that hides the navigation bar back button for the view.

navigationBarHidden(_:) Hides the navigation bar for this view.

navigationBarItems(leading:) Sets the navigation bar items for this view.

navigationBarItems(leading:trailing:) Sets the navigation bar items for this view.

navigationBarItems(trailing:) Configures the navigation bar items for this view.

navigationBarTitle(_:) A view modifier that sets the title in the navigation bar for this view.

navigationBarTitle(_:) A view modifier that sets the title of this view's navigation bar with a string.

navigationBarTitle(_:) A view modifier that sets the title of this view's navigation bar with a localized string.

navigationBarTitle(_:displayMode:) A view modifier that sets the title and display mode in the navigation bar for this view.

navigationBarTitle(_:displayMode:) A view modifier that sets the title and display mode in the navigation bar for this view.

navigationBarTitle(_:displayMode:) A view modifier that sets the title and display mode in the navigation bar for this view.

navigationBarTitleDisplayMode(_:) Configures the title display mode for this view.

navigationTitle(_:) Configures the view's title for purposes of navigation.

navigationTitle(_:) Configures the view's title for purposes of navigation, using a localized string.

navigationTitle(_:) Configures the view's title for purposes of navigation, using a string.

navigationViewStyle(_:) Sets the style for navigation views within this view.

offset(_:) A view modifier that translates this view horizontally and vertically by a CGSize.

offset(x:y:) A view modifier this view by the specified horizontal and vertical CGFloats.

onAppear(perform:) Perform an action when a view appears.

onChange(of:perform:) Adds a modifier for this view that fires an action when a specific value changes.

onContinueUserActivity(_:perform:) Registers a handler to invoke when the view receives the specified activity type for the scene or window the view is in.

onDisappear(perform:) A view modifier that performs an action when the view disappears.

onDrag(_:) Make a view draggable by providing dragged info.

onDrop(of:delegate:) Creates a drop-zone for drag & drop contents and provides drop location data.

onDrop(of:delegate:) Creates a drop-zone for drag & drop contents and provides drop location data.

onDrop(of:isTargeted:perform:) Creates a drop-zone for drag & drop contents.

onDrop(of:isTargeted:perform:) Creates a drop-zone for drag & drop contents and provides drop location data.

onDrop(of:isTargeted:perform:) Creates a drop-zone for drag & drop contents.

onDrop(of:isTargeted:perform:) Creates a drop-zone for drag & drop contents and provides drop location data.

onHover(perform:) A view modifier that adds an action to perform when the user moves the pointer over or away from the view's frame.

onLongPressGesture(minimumDuration:maximumDistance:pressing:perform:) A view modifier that calls a function after a long press.

onOpenURL(perform:) Registers a handler to invoke when the view receives a url for the scene or window the view is in.

onPreferenceChange(_:perform:) Adds an action to perform when the specified preference key's value changes.

onReceive(_:perform:) A view modifier that calls a function whenever a value is received by a publisher.

onTapGesture(count:perform:) A view modifier that adds an action to perform when this view recognizes a tap gesture.

opacity(_:) Sets the transparency of a view.

overlay(_:alignment:) A view modifier that places a view in front of the current view.

overlayPreferenceValue(_:_:) Uses the specified preference value from the view to produce another view as an overlay atop the first view.

padding(_:) Pads this view using the edges and padding amount you specify.

padding(_:) Pads the view along all edges by the specified amount.

padding(_:_:) A view that pads this view inside the specified edge insets with a system-calculated amount of padding.

pickerStyle(_:) Sets the style for pickers within this view.

popover(isPresented:attachmentAnchor:arrowEdge:content:) Presents a popover when a given condition is true.

popover(item:attachmentAnchor:arrowEdge:content:) A view modifier that presents a popover using the given item as a data source for the popover's content.

position(_:) A view modifier that positions the center of this view at the specified point in its parent's coordinate space.

position(x:y:) A view modifier that positions the center of this view at the specified coordinates in its parent's coordinate space.

preference(key:value:) Sets a value for the given preference.

preferredColorScheme(_:) A view modifier that sets the preferred color scheme for this presentation.

previewContext(_:) A view modifier that declares a context for the Xcode preview.

previewDevice(_:) A view modifier that sets the device for a preview.

previewDisplayName(_:) A view modifier that sets a custom name in the Xcode preview.

previewLayout(_:) A view modifier that sets the size for a Xcode preview.

progressViewStyle(_:) Sets the style for progress views in this view.

projectionEffect(_:) Applies a projection transformation to this view's rendered output.

redacted(reason:) A view modifier that replaces content with a smart placeholder.

rotation3DEffect(_:axis:anchor:anchorZ:perspective:) Rotates this view's rendered output in three dimensions around the given axis of rotation.

rotationEffect(_:anchor:) A view modifier that rotates this view's rendered output around the specified point.

saturation(_:) A view modifier that adjusts the color saturation of the view.

scaledToFill() A view modifier that scales this view to fill its parent.

scaledToFit() A view modifier that scales this view to fit its parent.

scaleEffect(_:anchor:) A view modifier that this view's rendered output by the given amount in both the horizontal and vertical directions, relative to an anchor point.

scaleEffect(_:anchor:) A view modifier that scales this view's rendered output by the given vertical and horizontal size amounts, relative to an anchor point.

scaleEffect(x:y:anchor:) A view modifier that scales this view's rendered output by the given horizontal and vertical amounts, relative to an anchor point.

shadow(color:radius:x:y:) A view modifier that adds a shadow to this view.

sheet(isPresented:onDismiss:content:) A view modifier that presents a sheet when a given condition is true.

sheet(item:onDismiss:content:) A view modifier that presents a sheet when a given value is not nil.

simultaneousGesture(_:including:) A view modifier that connects a gesture to the view, with equal priority to existing gestures.

statusBar(hidden:) Sets the visibility of the status bar.

tabItem(_:) A view modifier that sets the tab bar item associated with this view.

tabViewStyle(_:) Sets the style for the tab view within the the current environment.

tag(_:) Sets the unique tag value of this view.

textCase(_:) A view modifier that sets a transform for the case of the text contained in this view when displayed.

textContentType(_:) A view modifier that 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.

textFieldStyle(_:) Sets the style for text fields within this view.

toggleStyle(_:) A view modifier that sets the style for toggles within this view.

toolbar(content:) Populates the toolbar or navigation bar.

toolbar(content:) Populates the toolbar or navigation bar with items whose content is the specified views.

toolbar(id:content:) Populates the toolbar or navigation bar.

transaction(_:) Use this modifier to change or replace the animation used in a view. Consider three identical animations controlled by a button that executes all three animations simultaneously:

transformAnchorPreference(key:value:transform:) Use this to transform the value of an existing anchor preference.

transformEffect(_:) A view modifier that applies an affine transformation to this view's rendered output.

transformEnvironment(_:transform:) Transforms the environment value of the specified key path with the given function.

transformPreference(_:_:) Applies a transformation to a preference value.

transition(_:) A view modifier that adds a transition to this view when it appears and disappears.

truncationMode(_:) A view modifier that sets the truncation mode for lines of text that are too long to fit in the available space.

unredacted() A view modifier that removes all redaction reasons from a view.

userActivity(_:element:_:) Advertises a user activity type.

userActivity(_:isActive:_:) Advertises a user activity type.

zIndex(_:) A view modifier that controls the display order of overlapping views.


Instance Property

body The content and behavior of the view.


Associated Type

Body The type of view representing the body of this view.