Generic Structure

Toggle

A control that toggles between on and off states.

Declaration

struct Toggle<Label> where Label : View

Overview

The appearance and interaction of Toggle is determined at runtime and can be customized. Toggle uses the ToggleStyle provided by its environment to define its appearance and interaction. Each platform provides a default style that reflects the platform style, but providing a new style will redefine all Toggle instances within that environment.

Topics

Creating a Toggle

init(ToggleStyleConfiguration)
init<S>(S, isOn: Binding<Bool>)
init(isOn: Binding<Bool>, label: () -> Label)

Creates an instance that displays state based on isOn.

Styling a Toggle

Implementing a Custom View

Sizing 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.

func layoutPriority(Double) -> View

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

Positioning 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.

func coordinateSpace<T>(name: T) -> View

Assigns a name to this view’s coordinate space to which descendants of this view can refer.

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.

Layering 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.

func mask<Mask>(Mask) -> View

Masks this view using the alpha channel of the given view.

Scaling Views

func scaledToFill() -> View

Scales the view to fill its parent.

func scaledToFit() -> View

Scales the view to fit its parent.

func scaleEffect(CGFloat, anchor: UnitPoint) -> View

Scales this view’s rendered output by the given amount in both the horizontal and vertical directions, relative to an anchor point.

func scaleEffect(CGSize, anchor: UnitPoint) -> View

Scales this view’s rendered output by the given vertical and horizontal size amounts, relative to an anchor point.

func scaleEffect(x: CGFloat, y: CGFloat, anchor: UnitPoint) -> View

Scales this view’s rendered output by the given horizontal and vertical amounts, relative to an anchor point.

func aspectRatio(CGFloat?, contentMode: ContentMode) -> View

Constrains the view’s dimensions to the specified aspect ratio.

func aspectRatio(CGSize, contentMode: ContentMode) -> View

Constrains the view’s dimensions to the aspect ratio of the specified size.

func imageScale(Image.Scale) -> View

Sets the scale of images inside the view.

Rotating and Transforming Views

func rotationEffect(Angle, anchor: UnitPoint) -> View

Rotates this view’s rendered output around the specified point.

func projectionEffect(ProjectionTransform) -> View

Applies a projection transformation to this view’s rendered output.

func transformEffect(CGAffineTransform) -> View

Applies an affine transformation to this view’s rendered output.

Adjusting Text in a View

func keyboardType(UIKeyboardType) -> View

Sets the keyboard type for this 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 textContentType(UITextContentType?) -> View

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.

func textContentType(WKTextContentType?) -> 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.

func flipsForRightToLeftLayoutDirection(Bool) -> View

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

func autocapitalization(UITextAutocapitalizationType) -> View

Sets whether to apply auto-capitalization to this view.

func disableAutocorrection(Bool?) -> View

Sets whether to disable autocorrection for this view.

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.

Handling View Taps and Gestures

func onTapGesture(count: Int, perform: () -> Void) -> View

Adds an action to perform when this view recognizes a tap gesture.

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 transaction((inout Transaction) -> Void) -> View

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

Handling View Events

func onAppear(perform: (() -> Void)?) -> View

Adds an action to perform when the view appears.

func onDisappear(perform: (() -> Void)?) -> View

Adds an action to perform when the view disappears.

func onCutCommand(perform: (() -> [NSItemProvider])?) -> View

Adds an action to perform in response to the system’s Cut command.

func onCopyCommand(perform: (() -> [NSItemProvider])?) -> View

Adds an action to perform in response to the system’s Copy command.

func onPasteCommand(of: [String], perform: ([NSItemProvider]) -> Void) -> View

Adds an action to perform in response to the system’s Paste command.

func onPasteCommand<Payload>(of: [String], validator: ([NSItemProvider]) -> Payload?, perform: (Payload) -> Void) -> View

Adds an action to perform in response to the system’s Paste command with items that you validate.

func onDeleteCommand(perform: (() -> Void)?) -> View

Adds an action to perform in response to the system’s Delete command.

func onMoveCommand(perform: ((MoveCommandDirection) -> Void)?) -> View

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.

func onExitCommand(perform: (() -> Void)?) -> View

Sets up an action that triggers in response to receiving the exit command while the view has focus.

func onPlayPauseCommand(perform: (() -> Void)?) -> View

Adds an action to perform in response to the system’s Play/Pause command.

func onCommand(Selector, perform: (() -> Void)?) -> View

Adds an action to perform in response to the given selector.

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.

Handling Publisher Events

func onReceive<P>(P, perform: (P.Output) -> Void) -> View

Adds an action to perform when this view detects data emitted by the given publisher.

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.

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

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

Setting View Colors

func foregroundColor(Color?) -> View

Sets the color that the view uses for foreground elements.

func accentColor(Color?) -> View

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

Adopting View Color Schemes

func colorScheme(ColorScheme) -> View

Sets the view’s color scheme.

func preferredColorScheme(ColorScheme?) -> View

Sets the preferred color scheme for this view.

Applying Graphical Effects to a View

func blur(radius: CGFloat, opaque: Bool) -> View

Applies a Gaussian blur to the 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 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.

Compositing Views

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.

Configuring Control Attributes

func labelsHidden() -> View

Hides the labels of any controls contained within this view.

func defaultWheelPickerItemHeight(CGFloat) -> View

Sets the default wheel-style picker item height.

func horizontalRadioGroupLayout() -> View

Sets the style for radio group style pickers within the view’s environment to be radio buttons horizontally arranged inside of the layout.

func controlSize(ControlSize) -> View

Sets the size class, like regular or small, for controls within this view.

Styling Views

func buttonStyle<S>(S) -> View

Sets the style for buttons within this view.

func buttonStyle<S>(S) -> View

Sets the style for buttons within this view.

func menuButtonStyle<S>(S) -> View

Sets the style for menu buttons within this view.

func pickerStyle<S>(S) -> View

Sets the style for pickers within this view.

func datePickerStyle<S>(S) -> View

Sets the style for date pickers within this view.

func textFieldStyle<S>(S) -> View

Sets the style for text fields within this view.

func toggleStyle<S>(S) -> View

Sets the style for toggles within this view.

func listStyle<S>(S) -> View

Sets the style for lists within this view.

func navigationViewStyle<S>(S) -> View

Sets the style for navigation views within this 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 Status Bar Views

func navigationBarTitle(Text) -> View

Configures the title in the navigation bar for the view.

func navigationBarTitle(LocalizedStringKey) -> View

Configures the title of this view's navigation bar with a localized string.

func navigationBarTitle<S>(S) -> View

Configures the title of this view’s navigation bar with a string.

func navigationBarTitle(LocalizedStringKey, displayMode: NavigationBarItem.TitleDisplayMode) -> View

Configures the title of this view's navigation bar with a localized string and a display mode.

func navigationBarHidden(Bool) -> View

Hides the navigation bar for the view.

func statusBar(hidden: Bool) -> View

Sets the visibility of the status bar for the view.

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.

func tabItem<V>(() -> V) -> View

Sets the tab bar item associated with this view.

Configuring Context Menu Views

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

Attaches a contextual menu and its children to the view.

Configuring Touch Bar Views

func touchBar<Content>(content: () -> Content) -> View

Sets the content that the Touch Bar displays.

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.

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.

Customizing Accessibility Navigation of a View

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

func allowsHitTesting(Bool) -> View

Configures whether this view participates in hit test operations.

func contentShape<S>(S, eoFill: Bool) -> View

Defines the content shape 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.

Implementing View Modifiers

Relationships

Conforms To

See Also

Value Selectors

struct Picker

A control for selecting from a set of mutually exclusive values.

struct DatePicker

A control for selecting an absolute date.

struct Slider

A control for selecting a value from a bounded linear range of values.

struct Stepper

A control used to perform semantic increment and decrement actions.