Protocol

View

A type that represents a SwiftUI view.

Declaration

protocol View

Overview

You create custom views by declaring types that conform to the View protocol. Implement the required body computed property to provide the content and behavior for your custom view.

Topics

Implementing a Custom View

var body: Self.Body

The content and behavior of the view.

Required. Default implementations provided.

Setting the Size of a View

func frame(width: CGFloat?, height: CGFloat?, alignment: Alignment) -> View

Positions the view within an invisible frame with the specified size.

func fixedSize() -> View

Fixes the view at its ideal size.

func fixedSize(horizontal: Bool, vertical: Bool) -> View

Fixes the view at its ideal size in the specified dimensions.

Specifying the Relative Size of a View

func layoutPriority(Double) -> View

Sets the priority by which a parent layout should apportion space to the child.

Setting the Position of a View

func position(CGPoint) -> View

Fixes the center of the view at the specified point in its parent’s coordinate space.

func position(x: CGFloat, y: CGFloat) -> View

Fixes the center of the view at the specified coordinates in its parent’s coordinate space.

func offset(CGSize) -> View

Offsets the view by the horizontal and vertical distances in the given size.

func offset(x: CGFloat, y: CGFloat) -> View

Offsets the view by the specified horizontal and vertical distances.

func edgesIgnoringSafeArea(Edge.Set) -> View

Extends the view out of the safe area on the specified edges.

struct ViewDimensions

A view’s size and its alignment guides in its own coordinate space.

Adjusting the Padding of a View

func padding(CGFloat) -> View

Pads the view along all edge insets by the specified amount.

func padding(EdgeInsets) -> View

Pads the view using the specified edge insets.

func padding(Edge.Set, CGFloat?) -> View

Pads the view using the specified edge insets.

Setting the Foreground or Background of a View

func overlay<Overlay>(Overlay, alignment: Alignment) -> View

Layers a secondary view in front of the view.

func foregroundColor(Color?) -> View

Sets the color that the view uses for foreground elements.

func zIndex(Double) -> View

Controls the display order of overlapping views.

Setting the Border of a View

func border<S>(S, width: CGFloat) -> View

Adds a border to the view with the specified style and width.

Masking and Clipping Views

func clipped(antialiased: Bool) -> View

Clips the view to its bounding rectangular frame.

func clipShape<S>(S, style: FillStyle) -> View

Sets a clipping shape for the view.

func cornerRadius(CGFloat, antialiased: Bool) -> View

Clips the view to its bounding frame, with the specified corner radius.

Scaling Views

Adjusting Text in a View

func font(Font?) -> View

Sets the default font for text in the view.

func lineLimit(Int?) -> View

Sets the maximum number of lines that text can occupy in the view.

func lineSpacing(CGFloat) -> View

Sets the amount of space between lines of text in the view.

func minimumScaleFactor(CGFloat) -> View

Sets the minimum amount that text scales down to fit the available space.

func truncationMode(Text.TruncationMode) -> View

Sets the truncation mode for lines of text that are too long to fit in the available space.

func allowsTightening(Bool) -> View

Sets whether text can compress the space between characters when necessary to fit text in a line.

func flipsForRightToLeftLayoutDirection(Bool) -> View

Sets whether the view flips its contents horizontally when the layout direction is right-to-left.

Adding Animations to a View

func animation(Animation?) -> View

Applies the given animation to all animatable values within the view.

func animation<V>(Animation?, value: V) -> View

Applies the given animation to the view when the specified value changes.

func transition(AnyTransition) -> View

Associates a transition with the view.

Customizing Accessibility Labels of a View

Creating Accessible Views

Make your app accessible to everyone by applying accessibility modifiers to your SwiftUI views.

func accessibility(value: Text) -> ModifiedContent<Self, AccessibilityAttachmentModifier>

Adds a textual description of the value that the view contains.

Accessibility Modifier Types

A set of types used to improve a view’s comprehensibility, interactivity, and navigability.

Handling View Taps and Gestures

func gesture<T>(T, including: GestureMask) -> View

Attaches a gesture to the view with a lower precedence than gestures defined by the view.

func highPriorityGesture<T>(T, including: GestureMask) -> View

Attaches a gesture to the view with a higher precedence than gestures defined by the view.

func simultaneousGesture<T>(T, including: GestureMask) -> View

Attaches a gesture to the view to process simultaneously with gestures defined by the view.

func digitalCrownRotation<V>(Binding<V>) -> View

Tracks Digital Crown rotations by updating the specified binding.

func itemProvider(Optional<() -> NSItemProvider?>) -> View

Provides a closure that vends the drag representation to be used for a particular data element.

func transaction((inout Transaction) -> Void) -> View

Applies the given transaction mutation function to all transactions used within the view.

Handling View Hover and Focus

func onHover(perform: (Bool) -> Void) -> View

Adds an action to perform when the user moves the pointer over or away from the view’s frame.

func focusable(Bool, onFocusChange: (Bool) -> Void) -> View

Specifies if the view is focusable and, if so, adds an action to perform when the view comes into focus.

Supporting Drag and Drop in Views

func onDrag(() -> NSItemProvider) -> View

Activates the view as the source of a drag and drop operation.

func onDrop(of: [String], delegate: DropDelegate) -> View

Defines the destination of a drag and drop operation with the same size and position as the view using behavior controlled by the given delegate.

func onDrop(of: [String], isTargeted: Binding<Bool>?, perform: ([NSItemProvider], CGPoint) -> Bool) -> View

Defines the destination of a drag and drop operation with the same size and position as the view by handling dropped content and the drop location with the specified closure.

func onDrop(of: [String], isTargeted: Binding<Bool>?, perform: ([NSItemProvider]) -> Bool) -> View

Defines the destination for a drag and drop operation with the same size and position as the view by handling dropped content with the specified closure.

struct DropInfo

The current state of a drop.

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.

protocol DropDelegate

An interface that you implement to interact with a drop operation in a view modified to accept drops.

Adopting View Color Schemes

func colorScheme(ColorScheme) -> View

Sets the view’s color scheme.

enum ColorScheme

The possible types of color schemes, like Dark Mode.

func accentColor(Color?) -> View

Sets the accent color for the view and the views it contains.

Applying Blurs and Shadows to a View

Applying Graphical Effects to a View

func opacity(Double) -> View

Sets the transparency of the view.

func brightness(Double) -> View

Brightens the view by the specified amount.

func contrast(Double) -> View

Sets the contrast and separation between similar colors in the view.

func colorInvert() -> View

Inverts the colors in the view.

func colorMultiply(Color) -> View

Adds a color multiplication effect to the view.

func blendMode(BlendMode) -> View

Sets the blend mode for compositing the view with overlapping views.

func compositingGroup() -> View

Wraps the view in a compositing group.

func drawingGroup(opaque: Bool, colorMode: ColorRenderingMode) -> View

Composites the view’s contents into an offscreen image before final display.

enum ColorRenderingMode

The working color space for color-compositing operations.

func saturation(Double) -> View

Adjusts the color saturation of the view.

func grayscale(Double) -> View

Adds a grayscale effect to the view.

func hueRotation(Angle) -> View

Applies a hue rotation effect to the view.

func luminanceToAlpha() -> View

Adds a luminance to alpha effect to the view.

Configuring a List View

func listRowInsets(EdgeInsets?) -> View

Sets the inset to be applied to the view when placed in a list.

func listRowBackground<V>(V?) -> View

Sets a view behind the view when placed in a list.

func listRowPlatterColor(Color?) -> View

Sets the color to apply to the system cell platter of the view when placed in a list.

func tag<V>(V) -> View

Sets a tag for the view in order to differentiate it from a list of view options.

Configuring Navigation and Tab Bar Item Views

func navigationBarBackButtonHidden(Bool) -> View

Hides the navigation bar back button for the view.

func navigationBarItems<L>(leading: L) -> View

Configures the navigation bar items for the view.

func navigationBarItems<L, T>(leading: L, trailing: T) -> View

Configures the navigation bar items for the view.

func navigationBarItems<T>(trailing: T) -> View

Configures the navigation bar items for the view.

struct NavigationBarItem

A configuration for a navigation bar that represents a view at the top of a navigation stack.

Configuring Context Menu Views

func contextMenu<MenuItems>(ContextMenu<MenuItems>?) -> View

Attaches a contextual menu and its children to the view.

struct ContextMenu

A container for views that you present as a menu items in a contextual menu in response to the standard system gesture.

Configuring Touch Bar Views

func touchBar<Content>(TouchBar<Content>) -> View

Sets the touch bar and its content to be shown in the Touch Bar when applicable.

func touchBarItemPrincipal(Bool) -> View

Sets the view as having special significance to the TouchBar.

func touchBarCustomizationLabel(Text) -> View

Sets a user-visible string identifying the view’s functionality.

func touchBarItemPresence(TouchBarItemPresence) -> View

Sets the behavior of the view when being customized by the user.

struct TouchBar

A container for a view that you can show in the Touch Bar.

Hiding and Disabling Views

func hidden() -> View

Hides the view.

func disabled(Bool) -> View

Adds a condition for whether users can interact with the view.

func deleteDisabled(Bool) -> View

Adds a condition for whether the view’s view hierarchy is deletable.

func moveDisabled(Bool) -> View

Adds a condition for whether the view's view hierarchy is movable.

Responding to View Preferences

func onPreferenceChange<K>(K.Type, perform: (K.Value) -> Void) -> View

Adds an action to perform when the specified preference key’s value changes.

func backgroundPreferenceValue<Key, T>(Key.Type, (Key.Value) -> T) -> View

Uses the specified preference value from the view to produce another view as a background to the first view.

func overlayPreferenceValue<Key, T>(Key.Type, (Key.Value) -> T) -> View

Uses the specified preference value from the view to produce another view as an overlay atop the first view.

Setting the Environment Values of a View

func environment<V>(WritableKeyPath<EnvironmentValues, V>, V) -> View

Sets the environment value indicated by a key path to the given value.

func transformEnvironment<V>(WritableKeyPath<EnvironmentValues, V>, transform: (inout V) -> Void) -> View

Transforms the environment value indicated by a key path with the given function.

Configuring a View for Hit Testing

Configuring View Previews

func previewDevice(PreviewDevice?) -> View

Overrides the device for a preview.

func previewDisplayName(String?) -> View

Provides a user visible name shown in the editor.

func previewLayout(PreviewLayout) -> View

Overrides the size of the container for the preview.

Inspecting Views

func id<ID>(ID) -> View

Generates a uniquely identified view that can be inserted or removed.

func equatable() -> EquatableView<Self>

Prevents the view from updating its child view when its new value is the same as its old value.

associatedtype Body

The type of view representing the body of the view.

Required.

Implementing View Modifiers

struct EmptyModifier

The empty, or identity, modifier.

See Also

Essentials

Creating and Combining Views

This tutorial guides you through building Landmarks — an iOS app for discovering and sharing the places you love. You’ll start by building the view that shows a landmark’s details.

Working with UI Controls

In the Landmarks app, users can create a profile to express their personality. To give users the ability to change their profile, you’ll add an edit mode and design the preferences screen.

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