Skip to content

Instantly share code, notes, and snippets.

@eneko
Created November 10, 2023 16:35
Show Gist options
  • Save eneko/1fc347ac2c6a055aba6b011791225e70 to your computer and use it in GitHub Desktop.
Save eneko/1fc347ac2c6a055aba6b011791225e70 to your computer and use it in GitHub Desktop.
SwiftUI public interface - Xcode 15.0 15A240d
This file has been truncated, but you can view the full file.
import Accessibility
import AppKit
import Combine
import CoreData
import CoreFoundation
import CoreGraphics
import CoreText
import CoreTransferable
import Darwin
import DeveloperToolsSupport
import Foundation
import OSLog
import Observation
import Symbols
import UniformTypeIdentifiers
import _Concurrency
import _StringProcessing
import _SwiftConcurrencyShims
import os
import os.log
import os.signpost
/// 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.
///
/// Note that you may use the `@Environment` property wrapper inside the
/// implementation of your `AXChartDescriptorRepresentable`, in which case you
/// should implement `updateChartDescriptor`, which will be called when the
/// `Environment` changes.
///
/// For example, to provide accessibility for a view that represents a chart,
/// you would first declare your chart descriptor representable type:
///
/// struct MyChartDescriptorRepresentable: AXChartDescriptorRepresentable {
/// func makeChartDescriptor() -> AXChartDescriptor {
/// // Build and return your `AXChartDescriptor` here.
/// }
///
/// func updateChartDescriptor(_ descriptor: AXChartDescriptor) {
/// // Update your chart descriptor with any new values.
/// }
/// }
///
/// Then, provide an instance of your `AXChartDescriptorRepresentable` type to
/// your view using the `accessibilityChartDescriptor` modifier:
///
/// var body: some View {
/// MyChartView()
/// .accessibilityChartDescriptor(MyChartDescriptorRepresentable())
/// }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public protocol AXChartDescriptorRepresentable {
/// Create the `AXChartDescriptor` for this view, and return it.
///
/// This will be called once per identity of your `View`. It will not be run
/// again unless the identity of your `View` changes. If you need to
/// update the `AXChartDescriptor` based on changes in your `View`, or in
/// the `Environment`, implement `updateChartDescriptor`.
/// This method will only be called if / when accessibility needs the
/// `AXChartDescriptor` of your view, for VoiceOver.
func makeChartDescriptor() -> AXChartDescriptor
/// Update the existing `AXChartDescriptor` for your view, based on changes
/// in your view or in the `Environment`.
///
/// This will be called as needed, when accessibility needs your
/// `AXChartDescriptor` for VoiceOver. It will only be called if the inputs
/// to your views, or a relevant part of the `Environment`, have changed.
func updateChartDescriptor(_ descriptor: AXChartDescriptor)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AXChartDescriptorRepresentable {
/// Update the existing `AXChartDescriptor` for your view, based on changes
/// in your view or in the `Environment`.
///
/// This will be called as needed, when accessibility needs your
/// `AXChartDescriptor` for VoiceOver. It will only be called if the inputs
/// to your views, or a relevant part of the `Environment`, have changed.
public func updateChartDescriptor(_ descriptor: AXChartDescriptor)
}
/// The structure that defines the kinds of available accessibility actions.
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct AccessibilityActionKind : Equatable, Sendable {
/// The value that represents the default accessibility action.
public static let `default`: AccessibilityActionKind
/// The value that represents an action that cancels a pending accessibility action.
public static let escape: AccessibilityActionKind
@available(macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public static let delete: AccessibilityActionKind
@available(macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public static let showMenu: AccessibilityActionKind
public init(named name: Text)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AccessibilityActionKind, b: AccessibilityActionKind) -> Bool
}
/// A directional indicator you use when making an accessibility adjustment.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum AccessibilityAdjustmentDirection : Sendable {
case increment
case decrement
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AccessibilityAdjustmentDirection, b: AccessibilityAdjustmentDirection) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AccessibilityAdjustmentDirection : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AccessibilityAdjustmentDirection : Hashable {
}
/// A view modifier that adds accessibility properties to the view
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct AccessibilityAttachmentModifier : ViewModifier {
/// The type of view representing the body.
public typealias Body = Never
}
/// Defines the behavior for the child elements of the new parent element.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct AccessibilityChildBehavior : Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: AccessibilityChildBehavior, rhs: AccessibilityChildBehavior) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AccessibilityChildBehavior {
/// Any child accessibility elements become hidden.
///
/// Use this behavior when you want a view represented by
/// a single accessibility element. The new accessibility element
/// has no initial properties. So you will need to use other
/// accessibility modifiers, such as ``View/accessibilityLabel(_:)-5f0zj``,
/// to begin making it accessible.
///
/// var body: some View {
/// VStack {
/// Button("Previous Page", action: goBack)
/// Text("\(pageNumber)")
/// Button("Next Page", action: goForward)
/// }
/// .accessibilityElement(children: .ignore)
/// .accessibilityValue("Page \(pageNumber) of \(pages.count)")
/// .accessibilityAdjustableAction { action in
/// if action == .increment {
/// goForward()
/// } else {
/// goBack()
/// }
/// }
/// }
///
/// Before using the ``AccessibilityChildBehavior/ignore``behavior, consider
/// using the ``AccessibilityChildBehavior/combine`` behavior.
///
/// - Note: A new accessibility element is always created.
public static let ignore: AccessibilityChildBehavior
/// Any child accessibility elements become children of the new
/// accessibility element.
///
/// Use this behavior when you want a view to be an accessibility
/// container. An accessibility container groups child accessibility
/// elements which improves navigation. For example, all children
/// of an accessibility container are navigated in order before
/// navigating through the next accessibility container.
///
/// var body: some View {
/// ScrollView {
/// VStack {
/// HStack {
/// ForEach(users) { user in
/// UserCell(user)
/// }
/// }
/// .accessibilityElement(children: .contain)
/// .accessibilityLabel("Users")
///
/// VStack {
/// ForEach(messages) { message in
/// MessageCell(message)
/// }
/// }
/// .accessibilityElement(children: .contain)
/// .accessibilityLabel("Messages")
/// }
/// }
/// }
///
/// A new accessibility element is created when:
/// * The view contains multiple or zero accessibility elements
/// * The view contains a single accessibility element with no children
///
/// - Note: If an accessibility element is not created, the
/// ``AccessibilityChildBehavior`` of the existing
/// accessibility element is modified.
public static let contain: AccessibilityChildBehavior
/// Any child accessibility element's properties are merged
/// into the new accessibility element.
///
/// Use this behavior when you want a view represented by
/// a single accessibility element. The new accessibility element
/// merges properties from all non-hidden children. Some
/// properties may be transformed or ignored to achieve the
/// ideal combined result. For example, not all of ``AccessibilityTraits``
/// are merged and a ``AccessibilityActionKind/default`` action
/// may become a named action (``AccessibilityActionKind/init(named:)``).
///
/// struct UserCell: View {
/// var user: User
///
/// var body: some View {
/// VStack {
/// Image(user.image)
/// Text(user.name)
/// Button("Options", action: showOptions)
/// }
/// .accessibilityElement(children: .combine)
/// }
/// }
///
/// A new accessibility element is created when:
/// * The view contains multiple or zero accessibility elements
/// * The view wraps a ``UIViewRepresentable``/``NSViewRepresentable``.
///
/// - Note: If an accessibility element is not created, the
/// ``AccessibilityChildBehavior`` of the existing
/// accessibility element is modified.
public static let combine: AccessibilityChildBehavior
}
/// Key used to specify the identifier and label associated with
/// an entry of additional accessibility information.
///
/// Use `AccessibilityCustomContentKey` and the associated modifiers taking
/// this value as a parameter in order to simplify clearing or replacing
/// entries of additional information that are manipulated from multiple places
/// in your code.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AccessibilityCustomContentKey {
/// Create an `AccessibilityCustomContentKey` with the specified label and
/// identifier.
///
/// - Parameter label: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation".
/// - Parameter id: String used to identify the additional information entry
/// to SwiftUI. Adding an entry will replace any previous value with the
/// same identifier.
public init(_ label: Text, id: String)
/// Create an `AccessibilityCustomContentKey` with the specified label and
/// identifier.
///
/// - Parameter labelKey: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation".
/// - Parameter id: String used to identify the additional
/// information entry to SwiftUI. Adding an entry will replace any previous
/// value with the same identifier.
public init(_ labelKey: LocalizedStringKey, id: String)
/// Create an `AccessibilityCustomContentKey` with the specified label.
///
/// - Parameter labelKey: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation". This will also be used as the identifier.
public init(_ labelKey: LocalizedStringKey)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityCustomContentKey : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AccessibilityCustomContentKey, b: AccessibilityCustomContentKey) -> Bool
}
/// An option set that defines the functionality of a view's direct touch area.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct AccessibilityDirectTouchOptions : OptionSet, Sendable {
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = UInt
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public let rawValue: AccessibilityDirectTouchOptions.RawValue
/// Create a set of direct touch options
public init(rawValue: AccessibilityDirectTouchOptions.RawValue)
/// Allows a direct touch area to immediately receive touch events without
/// an assitive technology, such as VoiceOver, speaking. Appropriate for
/// apps that provide direct audio feedback on touch that would conflict
/// with speech feedback.
public static let silentOnTouch: AccessibilityDirectTouchOptions
/// Prevents touch passthrough with the direct touch area until an
/// assistive technology, such as VoiceOver, has activated the direct
/// touch area through a user action, for example a double tap.
public static let requiresActivation: AccessibilityDirectTouchOptions
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = AccessibilityDirectTouchOptions
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = AccessibilityDirectTouchOptions
}
/// 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.
///
/// Use this capability to request that VoiceOver or other accessibility
/// technologies programmatically focus on a specific element, or to determine
/// whether VoiceOver or other accessibility technologies are focused on
/// particular elements. Use ``View/accessibilityFocused(_:equals:)`` or
/// ``View/accessibilityFocused(_:)`` in conjunction with this property
/// wrapper to identify accessibility elements for which you want to get
/// or set accessibility focus. When accessibility focus enters the modified accessibility element,
/// the framework updates the wrapped value of this property to match a given
/// prototype value. When accessibility focus leaves, SwiftUI resets the wrapped value
/// of an optional property to `nil` or the wrapped value of a Boolean property to `false`.
/// Setting the property's value programmatically has the reverse effect, causing
/// accessibility focus to move to whichever accessibility element is associated with the updated value.
///
/// In the example below, when `notification` changes, and its `isPriority` property
/// is `true`, the accessibility focus moves to the notification `Text` element above the rest of the
/// view's content:
///
/// struct CustomNotification: Equatable {
/// var text: String
/// var isPriority: Bool
/// }
///
/// struct ContentView: View {
/// @Binding var notification: CustomNotification?
/// @AccessibilityFocusState var isNotificationFocused: Bool
///
/// var body: some View {
/// VStack {
/// if let notification = self.notification {
/// Text(notification.text)
/// .accessibilityFocused($isNotificationFocused)
/// }
/// Text("The main content for this view.")
/// }
/// .onChange(of: notification) { notification in
/// if (notification?.isPriority == true) {
/// isNotificationFocused = true
/// }
/// }
///
/// }
/// }
///
/// To allow for cases where accessibility focus is completely absent from the
/// tree of accessibility elements, or accessibility technologies are not
/// active, the wrapped value must be either optional or Boolean.
///
/// Some initializers of `AccessibilityFocusState` also allow specifying
/// accessibility technologies, determining to which types of accessibility
/// focus this binding applies. If you specify no accessibility technologies,
/// SwiftUI uses an aggregate of any and all active accessibility technologies.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@propertyWrapper @frozen public struct AccessibilityFocusState<Value> : DynamicProperty where Value : Hashable {
@propertyWrapper @frozen public struct Binding {
/// The underlying value referenced by the bound property.
public var wrappedValue: Value { get nonmutating set }
/// The currently focused element.
public var projectedValue: AccessibilityFocusState<Value>.Binding { get }
}
/// The current state value, taking into account whatever bindings might be
/// in effect due to the current location of focus.
///
/// When focus is not in any view that is bound to this state, the wrapped
/// value will be `nil` (for optional-typed state) or `false` (for `Bool`-
/// typed state).
public var wrappedValue: Value { get nonmutating set }
/// A projection of the state value that can be used to establish bindings between view content
/// and accessibility focus placement.
///
/// Use `projectedValue` in conjunction with
/// ``SwiftUI/View/accessibilityFocused(_:equals:)`` to establish
/// bindings between view content and accessibility focus placement.
public var projectedValue: AccessibilityFocusState<Value>.Binding { get }
/// Creates a new accessibility focus state for a Boolean value.
public init() where Value == Bool
/// Creates a new accessibility focus state for a Boolean value, using the accessibility
/// technologies you specify.
///
/// - Parameters:
/// - technologies: One of the available ``AccessibilityTechnologies``.
public init(for technologies: AccessibilityTechnologies) where Value == Bool
/// Creates a new accessibility focus state of the type you provide.
public init<T>() where Value == T?, T : Hashable
/// Creates a new accessibility focus state of the type and
/// using the accessibility technologies you specify.
///
/// - Parameter technologies: One or more of the available
/// ``AccessibilityTechnologies``.
public init<T>(for technologies: AccessibilityTechnologies) where Value == T?, T : Hashable
}
/// The hierarchy of a heading in relation other headings.
///
/// Assistive technologies can use this to improve a users navigation
/// through multiple headings. When users navigate through top level
/// headings they expect the content for each heading to be unrelated.
///
/// For example, you can categorize a list of available products into sections,
/// like Fruits and Vegetables. With only top level headings, this list requires no
/// heading hierarchy, and you use the ``unspecified`` heading level. On the other hand, if sections
/// contain subsections, like if the Fruits section has subsections for varieties of Apples,
/// Pears, and so on, you apply the ``h1`` level to Fruits and Vegetables, and the ``h2``
/// level to Apples and Pears.
///
/// Except for ``h1``, be sure to precede all leveled headings by another heading with a level
/// that's one less.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public enum AccessibilityHeadingLevel : UInt {
/// A heading without a hierarchy.
case unspecified
/// Level 1 heading.
case h1
/// Level 2 heading.
case h2
/// Level 3 heading.
case h3
/// Level 4 heading.
case h4
/// Level 5 heading.
case h5
/// Level 6 heading.
case h6
/// Creates a new instance with the specified raw value.
///
/// If there is no value of the type that corresponds with the specified raw
/// value, this initializer returns `nil`. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// print(PaperSize(rawValue: "Legal"))
/// // Prints "Optional("PaperSize.Legal")"
///
/// print(PaperSize(rawValue: "Tabloid"))
/// // Prints "nil"
///
/// - Parameter rawValue: The raw value to use for the new instance.
public init?(rawValue: UInt)
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = UInt
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public var rawValue: UInt { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityHeadingLevel : Equatable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityHeadingLevel : Hashable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityHeadingLevel : RawRepresentable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityHeadingLevel : Sendable {
}
/// The role of an accessibility element in a label / content pair.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@frozen public enum AccessibilityLabeledPairRole {
/// This element represents the label part of the label / content pair.
///
/// For example, it might be the explanatory text to the left of a control,
/// describing what the control does.
case label
/// This element represents the content part of the label / content pair.
///
/// For example, it might be the custom control itself.
case content
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AccessibilityLabeledPairRole, b: AccessibilityLabeledPairRole) -> Bool
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension AccessibilityLabeledPairRole : Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension AccessibilityLabeledPairRole : Sendable {
}
/// Content within an accessibility rotor.
///
/// Generally generated from control flow constructs like `ForEach` and `if`, and
/// `AccessibilityRotorEntry`.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public protocol AccessibilityRotorContent {
/// The type for the internal content of this `AccessibilityRotorContent`.
associatedtype Body : AccessibilityRotorContent
/// The internal content of this `AccessibilityRotorContent`.
@AccessibilityRotorContentBuilder var body: Self.Body { get }
}
/// Result builder you use to generate rotor entry content.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@resultBuilder public struct AccessibilityRotorContentBuilder {
/// Builds an expression within the builder.
public static func buildExpression<Content>(_ content: Content) -> Content where Content : AccessibilityRotorContent
public static func buildBlock<Content>(_ content: Content) -> some AccessibilityRotorContent where Content : AccessibilityRotorContent
public static func buildIf<Content>(_ content: Content?) -> some AccessibilityRotorContent where Content : AccessibilityRotorContent
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1, C2>(_ c0: C0, _ c1: C1, _ c2: C2) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent, C2 : AccessibilityRotorContent
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1, C2, C3>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent, C2 : AccessibilityRotorContent, C3 : AccessibilityRotorContent
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1, C2, C3, C4>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent, C2 : AccessibilityRotorContent, C3 : AccessibilityRotorContent, C4 : AccessibilityRotorContent
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent, C2 : AccessibilityRotorContent, C3 : AccessibilityRotorContent, C4 : AccessibilityRotorContent, C5 : AccessibilityRotorContent
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5, C6>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent, C2 : AccessibilityRotorContent, C3 : AccessibilityRotorContent, C4 : AccessibilityRotorContent, C5 : AccessibilityRotorContent, C6 : AccessibilityRotorContent
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5, C6, C7>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6, _ c7: C7) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent, C2 : AccessibilityRotorContent, C3 : AccessibilityRotorContent, C4 : AccessibilityRotorContent, C5 : AccessibilityRotorContent, C6 : AccessibilityRotorContent, C7 : AccessibilityRotorContent
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5, C6, C7, C8>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6, _ c7: C7, _ c8: C8) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent, C2 : AccessibilityRotorContent, C3 : AccessibilityRotorContent, C4 : AccessibilityRotorContent, C5 : AccessibilityRotorContent, C6 : AccessibilityRotorContent, C7 : AccessibilityRotorContent, C8 : AccessibilityRotorContent
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5, C6, C7, C8, C9>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6, _ c7: C7, _ c8: C8, _ c9: C9) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent, C2 : AccessibilityRotorContent, C3 : AccessibilityRotorContent, C4 : AccessibilityRotorContent, C5 : AccessibilityRotorContent, C6 : AccessibilityRotorContent, C7 : AccessibilityRotorContent, C8 : AccessibilityRotorContent, C9 : AccessibilityRotorContent
}
/// A struct representing an entry in an Accessibility Rotor.
///
/// An Accessibility Rotor is a shortcut for Accessibility users to
/// quickly navigate to specific elements of the user interface,
/// and optionally specific ranges of text within those elements.
///
/// An entry in a Rotor may contain a label to identify the entry to the user,
/// and identifier used to determine which Accessibility element the Rotor entry
/// should navigate to, as well as an optional range used for entries that
/// navigate to a specific position in the text of their associated
/// Accessibility element. An entry can also specify a handler to be
/// called before the entry is navigated to, to do any manual work needed to
/// bring the Accessibility element on-screen.
///
/// In the following example, a Message application creates a Rotor
/// allowing users to navigate to specifically the messages originating from
/// VIPs.
///
/// // `messages` is a list of `Identifiable` `Message`s.
///
/// ScrollView {
/// LazyVStack {
/// ForEach(messages) { message in
/// MessageView(message)
/// }
/// }
/// }
/// .accessibilityElement(children: .contain)
/// .accessibilityRotor("VIPs") {
/// // Not all the `MessageView`s are generated at once, but the model
/// // knows about all the messages.
/// ForEach(messages) { message in
/// // If the Message is from a VIP, make a Rotor entry for it.
/// if message.isVIP {
/// AccessibilityRotorEntry(message.subject, id: message.id)
/// }
/// }
/// }
///
/// An entry may also be created using an optional namespace, for situations
/// where there are multiple Accessibility elements within a ForEach iteration
/// or where a `ScrollView` is not present. In this case, the `prepare` closure
/// may be needed in order to scroll the element into position using
/// `ScrollViewReader`. The same namespace should be passed to calls to
/// `accessibilityRotorEntry(id:in:)` to tag the Accessibility elements
/// associated with this entry.
///
/// In the following example, a Message application creates a Rotor
/// allowing users to navigate to specifically the messages originating from
/// VIPs. The Rotor entries are associated with the content text of the message,
/// which is one of the two views within the ForEach that generate Accessibility
/// elements. That view is tagged with `accessibilityRotorEntry(id:in:)` so that
/// it can be found by the `AccessibilityRotorEntry`, and `ScrollViewReader` is
/// used with the `prepare` closure to scroll it into position.
///
/// struct MessageListView: View {
/// @Namespace var namespace
///
/// var body: some View {
/// ScrollViewReader { scroller in
/// ScrollView {
/// LazyVStack {
/// ForEach(allMessages) { message in
/// VStack {
/// Text(message.subject)
/// // Tag this `Text` as an element associated
/// // with a Rotor entry.
/// Text(message.content)
/// .accessibilityRotorEntry(
/// "\(message.id)_content",
/// in: namespace
/// )
/// }
/// }
/// }
/// }
/// .accessibilityElement(children: .contain)
/// .accessibilityRotor("VIP Messages") {
/// ForEach(vipMessages) { vipMessage in
/// // The Rotor entry points to a specific ID we
/// // defined within a given `ForEach` iteration,
/// // not to the entire `ForEach` iteration.
/// AccessibilityRotorEntry(vipMessage.subject,
/// id: "\(vipMessage.id)_content", in: namespace)
/// {
/// // But the ID we give to `ScrollViewReader`
/// // matches the one used in the `ForEach`, which
/// // is the identifier for the whole iteration
/// // and what `ScrollViewReader` requires.
/// scroller.scrollTo(vipMessage.id)
/// }
/// }
/// }
/// }
/// }
/// }
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AccessibilityRotorEntry<ID> where ID : Hashable {
/// Create a Rotor entry with a specific label and identifier, with an
/// optional range.
/// - Parameters:
/// - label: Localized string used to show this Rotor entry
/// to users.
/// - id: Used to find the UI element associated with this
/// Rotor entry. This identifier should be used within a `scrollView`,
/// either in a `ForEach` or using an `id` call.
/// - textRange: Optional range of text associated with this Rotor
/// entry. This should be a range within text that is set as the
/// either label or accessibility value of the associated element.
/// - prepare: Optional closure to run before a Rotor entry
/// is navigated to, to prepare the UI as needed. This can be used to
/// bring the UI element on-screen if it isn't already, and SwiftUI
/// is not able to automatically scroll to it.
public init(_ label: Text, id: ID, textRange: Range<String.Index>? = nil, prepare: @escaping (() -> Void) = {})
/// Create a Rotor entry with a specific label, identifier and namespace,
/// and with an optional range.
/// - Parameters:
/// - label: Localized string used to show this Rotor entry
/// to users.
/// - id: Used to find the UI element associated with this
/// Rotor entry. This identifier and namespace should match a call to
/// `accessibilityRotorEntry(id:in)`.
/// - namespace: Namespace for this identifier. Should match a call
/// to `accessibilityRotorEntry(id:in)`.
/// - textRange: Optional range of text associated with this Rotor
/// entry. This should be a range within text that is set as the
/// accessibility label or accessibility value of the associated
/// element.
/// - prepare: Optional closure to run before a Rotor entry
/// is navigated to, to prepare the UI as needed. This should be used to
/// bring the Accessibility element on-screen, if scrolling is needed to
/// get to it.
public init(_ label: Text, id: ID, in namespace: Namespace.ID, textRange: Range<String.Index>? = nil, prepare: @escaping (() -> Void) = {})
/// Create a Rotor entry with a specific label and range. This Rotor entry
/// will be associated with the Accessibility element that owns the Rotor.
/// - Parameters:
/// - label: Optional localized string used to show this Rotor entry
/// to users. If no label is specified, the Rotor entry will be labeled
/// based on the text at that range.
/// - range: Range of text associated with this Rotor
/// entry.
/// - prepare: Optional closure to run before a Rotor entry
/// is navigated to, to prepare the UI as needed. This can be used to
/// bring the UI element or text on-screen if it isn't already,
/// and SwiftUI not able to automatically scroll to it.
public init(_ label: Text? = nil, textRange: Range<String.Index>, prepare: @escaping (() -> Void) = {}) where ID == Never
/// Create a Rotor entry with a specific label and identifier, with an
/// optional range.
/// - Parameters:
/// - id: Used to find the UI element associated with this
/// Rotor entry. This identifier should be used within a `scrollView`,
/// either in a `ForEach` or using an `id` call.
/// - label: Localized string used to show this Rotor entry
/// to users.
/// - textRange: Optional range of text associated with this Rotor
/// entry. This should be a range within text that is set as the
/// accessibility label or accessibility value of the associated
/// element.
/// - prepare: Optional closure to run before a Rotor entry
/// is navigated to, to prepare the UI as needed. This can be used to
/// bring the UI element on-screen if it isn't already, and SwiftUI
/// is not able to automatically scroll to it.
public init(_ labelKey: LocalizedStringKey, id: ID, textRange: Range<String.Index>? = nil, prepare: @escaping (() -> Void) = {})
/// Create a Rotor entry with a specific label and identifier, with an
/// optional range.
/// - Parameters:
/// - label: Localized string used to show this Rotor entry
/// to users.
/// - id: Used to find the UI element associated with this
/// Rotor entry. This identifier should be used within a `scrollView`,
/// either in a `ForEach` or using an `id` call.
/// - textRange: Optional range of text associated with this Rotor
/// entry. This should be a range within text that is set as the
/// accessibility label or accessibility value of the associated
/// element.
/// - prepare: Optional closure to run before a Rotor entry
/// is navigated to, to prepare the UI as needed. This can be used to
/// bring the UI element on-screen if it isn't already, and SwiftUI
/// is not able to automatically scroll to it.
public init<L>(_ label: L, id: ID, textRange: Range<String.Index>? = nil, prepare: @escaping (() -> Void) = {}) where L : StringProtocol
/// Create a Rotor entry with a specific label, identifier and namespace,
/// and with an optional range.
/// - Parameters:
/// - labelKey: Localized string used to show this Rotor entry
/// to users.
/// - id: Used to find the UI element associated with this
/// Rotor entry. This identifier and namespace should match a call to
/// `accessibilityRotorEntry(id:in)`.
/// - namespace: Namespace for this identifier. Should match a call
/// to `accessibilityRotorEntry(id:in)`.
/// - textRange: Optional range of text associated with this Rotor
/// entry. This should be a range within text that is set as the
/// accessibility label or accessibility value of the associated
/// element.
/// - prepare: Optional closure to run before a Rotor entry
/// is navigated to, to prepare the UI as needed. This should be used to
/// bring the Accessibility element on-screen, if scrolling is needed to
/// get to it.
public init(_ labelKey: LocalizedStringKey, id: ID, in namespace: Namespace.ID, textRange: Range<String.Index>? = nil, prepare: @escaping (() -> Void) = {})
/// Create a Rotor entry with a specific label, identifier and namespace,
/// and with an optional range.
/// - Parameters:
/// - label: Localized string used to show this Rotor entry
/// to users.
/// - id: Used to find the UI element associated with this
/// Rotor entry. This identifier and namespace should match a call to
/// `accessibilityRotorEntry(id:in)`.
/// - namespace: Namespace for this identifier. Should match a call
/// to `accessibilityRotorEntry(id:in)`.
/// - textRange: Optional range of text associated with this Rotor
/// entry. This should be a range within text that is set as the
/// accessibility label or accessibility value of the associated
/// element.
/// - prepare: Optional closure to run before a Rotor entry
/// is navigated to, to prepare the UI as needed. This should be used to
/// bring the Accessibility element on-screen, if scrolling is needed to
/// get to it.
public init<L>(_ label: L, _ id: ID, in namespace: Namespace.ID, textRange: Range<String.Index>? = nil, prepare: @escaping (() -> Void) = {}) where L : StringProtocol
/// Create a Rotor entry with a specific label and range. This Rotor entry
/// will be associated with the Accessibility element that owns the Rotor.
/// - Parameters:
/// - labelKey: Localized string used to show this Rotor entry
/// to users. If no label is specified, the Rotor entry will be labeled
/// based on the text at that range.
/// - range: Range of text associated with this Rotor
/// entry.
/// - prepare: Optional closure to run before a Rotor entry
/// is navigated to, to prepare the UI as needed. This can be used to
/// bring the UI element or text on-screen if it isn't already,
/// and SwiftUI not able to automatically scroll to it.
public init(_ labelKey: LocalizedStringKey, textRange: Range<String.Index>, prepare: @escaping (() -> Void) = {})
/// Create a Rotor entry with a specific label and range. This Rotor entry
/// will be associated with the Accessibility element that owns the Rotor.
/// - Parameters:
/// - label: Localized string used to show this Rotor entry
/// to users. If no label is specified, the Rotor entry will be labeled
/// based on the text at that range.
/// - range: Range of text associated with this Rotor
/// entry.
/// - prepare: Optional closure to run before a Rotor entry
/// is navigated to, to prepare the UI as needed. This can be used to
/// bring the UI element or text on-screen if it isn't already,
/// and SwiftUI not able to automatically scroll to it.
public init<L>(_ label: L, textRange: Range<String.Index>, prepare: @escaping (() -> Void) = {}) where ID == Never, L : StringProtocol
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityRotorEntry : AccessibilityRotorContent {
/// The internal content of this `AccessibilityRotorContent`.
public var body: Never { get }
/// The type for the internal content of this `AccessibilityRotorContent`.
public typealias Body = Never
}
/// Designates a Rotor that replaces one of the automatic, system-provided
/// Rotors with a developer-provided Rotor.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AccessibilitySystemRotor : Sendable {
/// System Rotors allowing users to iterate through links or visited links.
public static func links(visited: Bool) -> AccessibilitySystemRotor
/// System Rotor allowing users to iterate through all links.
public static var links: AccessibilitySystemRotor { get }
/// System Rotors allowing users to iterate through all headings, of various
/// heading levels.
public static func headings(level: AccessibilityHeadingLevel) -> AccessibilitySystemRotor
/// System Rotor allowing users to iterate through all headings.
public static var headings: AccessibilitySystemRotor { get }
/// System Rotor allowing users to iterate through all the ranges of
/// bolded text.
public static var boldText: AccessibilitySystemRotor { get }
/// System Rotor allowing users to iterate through all the ranges of
/// italicized text.
public static var italicText: AccessibilitySystemRotor { get }
/// System Rotor allowing users to iterate through all the ranges of
/// underlined text.
public static var underlineText: AccessibilitySystemRotor { get }
/// System Rotor allowing users to iterate through all the ranges of
/// mis-spelled words.
public static var misspelledWords: AccessibilitySystemRotor { get }
/// System Rotor allowing users to iterate through all images.
public static var images: AccessibilitySystemRotor { get }
/// System Rotor allowing users to iterate through all text fields.
public static var textFields: AccessibilitySystemRotor { get }
/// System Rotor allowing users to iterate through all tables.
public static var tables: AccessibilitySystemRotor { get }
/// System Rotor allowing users to iterate through all lists.
public static var lists: AccessibilitySystemRotor { get }
/// System Rotor allowing users to iterate through all landmarks.
public static var landmarks: AccessibilitySystemRotor { get }
}
/// Accessibility technologies available to the system.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AccessibilityTechnologies : SetAlgebra, Sendable {
/// The value that represents the VoiceOver screen reader, allowing use
/// of the system without seeing the screen visually.
public static var voiceOver: AccessibilityTechnologies
/// The value that represents a Switch Control, allowing the use of the
/// entire system using controller buttons, a breath-controlled switch or similar hardware.
public static var switchControl: AccessibilityTechnologies
/// Creates a new accessibility technologies structure with an empy accessibility technology set.
public init()
/// Returns a new set with the elements of both this and the given set.
///
/// In the following example, the `attendeesAndVisitors` set is made up
/// of the elements of the `attendees` and `visitors` sets:
///
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors = ["Marcia", "Nathaniel"]
/// let attendeesAndVisitors = attendees.union(visitors)
/// print(attendeesAndVisitors)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept.
///
/// let initialIndices = Set(0..<5)
/// let expandedIndices = initialIndices.union([2, 3, 6, 7])
/// print(expandedIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set with the unique elements of this set and `other`.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
public func union(_ other: AccessibilityTechnologies) -> AccessibilityTechnologies
/// Adds the elements of the given set to the set.
///
/// In the following example, the elements of the `visitors` set are added to
/// the `attendees` set:
///
/// var attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors: Set = ["Diana", "Marcia", "Nathaniel"]
/// attendees.formUnion(visitors)
/// print(attendees)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept.
///
/// var initialIndices = Set(0..<5)
/// initialIndices.formUnion([2, 3, 6, 7])
/// print(initialIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
public mutating func formUnion(_ other: AccessibilityTechnologies)
/// Returns a new set with the elements that are common to both this set and
/// the given set.
///
/// In the following example, the `bothNeighborsAndEmployees` set is made up
/// of the elements that are in *both* the `employees` and `neighbors` sets.
/// Elements that are in only one or the other are left out of the result of
/// the intersection.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
public func intersection(_ other: AccessibilityTechnologies) -> AccessibilityTechnologies
/// Removes the elements of this set that aren't also in the given set.
///
/// In the following example, the elements of the `employees` set that are
/// not also members of the `neighbors` set are removed. In particular, the
/// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formIntersection(neighbors)
/// print(employees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
public mutating func formIntersection(_ other: AccessibilityTechnologies)
/// Returns a new set with the elements that are either in this set or in the
/// given set, but not in both.
///
/// In the following example, the `eitherNeighborsOrEmployees` set is made up
/// of the elements of the `employees` and `neighbors` sets that are not in
/// both `employees` *and* `neighbors`. In particular, the names `"Bethany"`
/// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`.
///
/// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani"]
/// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)
/// print(eitherNeighborsOrEmployees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
public func symmetricDifference(_ other: AccessibilityTechnologies) -> AccessibilityTechnologies
/// Removes the elements of the set that are also in the given set and adds
/// the members of the given set that are not already in the set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of `neighbors` are removed from `employees`, while the
/// elements of `neighbors` that are not members of `employees` are added to
/// `employees`. In particular, the names `"Bethany"` and `"Eric"` are
/// removed from `employees` while the name `"Forlani"` is added.
///
/// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani"]
/// employees.formSymmetricDifference(neighbors)
/// print(employees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A set of the same type.
public mutating func formSymmetricDifference(_ other: AccessibilityTechnologies)
/// Returns a Boolean value that indicates whether the given element exists
/// in the set.
///
/// This example uses the `contains(_:)` method to test whether an integer is
/// a member of a set of prime numbers.
///
/// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
/// let x = 5
/// if primes.contains(x) {
/// print("\(x) is prime!")
/// } else {
/// print("\(x). Not prime.")
/// }
/// // Prints "5 is prime!"
///
/// - Parameter member: An element to look for in the set.
/// - Returns: `true` if `member` exists in the set; otherwise, `false`.
public func contains(_ member: AccessibilityTechnologies) -> Bool
/// Inserts the given element in the set if it is not already present.
///
/// If an element equal to `newMember` is already contained in the set, this
/// method has no effect. In this example, a new element is inserted into
/// `classDays`, a set of days of the week. When an existing element is
/// inserted, the `classDays` set does not change.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
/// print(classDays.insert(.monday))
/// // Prints "(true, .monday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// print(classDays.insert(.friday))
/// // Prints "(false, .friday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: `(true, newMember)` if `newMember` was not contained in the
/// set. If an element equal to `newMember` was already contained in the
/// set, the method returns `(false, oldMember)`, where `oldMember` is the
/// element that was equal to `newMember`. In some cases, `oldMember` may
/// be distinguishable from `newMember` by identity comparison or some
/// other means.
public mutating func insert(_ newMember: AccessibilityTechnologies) -> (inserted: Bool, memberAfterInsert: AccessibilityTechnologies)
/// Removes the given element and any elements subsumed by the given element.
///
/// - Parameter member: The element of the set to remove.
/// - Returns: For ordinary sets, an element equal to `member` if `member` is
/// contained in the set; otherwise, `nil`. In some cases, a returned
/// element may be distinguishable from `member` by identity comparison
/// or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the set
/// and `[member]`, or `nil` if the intersection is empty.
public mutating func remove(_ member: AccessibilityTechnologies) -> AccessibilityTechnologies?
/// Inserts the given element into the set unconditionally.
///
/// If an element equal to `newMember` is already contained in the set,
/// `newMember` replaces the existing element. In this example, an existing
/// element is inserted into `classDays`, a set of days of the week.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]
/// print(classDays.update(with: .monday))
/// // Prints "Optional(.monday)"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: For ordinary sets, an element equal to `newMember` if the set
/// already contained such a member; otherwise, `nil`. In some cases, the
/// returned element may be distinguishable from `newMember` by identity
/// comparison or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the
/// set and `[newMember]`, or `nil` if the intersection is empty.
public mutating func update(with newMember: AccessibilityTechnologies) -> AccessibilityTechnologies?
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AccessibilityTechnologies, b: AccessibilityTechnologies) -> Bool
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = AccessibilityTechnologies
/// A type for which the conforming type provides a containment test.
public typealias Element = AccessibilityTechnologies
}
/// Textual context that assistive technologies can use to improve the
/// presentation of spoken text.
///
/// Use an `AccessibilityTextContentType` value when setting the accessibility text content
/// type of a view using the ``View/accessibilityTextContentType(_:)`` modifier.
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AccessibilityTextContentType : Sendable {
/// A type that represents generic text that has no specific type.
public static let plain: AccessibilityTextContentType
/// A type that represents text used for input, like in the Terminal app.
public static let console: AccessibilityTextContentType
/// A type that represents text used by a file browser, like in the Finder app in macOS.
public static let fileSystem: AccessibilityTextContentType
/// A type that represents text used in a message, like in the Messages app.
public static let messaging: AccessibilityTextContentType
/// A type that represents text used in a story or poem, like in the Books app.
public static let narrative: AccessibilityTextContentType
/// A type that represents text used in source code, like in Swift Playgrounds.
public static let sourceCode: AccessibilityTextContentType
/// A type that represents text used in a grid of data, like in the Numbers app.
public static let spreadsheet: AccessibilityTextContentType
/// A type that represents text used in a document, like in the Pages app.
public static let wordProcessing: AccessibilityTextContentType
}
/// A set of accessibility traits that describe how an element behaves.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct AccessibilityTraits : SetAlgebra, Sendable {
/// The accessibility element is a button.
public static let isButton: AccessibilityTraits
/// The accessibility element is a header that divides content into
/// sections, like the title of a navigation bar.
public static let isHeader: AccessibilityTraits
/// The accessibility element is currently selected.
public static let isSelected: AccessibilityTraits
/// The accessibility element is a link.
public static let isLink: AccessibilityTraits
/// The accessibility element is a search field.
public static let isSearchField: AccessibilityTraits
/// The accessibility element is an image.
public static let isImage: AccessibilityTraits
/// The accessibility element plays its own sound when activated.
public static let playsSound: AccessibilityTraits
/// The accessibility element behaves as a keyboard key.
public static let isKeyboardKey: AccessibilityTraits
/// The accessibility element is a static text that cannot be
/// modified by the user.
public static let isStaticText: AccessibilityTraits
/// The accessibility element provides summary information when the
/// application starts.
///
/// Use this trait to characterize an accessibility element that provides
/// a summary of current conditions, settings, or state, like the
/// temperature in the Weather app.
public static let isSummaryElement: AccessibilityTraits
/// The accessibility element frequently updates its label or value.
///
/// Use this trait when you want an assistive technology to poll for
/// changes when it needs updated information. For example, you might use
/// this trait to characterize the readout of a stopwatch.
public static let updatesFrequently: AccessibilityTraits
/// The accessibility element starts a media session when it is activated.
///
/// Use this trait to silence the audio output of an assistive technology,
/// such as VoiceOver, during a media session that should not be interrupted.
/// For example, you might use this trait to silence VoiceOver speech while
/// the user is recording audio.
public static let startsMediaSession: AccessibilityTraits
/// The accessibility element allows direct touch interaction for
/// VoiceOver users.
public static let allowsDirectInteraction: AccessibilityTraits
/// The accessibility element causes an automatic page turn when VoiceOver
/// finishes reading the text within it.
public static let causesPageTurn: AccessibilityTraits
/// The accessibility element is modal.
///
/// Use this trait to restrict which accessibility elements an assistive
/// technology can navigate. When a modal accessibility element is visible,
/// sibling accessibility elements that are not modal are ignored.
public static let isModal: AccessibilityTraits
/// The accessibility element is a toggle.
@available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *)
public static let isToggle: AccessibilityTraits
/// Creates an empty set.
///
/// This initializer is equivalent to initializing with an empty array
/// literal. For example, you create an empty `Set` instance with either
/// this initializer or with an empty array literal.
///
/// var emptySet = Set<Int>()
/// print(emptySet.isEmpty)
/// // Prints "true"
///
/// emptySet = []
/// print(emptySet.isEmpty)
/// // Prints "true"
public init()
/// Returns a new set with the elements of both this and the given set.
///
/// In the following example, the `attendeesAndVisitors` set is made up
/// of the elements of the `attendees` and `visitors` sets:
///
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors = ["Marcia", "Nathaniel"]
/// let attendeesAndVisitors = attendees.union(visitors)
/// print(attendeesAndVisitors)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept.
///
/// let initialIndices = Set(0..<5)
/// let expandedIndices = initialIndices.union([2, 3, 6, 7])
/// print(expandedIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set with the unique elements of this set and `other`.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
public func union(_ other: AccessibilityTraits) -> AccessibilityTraits
/// Adds the elements of the given set to the set.
///
/// In the following example, the elements of the `visitors` set are added to
/// the `attendees` set:
///
/// var attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors: Set = ["Diana", "Marcia", "Nathaniel"]
/// attendees.formUnion(visitors)
/// print(attendees)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept.
///
/// var initialIndices = Set(0..<5)
/// initialIndices.formUnion([2, 3, 6, 7])
/// print(initialIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
public mutating func formUnion(_ other: AccessibilityTraits)
/// Returns a new set with the elements that are common to both this set and
/// the given set.
///
/// In the following example, the `bothNeighborsAndEmployees` set is made up
/// of the elements that are in *both* the `employees` and `neighbors` sets.
/// Elements that are in only one or the other are left out of the result of
/// the intersection.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
public func intersection(_ other: AccessibilityTraits) -> AccessibilityTraits
/// Removes the elements of this set that aren't also in the given set.
///
/// In the following example, the elements of the `employees` set that are
/// not also members of the `neighbors` set are removed. In particular, the
/// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formIntersection(neighbors)
/// print(employees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
public mutating func formIntersection(_ other: AccessibilityTraits)
/// Returns a new set with the elements that are either in this set or in the
/// given set, but not in both.
///
/// In the following example, the `eitherNeighborsOrEmployees` set is made up
/// of the elements of the `employees` and `neighbors` sets that are not in
/// both `employees` *and* `neighbors`. In particular, the names `"Bethany"`
/// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`.
///
/// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani"]
/// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)
/// print(eitherNeighborsOrEmployees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
public func symmetricDifference(_ other: AccessibilityTraits) -> AccessibilityTraits
/// Removes the elements of the set that are also in the given set and adds
/// the members of the given set that are not already in the set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of `neighbors` are removed from `employees`, while the
/// elements of `neighbors` that are not members of `employees` are added to
/// `employees`. In particular, the names `"Bethany"` and `"Eric"` are
/// removed from `employees` while the name `"Forlani"` is added.
///
/// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani"]
/// employees.formSymmetricDifference(neighbors)
/// print(employees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A set of the same type.
public mutating func formSymmetricDifference(_ other: AccessibilityTraits)
/// Returns a Boolean value that indicates whether the given element exists
/// in the set.
///
/// This example uses the `contains(_:)` method to test whether an integer is
/// a member of a set of prime numbers.
///
/// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
/// let x = 5
/// if primes.contains(x) {
/// print("\(x) is prime!")
/// } else {
/// print("\(x). Not prime.")
/// }
/// // Prints "5 is prime!"
///
/// - Parameter member: An element to look for in the set.
/// - Returns: `true` if `member` exists in the set; otherwise, `false`.
public func contains(_ member: AccessibilityTraits) -> Bool
/// Inserts the given element in the set if it is not already present.
///
/// If an element equal to `newMember` is already contained in the set, this
/// method has no effect. In this example, a new element is inserted into
/// `classDays`, a set of days of the week. When an existing element is
/// inserted, the `classDays` set does not change.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
/// print(classDays.insert(.monday))
/// // Prints "(true, .monday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// print(classDays.insert(.friday))
/// // Prints "(false, .friday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: `(true, newMember)` if `newMember` was not contained in the
/// set. If an element equal to `newMember` was already contained in the
/// set, the method returns `(false, oldMember)`, where `oldMember` is the
/// element that was equal to `newMember`. In some cases, `oldMember` may
/// be distinguishable from `newMember` by identity comparison or some
/// other means.
public mutating func insert(_ newMember: AccessibilityTraits) -> (inserted: Bool, memberAfterInsert: AccessibilityTraits)
/// Removes the given element and any elements subsumed by the given element.
///
/// - Parameter member: The element of the set to remove.
/// - Returns: For ordinary sets, an element equal to `member` if `member` is
/// contained in the set; otherwise, `nil`. In some cases, a returned
/// element may be distinguishable from `member` by identity comparison
/// or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the set
/// and `[member]`, or `nil` if the intersection is empty.
public mutating func remove(_ member: AccessibilityTraits) -> AccessibilityTraits?
/// Inserts the given element into the set unconditionally.
///
/// If an element equal to `newMember` is already contained in the set,
/// `newMember` replaces the existing element. In this example, an existing
/// element is inserted into `classDays`, a set of days of the week.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]
/// print(classDays.update(with: .monday))
/// // Prints "Optional(.monday)"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: For ordinary sets, an element equal to `newMember` if the set
/// already contained such a member; otherwise, `nil`. In some cases, the
/// returned element may be distinguishable from `newMember` by identity
/// comparison or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the
/// set and `[newMember]`, or `nil` if the intersection is empty.
public mutating func update(with newMember: AccessibilityTraits) -> AccessibilityTraits?
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AccessibilityTraits, b: AccessibilityTraits) -> Bool
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = AccessibilityTraits
/// A type for which the conforming type provides a containment test.
public typealias Element = AccessibilityTraits
}
/// Position and direction information of a zoom gesture that someone performs
/// with an assistive technology like VoiceOver.
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
public struct AccessibilityZoomGestureAction {
/// A direction that matches the movement of a zoom gesture performed
/// by an assistive technology, such as a swipe up and down in Voiceover's
/// zoom rotor.
@frozen public enum Direction {
/// The gesture direction that represents zooming in.
case zoomIn
/// The gesture direction that represents zooming out.
case zoomOut
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AccessibilityZoomGestureAction.Direction, b: AccessibilityZoomGestureAction.Direction) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// The zoom gesture's direction.
public let direction: AccessibilityZoomGestureAction.Direction
/// The zoom gesture's activation point, normalized to the accessibility
/// element's frame.
public let location: UnitPoint
/// The zoom gesture's activation point within the window's coordinate
/// space.
public let point: CGPoint
}
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
extension AccessibilityZoomGestureAction.Direction : Equatable {
}
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
extension AccessibilityZoomGestureAction.Direction : Hashable {
}
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
extension AccessibilityZoomGestureAction.Direction : Sendable {
}
/// A button style that you use for extra actions in an accessory toolbar.
///
/// Use this style for buttons that perform extra actions relative to the
/// accessory toolbar's main functions, like adding or editing filters.
/// This style also affects other view types that you apply a button style to,
/// like ``Toggle``, ``Picker``, and ``Menu`` instances.
///
/// Use ``PrimitiveButtonStyle/accessoryBarAction`` to construct this style.
@available(macOS 14.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct AccessoryBarActionButtonStyle : PrimitiveButtonStyle {
/// Creates an accessory toolbar action button style
public init()
/// Creates a view that represents the body of a button.
///
/// The system calls this method for each ``Button`` instance in a view
/// hierarchy where this style is the current button style.
///
/// - Parameter configuration: The properties of the button.
public func makeBody(configuration: AccessoryBarActionButtonStyle.Configuration) -> some View
/// A view that represents the body of a button.
public typealias Body = some View
}
/// A button style that you use for actions in an accessory toolbar that
/// narrow the focus of a search or other operation.
///
/// This is the default button style for views in accessory toolbars,
/// which you create with ``ToolbarItemPlacement/init(id:)``,
/// and for searchable scopes.
/// This style also affects other view types that you apply a button style
/// to, like ``Toggle``, ``Picker``, and ``Menu`` instances.
///
/// Use ``PrimitiveButtonStyle/accessoryBar`` to construct this style.
@available(macOS 14.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct AccessoryBarButtonStyle : PrimitiveButtonStyle {
/// Creates an accessory toolbar style
public init()
/// Creates a view that represents the body of a button.
///
/// The system calls this method for each ``Button`` instance in a view
/// hierarchy where this style is the current button style.
///
/// - Parameter configuration: The properties of the button.
public func makeBody(configuration: AccessoryBarButtonStyle.Configuration) -> some View
/// A view that represents the body of a button.
public typealias Body = some View
}
/// A gauge style that displays a closed ring that's partially filled in to
/// indicate the gauge's current value.
///
/// Use ``GaugeStyle/accessoryCircularCapacity`` to construct this style.
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
public struct AccessoryCircularCapacityGaugeStyle : GaugeStyle {
/// Creates an accessory circular capacity gauge style.
public init()
/// Creates a view representing the body of a gauge.
///
/// The system calls this modifier on each instance of gauge within a view
/// hierarchy where this style is the current gauge style.
///
/// - Parameter configuration: The properties to apply to the gauge instance.
public func makeBody(configuration: AccessoryCircularCapacityGaugeStyle.Configuration) -> some View
/// A view representing the body of a gauge.
public typealias Body = some View
}
/// A gauge style that displays an open ring with a marker that appears at a
/// point along the ring to indicate the gauge's current value.
///
/// Use ``GaugeStyle/accessoryCircular`` to construct this style.
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
public struct AccessoryCircularGaugeStyle : GaugeStyle {
/// Creates an accessory circular gauge style.
public init()
/// Creates a view representing the body of a gauge.
///
/// The system calls this modifier on each instance of gauge within a view
/// hierarchy where this style is the current gauge style.
///
/// - Parameter configuration: The properties to apply to the gauge instance.
public func makeBody(configuration: AccessoryCircularGaugeStyle.Configuration) -> some View
/// A view representing the body of a gauge.
public typealias Body = some View
}
/// A gauge style that displays bar that fills from leading to trailing
/// edges as the gauge's current value increases.
///
/// Use ``GaugeStyle/accessoryLinearCapacity`` to construct this style.
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
public struct AccessoryLinearCapacityGaugeStyle : GaugeStyle {
/// Creates an accessory linear capacity gauge style.
public init()
/// Creates a view representing the body of a gauge.
///
/// The system calls this modifier on each instance of gauge within a view
/// hierarchy where this style is the current gauge style.
///
/// - Parameter configuration: The properties to apply to the gauge instance.
public func makeBody(configuration: AccessoryLinearCapacityGaugeStyle.Configuration) -> some View
/// A view representing the body of a gauge.
public typealias Body = some View
}
/// A gauge style that displays bar with a marker that appears at a
/// point along the bar to indicate the gauge's current value.
///
/// Use ``GaugeStyle/accessoryLinear`` to construct this style.
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
public struct AccessoryLinearGaugeStyle : GaugeStyle {
/// Creates an accessory linear gauge style.
public init()
/// Creates a view representing the body of a gauge.
///
/// The system calls this modifier on each instance of gauge within a view
/// hierarchy where this style is the current gauge style.
///
/// - Parameter configuration: The properties to apply to the gauge instance.
public func makeBody(configuration: AccessoryLinearGaugeStyle.Configuration) -> some View
/// A view representing the body of a gauge.
public typealias Body = some View
}
/// A representation of an alert presentation.
///
/// Use an alert when you want the user to act in response to the state of the
/// app or the system. If you want the user to make a choice in response to
/// their own action, use an ``ActionSheet`` instead.
///
/// You show an alert by using the ``View/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.")
/// )
/// }
/// }
///
/// ![A default alert dialog with the title Current Location Not Available in bold
/// text, the message your current location can’t be determined at this time in
/// smaller text, and a default OK button.](SwiftUI-Alert-OK.png)
///
/// 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 "destructive" button that calls a `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
/// )
/// )
/// }
/// }
///
/// ![An alert dialog with the title, Unable to Save Workout Data in bold text, and
/// the message, The connection to the server was lost, in smaller text. Below
/// the text, two buttons: a default button with Try Again in blue text, and a
/// button with Delete in red text.](SwiftUI-Alert-default-and-destructive.png)
///
/// The alert handles its own dismissal when the user taps one of the buttons in the alert, by setting
/// the bound `isPresented` value back to `false`.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "use `View.alert(title:isPresented:presenting::actions:) instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "use `View.alert(title:isPresented:presenting::actions:) instead.")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "use `View.alert(title:isPresented:presenting::actions:) instead.")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "use `View.alert(title:isPresented:presenting::actions:) instead.")
public struct Alert {
/// Creates an alert with one button.
/// - Parameters:
/// - title: The title of the alert.
/// - message: The message to display in the body of the alert.
/// - dismissButton: The button that dismisses the alert.
public init(title: Text, message: Text? = nil, dismissButton: Alert.Button? = nil)
/// Creates an alert with two buttons.
///
/// The system determines the visual ordering of the buttons.
/// - Parameters:
/// - title: The title of the alert.
/// - message: The message to display in the body of the alert.
/// - primaryButton: The first button to show in the alert.
/// - secondaryButton: The second button to show in the alert.
public init(title: Text, message: Text? = nil, primaryButton: Alert.Button, secondaryButton: Alert.Button)
/// A button representing an operation of an alert presentation.
public struct Button {
/// Creates an alert button with the default style.
/// - Parameters:
/// - label: The text to display on the button.
/// - action: A closure to execute when the user taps or presses the
/// button.
/// - Returns: An alert button with the default style.
public static func `default`(_ label: Text, action: (() -> Void)? = {}) -> Alert.Button
/// Creates an alert button that indicates cancellation, with a custom
/// label.
/// - Parameters:
/// - label: The text to display on the button.
/// - action: A closure to execute when the user taps or presses the
/// button.
/// - Returns: An alert button that indicates cancellation.
public static func cancel(_ label: Text, action: (() -> Void)? = {}) -> Alert.Button
/// Creates an alert button that indicates cancellation, with a
/// system-provided label.
///
/// The system automatically chooses locale-appropriate text for the
/// button's label.
/// - Parameter action: A closure to execute when the user taps or presses the
/// button.
/// - Returns: An alert button that indicates cancellation.
public static func cancel(_ action: (() -> Void)? = {}) -> Alert.Button
/// Creates an alert button with a style that indicates a destructive
/// action.
/// - Parameters:
/// - label: The text to display on the button.
/// - action: A closure to execute when the user taps or presses the
/// button.
/// - Returns: An alert button that indicates a destructive action.
public static func destructive(_ label: Text, action: (() -> Void)? = {}) -> Alert.Button
}
}
/// An alignment in both axes.
///
/// An `Alignment` contains a ``HorizontalAlignment`` guide and a
/// ``VerticalAlignment`` guide. Specify an alignment to direct the behavior of
/// certain layout containers and modifiers, like when you place views in a
/// ``ZStack``, or layer a view in front of or behind another view using
/// ``View/overlay(alignment:content:)`` or
/// ``View/background(alignment:content:)``, respectively. During layout,
/// SwiftUI brings the specified guides of the affected views together,
/// aligning the views.
///
/// SwiftUI provides a set of built-in alignments that represent common
/// combinations of the built-in horizontal and vertical alignment guides.
/// The blue boxes in the following diagram demonstrate the alignment named
/// by each box's label, relative to the background view:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A variety of blue
/// boxes are overlaid atop the square. Each contains the name of a built-in
/// alignment, and is aligned with the square in a way that matches the
/// alignment name. For example, the box lableled center appears at the
/// center of the square.](Alignment-1-iOS)
///
/// The following code generates the diagram above, where each blue box appears
/// in an overlay that's configured with a different alignment:
///
/// struct AlignmentGallery: View {
/// var body: some View {
/// BackgroundView()
/// .overlay(alignment: .topLeading) { box(".topLeading") }
/// .overlay(alignment: .top) { box(".top") }
/// .overlay(alignment: .topTrailing) { box(".topTrailing") }
/// .overlay(alignment: .leading) { box(".leading") }
/// .overlay(alignment: .center) { box(".center") }
/// .overlay(alignment: .trailing) { box(".trailing") }
/// .overlay(alignment: .bottomLeading) { box(".bottomLeading") }
/// .overlay(alignment: .bottom) { box(".bottom") }
/// .overlay(alignment: .bottomTrailing) { box(".bottomTrailing") }
/// .overlay(alignment: .leadingLastTextBaseline) { box(".leadingLastTextBaseline") }
/// .overlay(alignment: .trailingFirstTextBaseline) { box(".trailingFirstTextBaseline") }
/// }
///
/// private func box(_ name: String) -> some View {
/// Text(name)
/// .font(.system(.caption, design: .monospaced))
/// .padding(2)
/// .foregroundColor(.white)
/// .background(.blue.opacity(0.8), in: Rectangle())
/// }
/// }
///
/// private struct BackgroundView: View {
/// var body: some View {
/// Grid(horizontalSpacing: 0, verticalSpacing: 0) {
/// GridRow {
/// Text("Some text in an upper quadrant")
/// Color.gray.opacity(0.3)
/// }
/// GridRow {
/// Color.gray.opacity(0.3)
/// Text("More text in a lower quadrant")
/// }
/// }
/// .aspectRatio(1, contentMode: .fit)
/// .foregroundColor(.secondary)
/// .border(.gray)
/// }
/// }
///
/// To avoid crowding, the alignment diagram shows only two of the available
/// text baseline alignments. The others align as their names imply. Notice that
/// the first text baseline alignment aligns with the top-most line of text in
/// the background view, while the last text baseline aligns with the
/// bottom-most line. For more information about text baseline alignment, see
/// ``VerticalAlignment``.
///
/// In a left-to-right language like English, the leading and trailing
/// alignments appear on the left and right edges, respectively. SwiftUI
/// reverses these in right-to-left language environments. For more
/// information, see ``HorizontalAlignment``.
///
/// ### Custom alignment
///
/// You can create custom alignments --- which you typically do to make use
/// of custom horizontal or vertical guides --- by using the
/// ``init(horizontal:vertical:)`` initializer. For example, you can combine
/// a custom vertical guide called `firstThird` with the built-in horizontal
/// ``HorizontalAlignment/center`` guide, and use it to configure a ``ZStack``:
///
/// ZStack(alignment: Alignment(horizontal: .center, vertical: .firstThird)) {
/// // ...
/// }
///
/// For more information about creating custom guides, including the code
/// that creates the custom `firstThird` alignment in the example above,
/// see ``AlignmentID``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Alignment : Equatable {
/// The alignment on the horizontal axis.
///
/// Set this value when you initialize an alignment using the
/// ``init(horizontal:vertical:)`` method. Use one of the built-in
/// ``HorizontalAlignment`` guides, like ``HorizontalAlignment/center``,
/// or a custom guide that you create.
///
/// For information about creating custom guides, see ``AlignmentID``.
public var horizontal: HorizontalAlignment
/// The alignment on the vertical axis.
///
/// Set this value when you initialize an alignment using the
/// ``init(horizontal:vertical:)`` method. Use one of the built-in
/// ``VerticalAlignment`` guides, like ``VerticalAlignment/center``,
/// or a custom guide that you create.
///
/// For information about creating custom guides, see ``AlignmentID``.
public var vertical: VerticalAlignment
/// Creates a custom alignment value with the specified horizontal
/// and vertical alignment guides.
///
/// SwiftUI provides a variety of built-in alignments that combine built-in
/// ``HorizontalAlignment`` and ``VerticalAlignment`` guides. Use this
/// initializer to create a custom alignment that makes use
/// of a custom horizontal or vertical guide, or both.
///
/// For example, you can combine a custom vertical guide called
/// `firstThird` with the built-in ``HorizontalAlignment/center``
/// guide, and use it to configure a ``ZStack``:
///
/// ZStack(alignment: Alignment(horizontal: .center, vertical: .firstThird)) {
/// // ...
/// }
///
/// For more information about creating custom guides, including the code
/// that creates the custom `firstThird` alignment in the example above,
/// see ``AlignmentID``.
///
/// - Parameters:
/// - horizontal: The alignment on the horizontal axis.
/// - vertical: The alignment on the vertical axis.
@inlinable public init(horizontal: HorizontalAlignment, vertical: VerticalAlignment)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Alignment, b: Alignment) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Alignment {
/// A guide that marks the center of the view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/center``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Center, appears at the center of the
/// square.](Alignment-center-1-iOS)
public static let center: Alignment
/// A guide that marks the leading edge of the view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/center``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Leading, appears on the left edge of the
/// square, centered vertically.](Alignment-leading-1-iOS)
public static let leading: Alignment
/// A guide that marks the trailing edge of the view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/center``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Trailing, appears on the right edge of the
/// square, centered vertically.](Alignment-trailing-1-iOS)
public static let trailing: Alignment
/// A guide that marks the top edge of the view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/top``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Top, appears on the top edge of the
/// square, centered horizontally.](Alignment-top-1-iOS)
public static let top: Alignment
/// A guide that marks the bottom edge of the view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/bottom``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Bottom, appears on the bottom edge of the
/// square, centered horizontally.](Alignment-bottom-1-iOS)
public static let bottom: Alignment
/// A guide that marks the top and leading edges of the view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/top``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, topLeading, appears in the upper-left corner of
/// the square.](Alignment-topLeading-1-iOS)
public static let topLeading: Alignment
/// A guide that marks the top and trailing edges of the view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/top``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, topTrailing, appears in the upper-right corner of
/// the square.](Alignment-topTrailing-1-iOS)
public static let topTrailing: Alignment
/// A guide that marks the bottom and leading edges of the view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/bottom``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, bottomLeading, appears in the lower-left corner of
/// the square.](Alignment-bottomLeading-1-iOS)
public static let bottomLeading: Alignment
/// A guide that marks the bottom and trailing edges of the view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/bottom``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, bottomTrailing, appears in the lower-right corner of
/// the square.](Alignment-bottomTrailing-1-iOS)
public static let bottomTrailing: Alignment
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Alignment {
/// A guide that marks the top-most text baseline in a view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/firstTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, centerFirstTextBaseline, appears aligned with, and
/// partially overlapping, the first line of the text in the upper quadrant,
/// centered horizontally.](Alignment-centerFirstTextBaseline-1-iOS)
public static var centerFirstTextBaseline: Alignment { get }
/// A guide that marks the bottom-most text baseline in a view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/lastTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, centerLastTextBaseline, appears aligned with, and
/// partially overlapping, the last line of the text in the lower quadrant,
/// centered horizontally.](Alignment-centerLastTextBaseline-1-iOS)
public static var centerLastTextBaseline: Alignment { get }
/// A guide that marks the leading edge and top-most text baseline in a
/// view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/firstTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, leadingFirstTextBaseline, appears aligned with, and
/// partially overlapping, the first line of the text in the upper quadrant.
/// The box aligns with the left edge of the
/// square.](Alignment-leadingFirstTextBaseline-1-iOS)
public static var leadingFirstTextBaseline: Alignment { get }
/// A guide that marks the leading edge and bottom-most text baseline
/// in a view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/lastTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, leadingLastTextBaseline, appears aligned with the
/// last line of the text in the lower quadrant. The box aligns with the
/// left edge of the square.](Alignment-leadingLastTextBaseline-1-iOS)
public static var leadingLastTextBaseline: Alignment { get }
/// A guide that marks the trailing edge and top-most text baseline in
/// a view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/firstTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, trailingFirstTextBaseline, appears aligned with the
/// first line of the text in the upper quadrant. The box aligns with the
/// right edge of the square.](Alignment-trailingFirstTextBaseline-1-iOS)
public static var trailingFirstTextBaseline: Alignment { get }
/// A guide that marks the trailing edge and bottom-most text baseline
/// in a view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/lastTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, trailingLastTextBaseline, appears aligned with the
/// last line of the text in the lower quadrant. The box aligns with the
/// right edge of the square.](Alignment-trailingLastTextBaseline-1-iOS)
public static var trailingLastTextBaseline: Alignment { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Alignment : Sendable {
}
/// A type that you use to create custom alignment guides.
///
/// Every built-in alignment guide that ``VerticalAlignment`` or
/// ``HorizontalAlignment`` defines as a static property, like
/// ``VerticalAlignment/top`` or ``HorizontalAlignment/leading``, has a
/// unique alignment identifier type that produces the default offset for
/// that guide. To create a custom alignment guide, define your own alignment
/// identifier as a type that conforms to the `AlignmentID` protocol, and
/// implement the required ``AlignmentID/defaultValue(in:)`` method:
///
/// private struct FirstThirdAlignment: AlignmentID {
/// static func defaultValue(in context: ViewDimensions) -> CGFloat {
/// context.height / 3
/// }
/// }
///
/// When implementing the method, calculate the guide's default offset
/// from the view's origin. If it's helpful, you can use information from the
/// ``ViewDimensions`` input in the calculation. This parameter provides context
/// about the specific view that's using the guide. The above example creates an
/// identifier called `FirstThirdAlignment` and calculates a default value
/// that's one-third of the height of the aligned view.
///
/// Use the identifier's type to create a static property in an extension of
/// one of the alignment guide types, like ``VerticalAlignment``:
///
/// extension VerticalAlignment {
/// static let firstThird = VerticalAlignment(FirstThirdAlignment.self)
/// }
///
/// You can apply your custom guide like any of the built-in guides. For
/// example, you can use an ``HStack`` to align its views at one-third
/// of their height using the guide defined above:
///
/// struct StripesGroup: View {
/// var body: some View {
/// HStack(alignment: .firstThird, spacing: 1) {
/// HorizontalStripes().frame(height: 60)
/// HorizontalStripes().frame(height: 120)
/// HorizontalStripes().frame(height: 90)
/// }
/// }
/// }
///
/// struct HorizontalStripes: View {
/// var body: some View {
/// VStack(spacing: 1) {
/// ForEach(0..<3) { _ in Color.blue }
/// }
/// }
/// }
///
/// Because each set of stripes has three equal, vertically stacked
/// rectangles, they align at the bottom edge of the top rectangle. This
/// corresponds in each case to a third of the overall height, as
/// measured from the origin at the top of each set of stripes:
///
/// ![Three vertical stacks of rectangles, arranged in a row.
/// The rectangles in each stack have the same height as each other, but
/// different heights than the rectangles in the other stacks. The bottom edges
/// of the top-most rectangle in each stack are aligned with each
/// other.](AlignmentId-1-iOS)
///
/// You can also use the ``View/alignmentGuide(_:computeValue:)-6y3u2`` view
/// modifier to alter the behavior of your custom guide for a view, as you
/// might alter a built-in guide. For example, you can change
/// one of the stacks of stripes from the previous example to align its
/// `firstThird` guide at two thirds of the height instead:
///
/// struct StripesGroupModified: View {
/// var body: some View {
/// HStack(alignment: .firstThird, spacing: 1) {
/// HorizontalStripes().frame(height: 60)
/// HorizontalStripes().frame(height: 120)
/// HorizontalStripes().frame(height: 90)
/// .alignmentGuide(.firstThird) { context in
/// 2 * context.height / 3
/// }
/// }
/// }
/// }
///
/// The modified guide calculation causes the affected view to place the
/// bottom edge of its middle rectangle on the `firstThird` guide, which aligns
/// with the bottom edge of the top rectangle in the other two groups:
///
/// ![Three vertical stacks of rectangles, arranged in a row.
/// The rectangles in each stack have the same height as each other, but
/// different heights than the rectangles in the other stacks. The bottom edges
/// of the top-most rectangle in the first two stacks are aligned with each
/// other, and with the bottom edge of the middle rectangle in the third
/// stack.](AlignmentId-2-iOS)
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol AlignmentID {
/// Calculates a default value for the corresponding guide in the specified
/// context.
///
/// Implement this method when you create a type that conforms to the
/// ``AlignmentID`` protocol. Use the method to calculate the default
/// offset of the corresponding alignment guide. SwiftUI interprets the
/// value that you return as an offset in the coordinate space of the
/// view that's being laid out. For example, you can use the context to
/// return a value that's one-third of the height of the view:
///
/// private struct FirstThirdAlignment: AlignmentID {
/// static func defaultValue(in context: ViewDimensions) -> CGFloat {
/// context.height / 3
/// }
/// }
///
/// You can override the default value that this method returns for a
/// particular guide by adding the
/// ``View/alignmentGuide(_:computeValue:)-9mdoh`` view modifier to a
/// particular view.
///
/// - Parameter context: The context of the view that you apply
/// the alignment guide to. The context gives you the view's dimensions,
/// as well as the values of other alignment guides that apply to the
/// view, including both built-in and custom guides. You can use any of
/// these values, if helpful, to calculate the value for your custom
/// guide.
///
/// - Returns: The offset of the guide from the origin in the
/// view's coordinate space.
static func defaultValue(in context: ViewDimensions) -> CGFloat
}
/// The styling of views with respect to alternating row backgrounds.
///
/// Use values of this type with the ``View/alternatingRowBackgrounds(_:)``
/// modifier.
@available(macOS 14.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct AlternatingRowBackgroundBehavior : Hashable, Sendable {
/// The automatic alternating row background behavior.
///
/// This defers to default component behavior for alternating row
/// backgrounds. Some components, such as `Table` on macOS, will default
/// to having alternating row backgrounds; while List does not.
public static let automatic: AlternatingRowBackgroundBehavior
/// Alternating rows will be enabled for applicable views.
public static let enabled: AlternatingRowBackgroundBehavior
/// Alternating rows will be disabled for applicable views.
public static let disabled: AlternatingRowBackgroundBehavior
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AlternatingRowBackgroundBehavior, b: AlternatingRowBackgroundBehavior) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// An opaque value derived from an anchor source and a particular view.
///
/// You can convert the anchor to a `Value` in the coordinate space of a target
/// view by using a ``GeometryProxy`` to specify the target view.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Anchor<Value> {
/// A type-erased geometry value that produces an anchored value of a given
/// type.
///
/// SwiftUI passes anchored geometry values around the view tree via
/// preference keys. It then converts them back into the local coordinate
/// space using a ``GeometryProxy`` value.
@frozen public struct Source {
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor : Sendable where Value : Sendable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Anchor : Equatable where Value : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Anchor<Value>, rhs: Anchor<Value>) -> Bool
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Anchor : Hashable where Value : Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor.Source : Sendable where Value : Sendable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor.Source {
public init<T>(_ array: [Anchor<T>.Source]) where Value == [T]
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor.Source {
public init<T>(_ anchor: Anchor<T>.Source?) where Value == T?
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor.Source where Value == CGPoint {
public static func point(_ p: CGPoint) -> Anchor<Value>.Source
public static func unitPoint(_ p: UnitPoint) -> Anchor<Value>.Source
public static var topLeading: Anchor<CGPoint>.Source { get }
public static var top: Anchor<CGPoint>.Source { get }
public static var topTrailing: Anchor<CGPoint>.Source { get }
public static var leading: Anchor<CGPoint>.Source { get }
public static var center: Anchor<CGPoint>.Source { get }
public static var trailing: Anchor<CGPoint>.Source { get }
public static var bottomLeading: Anchor<CGPoint>.Source { get }
public static var bottom: Anchor<CGPoint>.Source { get }
public static var bottomTrailing: Anchor<CGPoint>.Source { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor.Source where Value == CGRect {
/// Returns an anchor source rect defined by `r` in the current view.
public static func rect(_ r: CGRect) -> Anchor<Value>.Source
/// An anchor source rect defined as the entire bounding rect of the current
/// view.
public static var bounds: Anchor<CGRect>.Source { get }
}
/// A geometric angle whose value you access in either radians or degrees.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Angle {
public var radians: Double
@inlinable public var degrees: Double
@inlinable public init()
@inlinable public init(radians: Double)
@inlinable public init(degrees: Double)
@inlinable public static func radians(_ radians: Double) -> Angle
@inlinable public static func degrees(_ degrees: Double) -> Angle
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Angle : Hashable, Comparable {
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
@inlinable public static func < (lhs: Angle, rhs: Angle) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Angle, b: Angle) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Angle : Animatable {
/// The data to animate.
public var animatableData: Double
@inlinable public static var zero: Angle { get }
/// The type defining the data to animate.
public typealias AnimatableData = Double
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Angle : Sendable {
}
/// An angular gradient.
///
/// An angular gradient is also known as a "conic" gradient. This gradient
/// applies the color function as the angle changes, relative to a center
/// point and defined start and end angles. If `endAngle - startAngle > 2π`,
/// the gradient only draws the last complete turn. If
/// `endAngle - startAngle < 2π`, the gradient fills the missing area with
/// the colors defined by gradient locations one and zero, transitioning
/// between the two halfway across the missing area. The gradient maps the
/// unit space center point into the bounding rectangle of each shape filled
/// with the gradient.
///
/// When using an angular gradient as a shape style, you can also use
/// ``ShapeStyle/angularGradient(_:center:startAngle:endAngle:)-378tu``,
/// ``ShapeStyle/conicGradient(_:center:angle:)-e0rd``, or similar methods.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AngularGradient : ShapeStyle, View, Sendable {
/// Creates an angular gradient.
public init(gradient: Gradient, center: UnitPoint, startAngle: Angle = .zero, endAngle: Angle = .zero)
/// Creates an angular gradient from a collection of colors.
public init(colors: [Color], center: UnitPoint, startAngle: Angle, endAngle: Angle)
/// Creates an angular gradient from a collection of color stops.
public init(stops: [Gradient.Stop], center: UnitPoint, startAngle: Angle, endAngle: Angle)
/// Creates a conic gradient that completes a full turn.
public init(gradient: Gradient, center: UnitPoint, angle: Angle = .zero)
/// Creates a conic gradient from a collection of colors that completes
/// a full turn.
public init(colors: [Color], center: UnitPoint, angle: Angle = .zero)
/// Creates a conic gradient from a collection of color stops that
/// completes a full turn.
public init(stops: [Gradient.Stop], center: UnitPoint, angle: Angle = .zero)
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
public typealias Resolved = Never
}
/// A type that describes how to animate a property of a view.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol Animatable {
/// The type defining the data to animate.
associatedtype AnimatableData : VectorArithmetic
/// The data to animate.
var animatableData: Self.AnimatableData { get set }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animatable where Self : VectorArithmetic {
/// The data to animate.
public var animatableData: Self
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animatable where Self.AnimatableData == EmptyAnimatableData {
/// The data to animate.
public var animatableData: EmptyAnimatableData
}
/// A modifier that can create another modifier with animation.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "use Animatable directly")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "use Animatable directly")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "use Animatable directly")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "use Animatable directly")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "use Animatable directly")
public protocol AnimatableModifier : Animatable, ViewModifier {
}
/// A pair of animatable values, which is itself animatable.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AnimatablePair<First, Second> : VectorArithmetic where First : VectorArithmetic, Second : VectorArithmetic {
/// The first value.
public var first: First
/// The second value.
public var second: Second
/// Creates an animated pair with the provided values.
@inlinable public init(_ first: First, _ second: Second)
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
public static var zero: AnimatablePair<First, Second> { get }
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
public static func += (lhs: inout AnimatablePair<First, Second>, rhs: AnimatablePair<First, Second>)
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
public static func -= (lhs: inout AnimatablePair<First, Second>, rhs: AnimatablePair<First, Second>)
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
public static func + (lhs: AnimatablePair<First, Second>, rhs: AnimatablePair<First, Second>) -> AnimatablePair<First, Second>
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
public static func - (lhs: AnimatablePair<First, Second>, rhs: AnimatablePair<First, Second>) -> AnimatablePair<First, Second>
/// Multiplies each component of this value by the given value.
public mutating func scale(by rhs: Double)
/// The dot-product of this animated pair with itself.
public var magnitudeSquared: Double { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AnimatablePair<First, Second>, b: AnimatablePair<First, Second>) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnimatablePair : Sendable where First : Sendable, Second : Sendable {
}
/// The way a view changes over time to create a smooth visual transition from
/// one state to another.
///
/// An `Animation` provides a visual transition of a view when a state value
/// changes from one value to another. The characteristics of this transition
/// vary according to the animation type. For instance, a ``linear`` animation
/// provides a mechanical feel to the animation because its speed is consistent
/// from start to finish. In contrast, an animation that uses easing, like
/// ``easeOut``, offers a more natural feel by varying the acceleration
/// of the animation.
///
/// To apply an animation to a view, add the ``View/animation(_:value:)``
/// modifier, and specify both an animation type and the value to animate. For
/// instance, the ``Circle`` view in the following code performs an
/// ``easeIn`` animation each time the state variable `scale` changes:
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scaleEffect(scale)
/// .animation(.easeIn, value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// .padding()
/// }
///
/// @Video(source: "animation-01-overview-easein.mp4", poster: "animation-01-overview-easein.png", alt: "A video that shows a circle enlarging then shrinking to its original size using an ease-in animation.")
///
/// When the value of `scale` changes, the modifier
/// ``View/scaleEffect(_:anchor:)-pmi7`` resizes ``Circle`` according to the
/// new value. SwiftUI can animate the transition between sizes because
/// ``Circle`` conforms to the ``Shape`` protocol. Shapes in SwiftUI conform to
/// the ``Animatable`` protocol, which describes how to animate a property of a
/// view.
///
/// In addition to adding an animation to a view, you can also configure the
/// animation by applying animation modifiers to the animation type. For
/// example, you can:
///
/// - Delay the start of the animation by using the ``delay(_:)`` modifier.
/// - Repeat the animation by using the ``repeatCount(_:autoreverses:)`` or
/// ``repeatForever(autoreverses:)`` modifiers.
/// - Change the speed of the animation by using the ``speed(_:)`` modifier.
///
/// For example, the ``Circle`` view in the following code repeats
/// the ``easeIn`` animation three times by using the
/// ``repeatCount(_:autoreverses:)`` modifier:
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scaleEffect(scale)
/// .animation(.easeIn.repeatCount(3), value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// .padding()
/// }
/// }
///
/// @Video(source: "animation-02-overview-easein-repeat.mp4", poster: "animation-02-overview-easein-repeat.png", alt: "A video that shows a circle that repeats the ease-in animation three times: enlarging, then shrinking, then enlarging again. The animation reverses causing the circle to shrink, then enlarge, then shrink to its original size.")
///
/// A view can also perform an animation when a binding value changes. To
/// specify the animation type on a binding, call its ``Binding/animation(_:)``
/// method. For example, the view in the following code performs a
/// ``linear`` animation, moving the box truck between the leading and trailing
/// edges of the view. The truck moves each time a person clicks the ``Toggle``
/// control, which changes the value of the `$isTrailing` binding.
///
/// struct ContentView: View {
/// @State private var isTrailing = false
///
/// var body: some View {
/// VStack(alignment: isTrailing ? .trailing : .leading) {
/// Image(systemName: "box.truck")
/// .font(.system(size: 64))
///
/// Toggle("Move to trailing edge",
/// isOn: $isTrailing.animation(.linear))
/// }
/// }
/// }
///
/// @Video(source: "animation-03-overview-binding.mp4", poster: "animation-03-overview-binding.png", alt: "A video that shows a box truck that moves from the leading edge of a view to the trailing edge. The box truck then returns to the view's leading edge.")
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Animation : Equatable, Sendable {
/// Create an `Animation` that contains the specified custom animation.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public init<A>(_ base: A) where A : CustomAnimation
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Animation, rhs: Animation) -> Bool
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Animation : Hashable {
/// Calculates the current value of the animation.
///
/// - Returns: The current value of the animation, or `nil` if the animation has finished.
public func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic
/// Calculates the current velocity of the animation.
///
/// - Returns: The current velocity of the animation, or `nil` if the the velocity isn't available.
public func velocity<V>(value: V, time: TimeInterval, context: AnimationContext<V>) -> V? where V : VectorArithmetic
/// Returns a Boolean value that indicates whether the current animation
/// should merge with a previous animation.
public func shouldMerge<V>(previous: Animation, value: V, time: TimeInterval, context: inout AnimationContext<V>) -> Bool where V : VectorArithmetic
public var base: CustomAnimation { get }
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
/// A textual representation of this instance.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(describing:)`
/// initializer. This initializer works with any type, and uses the custom
/// `description` property for types that conform to
/// `CustomStringConvertible`:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String { get }
/// A textual representation of this instance, suitable for debugging.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(reflecting:)`
/// initializer. This initializer works with any type, and uses the custom
/// `debugDescription` property for types that conform to
/// `CustomDebugStringConvertible`:
///
/// struct Point: CustomDebugStringConvertible {
/// let x: Int, y: Int
///
/// var debugDescription: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(reflecting: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `debugDescription` property.
public var debugDescription: String { get }
/// The custom mirror for this instance.
///
/// If this type has value semantics, the mirror should be unaffected by
/// subsequent mutations of the instance.
public var customMirror: Mirror { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Animation {
/// A persistent spring animation.
///
/// When mixed with other `spring()`
/// or `interactiveSpring()` animations on the same property, each
/// animation will be replaced by their successor, preserving
/// velocity from one animation to the next. Optionally blends the
/// duration values between springs over a time period.
public static func spring(_ spring: Spring, blendDuration: TimeInterval = 0.0) -> Animation
/// An interpolating spring animation that uses a damped spring
/// model to produce values in the range of one to zero.
///
/// These vales are used to interpolate within the `[from, to]` range
/// of the animated
/// property. Preserves velocity across overlapping animations by
/// adding the effects of each animation.
public static func interpolatingSpring(_ spring: Spring, initialVelocity: Double = 0.0) -> Animation
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Animation {
/// Creates a new animation with speed controlled by the given curve.
///
/// - Parameters:
/// - timingCurve: A curve that describes the speed of the
/// animation over its duration.
/// - duration: The duration of the animation, in seconds.
public static func timingCurve(_ curve: UnitCurve, duration: TimeInterval) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// Repeats the animation for a specific number of times.
///
/// Use this method to repeat the animation a specific number of times. For
/// example, in the following code, the animation moves a truck from one
/// edge of the view to the other edge. It repeats this animation three
/// times.
///
/// struct ContentView: View {
/// @State private var driveForward = true
///
/// private var driveAnimation: Animation {
/// .easeInOut
/// .repeatCount(3, autoreverses: true)
/// .speed(0.5)
/// }
///
/// var body: some View {
/// VStack(alignment: driveForward ? .leading : .trailing, spacing: 40) {
/// Image(systemName: "box.truck")
/// .font(.system(size: 48))
/// .animation(driveAnimation, value: driveForward)
///
/// HStack {
/// Spacer()
/// Button("Animate") {
/// driveForward.toggle()
/// }
/// Spacer()
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-16-repeat-count.mp4", poster: "animation-16-repeat-count.png", alt: "A video that shows a box truck moving from the leading edge of a view to the trailing edge, and back again before looping in the opposite direction.")
///
/// The first time the animation runs, the truck moves from the leading
/// edge to the trailing edge of the view. The second time the animation
/// runs, the truck moves from the trailing edge to the leading edge
/// because `autoreverse` is `true`. If `autoreverse` were `false`, the
/// truck would jump back to leading edge before moving to the trailing
/// edge. The third time the animation runs, the truck moves from the
/// leading to the trailing edge of the view.
///
/// - Parameters:
/// - repeatCount: The number of times that the animation repeats. Each
/// repeated sequence starts at the beginning when `autoreverse` is
/// `false`.
/// - autoreverses: A Boolean value that indicates whether the animation
/// sequence plays in reverse after playing forward. Autoreverse counts
/// towards the `repeatCount`. For instance, a `repeatCount` of one plays
/// the animation forward once, but it doesn’t play in reverse even if
/// `autoreverse` is `true`. When `autoreverse` is `true` and
/// `repeatCount` is `2`, the animation moves forward, then reverses, then
/// stops.
/// - Returns: An animation that repeats for specific number of times.
public func repeatCount(_ repeatCount: Int, autoreverses: Bool = true) -> Animation
/// Repeats the animation for the lifespan of the view containing the
/// animation.
///
/// Use this method to repeat the animation until the instance of the view
/// no longer exists, or the view’s explicit or structural identity
/// changes. For example, the following code continuously rotates a
/// gear symbol for the lifespan of the view.
///
/// struct ContentView: View {
/// @State private var rotationDegrees = 0.0
///
/// private var animation: Animation {
/// .linear
/// .speed(0.1)
/// .repeatForever(autoreverses: false)
/// }
///
/// var body: some View {
/// Image(systemName: "gear")
/// .font(.system(size: 86))
/// .rotationEffect(.degrees(rotationDegrees))
/// .onAppear {
/// withAnimation(animation) {
/// rotationDegrees = 360.0
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-17-repeat-forever.mp4", poster: "animation-17-repeat-forever.png", alt: "A video that shows a gear that continuously rotates clockwise.")
///
/// - Parameter autoreverses: A Boolean value that indicates whether the
/// animation sequence plays in reverse after playing forward.
/// - Returns: An animation that continuously repeats.
public func repeatForever(autoreverses: Bool = true) -> Animation
}
extension Animation {
/// Causes the animation to report logical completion after the specified
/// duration, if it has not already logically completed.
///
/// Note that the indicated duration will not cause the animation to
/// continue running after the base animation has fully completed.
///
/// If the animation is removed before the given duration is reached,
/// logical completion will be reported immediately.
///
/// - Parameters:
/// - duration: The duration after which the animation should report
/// that it is logically complete.
/// - Returns: An animation that reports logical completion after the
/// given duration.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func logicallyComplete(after duration: TimeInterval) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// An animation with a specified duration that combines the behaviors of
/// in and out easing animations.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. An ease in and out animation
/// starts slowly, increasing its speed towards the halfway point, and
/// finally decreasing the speed towards the end of the animation.
///
/// Use `easeInOut(duration:)` when you want to specify the time it takes
/// for the animation to complete. Otherwise, use ``easeInOut`` to perform
/// the animation for a default length of time.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using an ease in and out animation with a duration of
/// one second.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeInOut(duration: 1.0), value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-13-easeineaseout-duration.mp4", poster: "animation-13-easeineaseout-duration.png", alt: "A video that shows a circle enlarging for one second, then shrinking for another second to its original size using an ease-in ease-out animation.")
///
/// - Parameter duration: The length of time, expressed in seconds, that
/// the animation takes to complete.
///
/// - Returns: An ease-in ease-out animation with a specified duration.
public static func easeInOut(duration: TimeInterval) -> Animation
/// An animation that combines the behaviors of in and out easing
/// animations.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. An ease in and out animation
/// starts slowly, increasing its speed towards the halfway point, and
/// finally decreasing the speed towards the end of the animation.
///
/// The `easeInOut` animation has a default duration of 0.35 seconds. To
/// specify the duration, use the ``easeInOut(duration:)`` method.
///
/// The following code shows an example of animating the size changes of a
/// ``Circle`` using an ease in and out animation.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeInOut, value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-12-easeineaseout.mp4", poster: "animation-12-easeineaseout.png", alt: "A video that shows a circle enlarging, then shrinking to its original size using an ease-in ease-out animation.")
///
/// - Returns: An ease-in ease-out animation with the default duration.
public static var easeInOut: Animation { get }
/// An animation with a specified duration that starts slowly and then
/// increases speed towards the end of the movement.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. With an ease in animation, the
/// motion starts slowly and increases its speed towards the end.
///
/// Use `easeIn(duration:)` when you want to specify the time it takes
/// for the animation to complete. Otherwise, use ``easeIn`` to perform the
/// animation for a default length of time.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using an ease in animation with a duration of one
/// second.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeIn(duration: 1.0), value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-09-easein-duration.mp4", poster: "animation-09-easein-duration.png", alt: "A video that shows a circle enlarging for one second, then shrinking for another second to its original size using an ease-in animation.")
///
/// - Parameter duration: The length of time, expressed in seconds, that
/// the animation takes to complete.
///
/// - Returns: An ease-in animation with a specified duration.
public static func easeIn(duration: TimeInterval) -> Animation
/// An animation that starts slowly and then increases speed towards the
/// end of the movement.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. With an ease in animation, the
/// motion starts slowly and increases its speed towards the end.
///
/// The `easeIn` animation has a default duration of 0.35 seconds. To
/// specify a different duration, use ``easeIn(duration:)``.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using the ease in animation.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeIn, value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-08-easein.mp4", poster: "animation-08-easein.png", alt: "A video that shows a circle enlarging, then shrinking to its original size using an ease-in animation.")
///
/// - Returns: An ease-in animation with the default duration.
public static var easeIn: Animation { get }
/// An animation with a specified duration that starts quickly and then
/// slows towards the end of the movement.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. With an ease out animation, the
/// motion starts quickly and decreases its speed towards the end.
///
/// Use `easeOut(duration:)` when you want to specify the time it takes
/// for the animation to complete. Otherwise, use ``easeOut`` to perform
/// the animation for a default length of time.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using an ease out animation with a duration of one
/// second.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeOut(duration: 1.0), value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-09-easein-duration.mp4", poster: "animation-09-easein-duration.png", alt: "A video that shows a circle enlarging for one second, then shrinking for another second to its original size using an ease-in animation.")
///
/// - Parameter duration: The length of time, expressed in seconds, that
/// the animation takes to complete.
///
/// - Returns: An ease-out animation with a specified duration.
public static func easeOut(duration: TimeInterval) -> Animation
/// An animation that starts quickly and then slows towards the end of the
/// movement.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. With an ease out animation, the
/// motion starts quickly and decreases its speed towards the end.
///
/// The `easeOut` animation has a default duration of 0.35 seconds. To
/// specify a different duration, use ``easeOut(duration:)``.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using an ease out animation.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeOut, value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-10-easeout.mp4", poster: "animation-10-easeout.png", alt: "A video that shows a circle enlarging, then shrinking to its original size using an ease-out animation.")
///
/// - Returns: An ease-out animation with the default duration.
public static var easeOut: Animation { get }
/// An animation that moves at a constant speed during a specified
/// duration.
///
/// A linear animation provides a mechanical feel to the motion because its
/// speed is consistent from start to finish of the animation. This
/// constant speed makes a linear animation ideal for animating the
/// movement of objects where changes in the speed might feel awkward, such
/// as with an activity indicator.
///
/// Use `linear(duration:)` when you want to specify the time it takes
/// for the animation to complete. Otherwise, use ``linear`` to perform the
/// animation for a default length of time.
///
/// The following code shows an example of using linear animation with a
/// duration of two seconds to animate the movement of a circle as it moves
/// between the leading and trailing edges of the view. The color of the
/// circle also animates from red to blue as it moves across the view.
///
/// struct ContentView: View {
/// @State private var isActive = false
///
/// var body: some View {
/// VStack(alignment: isActive ? .trailing : .leading) {
/// Circle()
/// .fill(isActive ? Color.red : Color.blue)
/// .frame(width: 50, height: 50)
///
/// Button("Animate") {
/// withAnimation(.linear(duration: 2.0)) {
/// isActive.toggle()
/// }
/// }
/// .frame(maxWidth: .infinity)
/// }
/// }
/// }
///
/// @Video(source: "animation-07-linear-duration.mp4", poster: "animation-07-linear-duration.png", alt: "A video that shows a circle moving from the leading edge of the view to the trailing edge. The color of the circle also changes from red to blue as it moves across the view. Then the circle moves from the trailing edge back to the leading edge while also changing colors from blue to red.")
///
/// - Parameter duration: The length of time, expressed in seconds, that
/// the animation takes to complete.
///
/// - Returns: A linear animation with a specified duration.
public static func linear(duration: TimeInterval) -> Animation
/// An animation that moves at a constant speed.
///
/// A linear animation provides a mechanical feel to the motion because its
/// speed is consistent from start to finish of the animation. This
/// constant speed makes a linear animation ideal for animating the
/// movement of objects where changes in the speed might feel awkward, such
/// as with an activity indicator.
///
/// The following code shows an example of using linear animation to
/// animate the movement of a circle as it moves between the leading and
/// trailing edges of the view. The circle also animates its color change
/// as it moves across the view.
///
/// struct ContentView: View {
/// @State private var isActive = false
///
/// var body: some View {
/// VStack(alignment: isActive ? .trailing : .leading) {
/// Circle()
/// .fill(isActive ? Color.red : Color.blue)
/// .frame(width: 50, height: 50)
///
/// Button("Animate") {
/// withAnimation(.linear) {
/// isActive.toggle()
/// }
/// }
/// .frame(maxWidth: .infinity)
/// }
/// }
/// }
///
/// @Video(source: "animation-06-linear.mp4", poster: "animation-06-linear.png", alt: "A video that shows a circle moving from the leading edge of the view to the trailing edge. The color of the circle also changes from red to blue as it moves across the view. Then the circle moves from the trailing edge back to the leading edge while also changing colors from blue to red.")
///
/// The `linear` animation has a default duration of 0.35 seconds. To
/// specify a different duration, use ``linear(duration:)``.
///
/// - Returns: A linear animation with the default duration.
public static var linear: Animation { get }
/// An animation created from a cubic Bézier timing curve.
///
/// Use this method to create a timing curve based on the control points of
/// a cubic Bézier curve. A cubic Bézier timing curve consists of a line
/// whose starting point is `(0, 0)` and whose end point is `(1, 1)`. Two
/// additional control points, `(p1x, p1y)` and `(p2x, p2y)`, define the
/// shape of the curve.
///
/// The slope of the line defines the speed of the animation at that point
/// in time. A steep slopes causes the animation to appear to run faster,
/// while a shallower slope appears to run slower. The following
/// illustration shows a timing curve where the animation starts and
/// finishes fast, but appears slower through the middle section of the
/// animation.
///
/// ![An illustration of an XY graph that shows the path of a Bézier timing curve that an animation frame follows over time. The horizontal x-axis has a label with the text Time, and a label with the text Frame appears along the vertical y-axis. The path begins at the graph's origin, labeled as (0.0, 0.0). The path moves upwards, forming a concave down shape. At the point of inflection, the path continues upwards, forming a concave up shape. A label with the text First control point (p1x, p1y) appears above the path. Extending from the label is a dotted line pointing to the position (0.1, 0.75) on the graph. Another label with the text Second control point (p2x, p2y) appears below the path. A dotted line extends from the label to the (0.85, 0.35) position on the graph.](Animation-timingCurve-1)
///
/// The following code uses the timing curve from the previous
/// illustration to animate a ``Circle`` as its size changes.
///
/// struct ContentView: View {
/// @State private var scale = 1.0
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scaleEffect(scale)
/// .animation(
/// .timingCurve(0.1, 0.75, 0.85, 0.35, duration: 2.0),
/// value: scale)
///
/// Button("Animate") {
/// if scale == 1.0 {
/// scale = 0.25
/// } else {
/// scale = 1.0
/// }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-14-timing-curve.mp4", poster: "animation-14-timing-curve.png", alt: "A video that shows a circle shrinking then growing to its original size using a timing curve animation. The first control point of the time curve is (0.1, 0.75) and the second is (0.85, 0.35).")
///
/// - Parameters:
/// - p1x: The x-coordinate of the first control point of the cubic
/// Bézier curve.
/// - p1y: The y-coordinate of the first control point of the cubic
/// Bézier curve.
/// - p2x: The x-coordinate of the second control point of the cubic
/// Bézier curve.
/// - p2y: The y-coordinate of the second control point of the cubic
/// Bézier curve.
/// - duration: The length of time, expressed in seconds, the animation
/// takes to complete.
/// - Returns: A cubic Bézier timing curve animation.
public static func timingCurve(_ p1x: Double, _ p1y: Double, _ p2x: Double, _ p2y: Double, duration: TimeInterval = 0.35) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// A default animation instance.
///
/// The `default` animation is ``spring(response:dampingFraction:blendDuration:)``
/// with:
///
/// - `response` equal to `0.55`
/// - `dampingFraction` equal to `1.0`
/// - `blendDuration` equal to `0.0`
///
/// Prior to iOS 17, macOS 14, tvOS 17, and watchOS 10, the `default`
/// animation is ``easeInOut``.
///
/// The global function
/// ``withAnimation(_:_:)`` uses the default animation if you don't
/// provide one. For instance, the following code listing shows
/// an example of using the `default` animation to flip the text "Hello"
/// each time someone clicks the Animate button.
///
/// struct ContentView: View {
/// @State private var degrees = Double.zero
///
/// var body: some View {
/// VStack {
/// Spacer()
/// Text("Hello")
/// .font(.largeTitle)
/// .rotation3DEffect(.degrees(degrees), axis: (x: 0, y: 1, z: 0))
///
/// Spacer()
/// Button("Animate") {
/// withAnimation {
/// degrees = (degrees == .zero) ? 180 : .zero
/// }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-04-default-flip.mp4", poster: "animation-04-default-flip.png", alt: "A video that shows the word Hello flip horizontally so that its letters appear backwards. Then it flips in reverse so that the word Hello appears correctly.")
///
/// To use the `default` animation when adding the ``View/animation(_:value:)``
/// view modifier, specify it explicitly as the animation type. For
/// instance, the following code shows an example of the `default`
/// animation to spin the text "Hello" each time someone clicks the Animate
/// button.
///
/// struct ContentView: View {
/// @State private var degrees = Double.zero
///
/// var body: some View {
/// VStack {
/// Spacer()
/// Text("Hello")
/// .font(.largeTitle)
/// .rotationEffect(.degrees(degrees))
/// .animation(.default, value: degrees)
///
/// Spacer()
/// Button("Animate") {
/// degrees = (degrees == .zero) ? 360 : .zero
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-05-default-spin.mp4", poster: "animation-05-default-spin.png", alt: "A video that shows the word Hello spinning clockwise for one full rotation, that is, 360 degrees. Then Hello spins counterclockwise for one full rotation.")
///
/// A `default` animation instance is only equal to other `default`
/// animation instances (using `==`), and not equal to other animation
/// instances even when the animations are identical. For example, if you
/// create an animation using the ``spring(response:dampingFraction:blendDuration:)``
/// modifier with the same parameter values that `default` uses, the
/// animation isn't equal to `default`. This behavior lets you
/// differentiate between animations that you intentionally choose and
/// those that use the `default` animation.
public static let `default`: Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// An interpolating spring animation that uses a damped spring
/// model to produce values in the range [0, 1] that are then used
/// to interpolate within the [from, to] range of the animated
/// property. Preserves velocity across overlapping animations by
/// adding the effects of each animation.
///
/// - Parameters:
/// - mass: The mass of the object attached to the spring.
/// - stiffness: The stiffness of the spring.
/// - damping: The spring damping value.
/// - initialVelocity: the initial velocity of the spring, as
/// a value in the range [0, 1] representing the magnitude of
/// the value being animated.
/// - Returns: a spring animation.
public static func interpolatingSpring(mass: Double = 1.0, stiffness: Double, damping: Double, initialVelocity: Double = 0.0) -> Animation
/// An interpolating spring animation that uses a damped spring
/// model to produce values in the range [0, 1] that are then used
/// to interpolate within the [from, to] range of the animated
/// property. Preserves velocity across overlapping animations by
/// adding the effects of each animation.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - bounce: How bouncy the spring should be. A value of 0 indicates
/// no bounces (a critically damped spring), positive values indicate
/// increasing amounts of bounciness up to a maximum of 1.0
/// (corresponding to undamped oscillation), and negative values
/// indicate overdamped springs with a minimum value of -1.0.
/// - initialVelocity: the initial velocity of the spring, as
/// a value in the range [0, 1] representing the magnitude of
/// the value being animated.
/// - Returns: a spring animation.
public static func interpolatingSpring(duration: TimeInterval = 0.5, bounce: Double = 0.0, initialVelocity: Double = 0.0) -> Animation
/// An interpolating spring animation that uses a damped spring
/// model to produce values in the range [0, 1] that are then used
/// to interpolate within the [from, to] range of the animated
/// property. Preserves velocity across overlapping animations by
/// adding the effects of each animation.
///
/// This uses the default parameter values.
public static var interpolatingSpring: Animation { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// Delays the start of the animation by the specified number of seconds.
///
/// Use this method to delay the start of an animation. For example, the
/// following code animates the height change of two capsules.
/// Animation of the first ``Capsule`` begins immediately. However,
/// animation of the second one doesn't begin until a half second later.
///
/// struct ContentView: View {
/// @State private var adjustBy = 100.0
///
/// var body: some View {
/// VStack(spacing: 40) {
/// HStack(alignment: .bottom) {
/// Capsule()
/// .frame(width: 50, height: 175 - adjustBy)
/// .animation(.easeInOut, value: adjustBy)
/// Capsule()
/// .frame(width: 50, height: 175 + adjustBy)
/// .animation(.easeInOut.delay(0.5), value: adjustBy)
/// }
///
/// Button("Animate") {
/// adjustBy *= -1
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-15-delay.mp4", poster: "animation-15-delay.png", alt: "A video that shows two capsules side by side that animate using the ease-in ease-out animation. The capsule on the left is short, while the capsule on the right is tall. As they animate, the short capsule grows upwards to match the height of the tall capsule. Then the tall capsule shrinks to match the original height of the short capsule. Then the capsule on the left shrinks to its original height, followed by the capsule on the right growing to its original height.")
///
/// - Parameter delay: The number of seconds to delay the start of the
/// animation.
/// - Returns: An animation with a delayed start.
public func delay(_ delay: TimeInterval) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// Changes the duration of an animation by adjusting its speed.
///
/// Setting the speed of an animation changes the duration of the animation
/// by a factor of `speed`. A higher speed value causes a faster animation
/// sequence due to a shorter duration. For example, a one-second animation
/// with a speed of `2.0` completes in half the time (half a second).
///
/// struct ContentView: View {
/// @State private var adjustBy = 100.0
///
/// private var oneSecondAnimation: Animation {
/// .easeInOut(duration: 1.0)
/// }
///
/// var body: some View {
/// VStack(spacing: 40) {
/// HStack(alignment: .bottom) {
/// Capsule()
/// .frame(width: 50, height: 175 - adjustBy)
/// Capsule()
/// .frame(width: 50, height: 175 + adjustBy)
/// }
/// .animation(oneSecondAnimation.speed(2.0), value: adjustBy)
///
/// Button("Animate") {
/// adjustBy *= -1
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-18-speed.mp4", poster: "animation-18-speed.png", alt: "A video that shows two capsules side by side that animate using the ease-in ease-out animation. The capsule on the left is short, while the capsule on the right is tall. They animate for half a second with the short capsule growing upwards to match the height of the tall capsule. Then the tall capsule shrinks to match the original height of the short capsule. For another half second, the capsule on the left shrinks to its original height, followed by the capsule on the right growing to its original height.")
///
/// Setting `speed` to a lower number slows the animation, extending its
/// duration. For example, a one-second animation with a speed of `0.25`
/// takes four seconds to complete.
///
/// struct ContentView: View {
/// @State private var adjustBy = 100.0
///
/// private var oneSecondAnimation: Animation {
/// .easeInOut(duration: 1.0)
/// }
///
/// var body: some View {
/// VStack(spacing: 40) {
/// HStack(alignment: .bottom) {
/// Capsule()
/// .frame(width: 50, height: 175 - adjustBy)
/// Capsule()
/// .frame(width: 50, height: 175 + adjustBy)
/// }
/// .animation(oneSecondAnimation.speed(0.25), value: adjustBy)
///
/// Button("Animate") {
/// adjustBy *= -1
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-19-speed-slow.mp4", poster: "animation-19-speed-slow.png", alt: "A video that shows two capsules side by side that animate using the ease-in ease-out animation. The capsule on the left is short, while the right-side capsule is tall. They animate for four seconds with the short capsule growing upwards to match the height of the tall capsule. Then the tall capsule shrinks to match the original height of the short capsule. For another four seconds, the capsule on the left shrinks to its original height, followed by the capsule on the right growing to its original height.")
///
/// - Parameter speed: The speed at which SwiftUI performs the animation.
/// - Returns: An animation with the adjusted speed.
public func speed(_ speed: Double) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// A persistent spring animation. When mixed with other `spring()`
/// or `interactiveSpring()` animations on the same property, each
/// animation will be replaced by their successor, preserving
/// velocity from one animation to the next. Optionally blends the
/// duration values between springs over a time period.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - bounce: How bouncy the spring should be. A value of 0 indicates
/// no bounces (a critically damped spring), positive values indicate
/// increasing amounts of bounciness up to a maximum of 1.0
/// (corresponding to undamped oscillation), and negative values
/// indicate overdamped springs with a minimum value of -1.0.
/// - blendDuration: The duration in seconds over which to
/// interpolate changes to the duration.
/// - Returns: a spring animation.
public static func spring(duration: TimeInterval = 0.5, bounce: Double = 0.0, blendDuration: Double = 0) -> Animation
/// A persistent spring animation. When mixed with other `spring()`
/// or `interactiveSpring()` animations on the same property, each
/// animation will be replaced by their successor, preserving
/// velocity from one animation to the next. Optionally blends the
/// response values between springs over a time period.
///
/// - Parameters:
/// - response: The stiffness of the spring, defined as an
/// approximate duration in seconds. A value of zero requests
/// an infinitely-stiff spring, suitable for driving
/// interactive animations.
/// - dampingFraction: The amount of drag applied to the value
/// being animated, as a fraction of an estimate of amount
/// needed to produce critical damping.
/// - blendDuration: The duration in seconds over which to
/// interpolate changes to the response value of the spring.
/// - Returns: a spring animation.
public static func spring(response: Double = 0.5, dampingFraction: Double = 0.825, blendDuration: TimeInterval = 0) -> Animation
/// A persistent spring animation. When mixed with other `spring()`
/// or `interactiveSpring()` animations on the same property, each
/// animation will be replaced by their successor, preserving
/// velocity from one animation to the next. Optionally blends the
/// response values between springs over a time period.
///
/// This uses the default parameter values.
public static var spring: Animation { get }
/// A convenience for a `spring` animation with a lower
/// `response` value, intended for driving interactive animations.
public static func interactiveSpring(response: Double = 0.15, dampingFraction: Double = 0.86, blendDuration: TimeInterval = 0.25) -> Animation
/// A convenience for a `spring` animation with a lower
/// `duration` value, intended for driving interactive animations.
///
/// This uses the default parameter values.
public static var interactiveSpring: Animation { get }
/// A convenience for a `spring` animation with a lower
/// `response` value, intended for driving interactive animations.
public static func interactiveSpring(duration: TimeInterval = 0.15, extraBounce: Double = 0.0, blendDuration: TimeInterval = 0.25) -> Animation
/// A smooth spring animation with a predefined duration and no bounce.
public static var smooth: Animation { get }
/// A smooth spring animation with a predefined duration and no bounce
/// that can be tuned.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - extraBounce: How much additional bounce should be added to the base
/// bounce of 0.
/// - blendDuration: The duration in seconds over which to interpolate
/// changes to the duration.
public static func smooth(duration: TimeInterval = 0.5, extraBounce: Double = 0.0) -> Animation
/// A spring animation with a predefined duration and small amount of
/// bounce that feels more snappy.
public static var snappy: Animation { get }
/// A spring animation with a predefined duration and small amount of
/// bounce that feels more snappy and can be tuned.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - extraBounce: How much additional bounce should be added to the base
/// bounce of 0.15.
/// - blendDuration: The duration in seconds over which to interpolate
/// changes to the duration.
public static func snappy(duration: TimeInterval = 0.5, extraBounce: Double = 0.0) -> Animation
/// A spring animation with a predefined duration and higher amount of
/// bounce.
public static var bouncy: Animation { get }
/// A spring animation with a predefined duration and higher amount of
/// bounce that can be tuned.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - extraBounce: How much additional bounce should be added to the base
/// bounce of 0.3.
/// - blendDuration: The duration in seconds over which to interpolate
/// changes to the duration.
public static func bouncy(duration: TimeInterval = 0.5, extraBounce: Double = 0.0) -> Animation
}
/// The criteria that determines when an animation is considered finished.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct AnimationCompletionCriteria : Hashable, Sendable {
/// The animation has logically completed, but may still be in its long
/// tail.
///
/// If a subsequent change occurs that creates additional animations on
/// properties with `logicallyComplete` completion callbacks registered,
/// then those callbacks will fire when the animations from the change that
/// they were registered with logically complete, ignoring the new
/// animations.
public static let logicallyComplete: AnimationCompletionCriteria
/// The entire animation is finished and will now be removed.
///
/// If a subsequent change occurs that creates additional animations on
/// properties with `removed` completion callbacks registered, then those
/// callbacks will only fire when *all* of the created animations are
/// complete.
public static let removed: AnimationCompletionCriteria
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AnimationCompletionCriteria, b: AnimationCompletionCriteria) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// Contextual values that a custom animation can use to manage state and
/// access a view's environment.
///
/// The system provides an `AnimationContext` to a ``CustomAnimation`` instance
/// so that the animation can store and retrieve values in an instance of
/// ``AnimationState``. To access these values, use the context's
/// ``AnimationContext/state`` property.
///
/// For more convenient access to state, create an ``AnimationStateKey`` and
/// extend `AnimationContext` to include a computed property that gets and
/// sets the ``AnimationState`` value. Then use this property instead of
/// ``AnimationContext/state`` to retrieve the state of a custom animation. For
/// example, the following code creates an animation state key named
/// `PausableState`. Then the code extends `AnimationContext` to include the
/// `pausableState` property:
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// To access the pausable state, the custom animation `PausableAnimation` uses
/// the `pausableState` property instead of the ``AnimationContext/state``
/// property:
///
/// struct PausableAnimation: CustomAnimation {
/// let base: Animation
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
///
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// if pausableState.paused != paused {
/// pauseTime = time - pauseTime
/// context.pausableState = PausableState(paused: paused, pauseTime: pauseTime)
/// }
///
/// let effectiveTime = paused ? pauseTime : time - pauseTime
/// let result = base.animate(value: value, time: effectiveTime, context: &context)
/// return result
/// }
/// }
///
/// The animation can also retrieve environment values of the view that created
/// the animation. To retrieve a view's environment value, use the context's
/// ``AnimationContext/environment`` property. For instance, the following code
/// creates a custom ``EnvironmentKey`` named `AnimationPausedKey`, and the
/// view `PausableAnimationView` uses the key to store the paused state:
///
/// struct AnimationPausedKey: EnvironmentKey {
/// static let defaultValue = false
/// }
///
/// extension EnvironmentValues {
/// var animationPaused: Bool {
/// get { self[AnimationPausedKey.self] }
/// set { self[AnimationPausedKey.self] = newValue }
/// }
/// }
///
/// struct PausableAnimationView: View {
/// @State private var paused = false
///
/// var body: some View {
/// VStack {
/// ...
/// }
/// .environment(\.animationPaused, paused)
/// }
/// }
///
/// Then the custom animation `PausableAnimation` retrieves the paused state
/// from the view's environment using the ``AnimationContext/environment``
/// property:
///
/// struct PausableAnimation: CustomAnimation {
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
/// ...
/// }
/// }
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct AnimationContext<Value> where Value : VectorArithmetic {
/// The current state of a custom animation.
///
/// An instance of ``CustomAnimation`` uses this property to read and
/// write state values as the animation runs.
///
/// An alternative to using the `state` property in a custom animation is
/// to create an ``AnimationStateKey`` type and extend ``AnimationContext``
/// with a custom property that returns the state as a custom type. For
/// example, the following code creates a state key named `PausableState`.
/// It's convenient to store state values in the key type, so the
/// `PausableState` structure includes properties for the stored state
/// values `paused` and `pauseTime`.
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// To provide access the pausable state, the following code extends
/// `AnimationContext` to include the `pausableState` property. This
/// property returns an instance of the custom `PausableState` structure
/// stored in ``AnimationContext/state``, and it can also store a new
/// `PausableState` instance in `state`.
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// Now a custom animation can use the `pausableState` property instead of
/// the ``AnimationContext/state`` property as a convenient way to read and
/// write state values as the animation runs.
///
/// struct PausableAnimation: CustomAnimation {
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// ...
/// }
/// }
///
public var state: AnimationState<Value>
/// Set this to `true` to indicate that an animation is logically complete.
///
/// This controls when AnimationCompletionCriteria.logicallyComplete
/// completion callbacks are fired. This should be set to `true` at most
/// once in the life of an animation, changing back to `false` later will be
/// ignored. If this is never set to `true`, the behavior is equivalent to
/// if this had been set to `true` just as the animation finished (by
/// returning `nil`).
public var isLogicallyComplete: Bool
/// The current environment of the view that created the custom animation.
///
/// An instance of ``CustomAnimation`` uses this property to read
/// environment values from the view that created the animation. To learn
/// more about environment values including how to define custom
/// environment values, see ``EnvironmentValues``.
public var environment: EnvironmentValues { get }
/// Creates a new context from another one with a state that you provide.
///
/// Use this method to create a new context that contains the state that
/// you provide and view environment values from the original context.
///
/// - Parameter state: The initial state for the new context.
/// - Returns: A new context that contains the specified state.
public func withState<T>(_ state: AnimationState<T>) -> AnimationContext<T> where T : VectorArithmetic
}
/// A container that stores the state for a custom animation.
///
/// An ``AnimationContext`` uses this type to store state for a
/// ``CustomAnimation``. To retrieve the stored state of a context, you can
/// use the ``AnimationContext/state`` property. However, a more convenient
/// way to access the animation state is to define an ``AnimationStateKey``
/// and extend ``AnimationContext`` with a computed property that gets
/// and sets the animation state, as shown in the following code:
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// static var defaultValue: Self { .init() }
/// }
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// When creating an ``AnimationStateKey``, it's convenient to define the
/// state values that your custom animation needs. For example, the following
/// code adds the properties `paused` and `pauseTime` to the `PausableState`
/// animation state key:
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// To access the pausable state in a `PausableAnimation`, the follow code
/// calls `pausableState` instead of using the context's
/// ``AnimationContext/state`` property. And because the animation state key
/// `PausableState` defines properties for state values, the custom animation
/// can read and write those values.
///
/// struct PausableAnimation: CustomAnimation {
/// let base: Animation
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
///
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// if pausableState.paused != paused {
/// pauseTime = time - pauseTime
/// context.pausableState = PausableState(paused: paused, pauseTime: pauseTime)
/// }
///
/// let effectiveTime = paused ? pauseTime : time - pauseTime
/// let result = base.animate(value: value, time: effectiveTime, context: &context)
/// return result
/// }
/// }
///
/// ### Storing state for secondary animations
///
/// A custom animation can also use `AnimationState` to store the state of a
/// secondary animation. For example, the following code creates an
/// ``AnimationStateKey`` that includes the property `secondaryState`, which a
/// custom animation can use to store other state:
///
/// private struct TargetState<Value: VectorArithmetic>: AnimationStateKey {
/// var timeDelta = 0.0
/// var valueDelta = Value.zero
/// var secondaryState: AnimationState<Value>? = .init()
///
/// static var defaultValue: Self { .init() }
/// }
///
/// extension AnimationContext {
/// fileprivate var targetState: TargetState<Value> {
/// get { state[TargetState<Value>.self] }
/// set { state[TargetState<Value>.self] = newValue }
/// }
/// }
///
/// The custom animation `TargetAnimation` uses `TargetState` to store state
/// data in `secondaryState` for another animation that runs as part of the
/// target animation.
///
/// struct TargetAnimation: CustomAnimation {
/// var base: Animation
/// var secondary: Animation
///
/// func animate<V: VectorArithmetic>(value: V, time: Double, context: inout AnimationContext<V>) -> V? {
/// var targetValue = value
/// if let secondaryState = context.targetState.secondaryState {
/// var secondaryContext = context
/// secondaryContext.state = secondaryState
/// let secondaryValue = value - context.targetState.valueDelta
/// let result = secondary.animate(
/// value: secondaryValue, time: time - context.targetState.timeDelta,
/// context: &secondaryContext)
/// if let result = result {
/// context.targetState.secondaryState = secondaryContext.state
/// targetValue = result + context.targetState.valueDelta
/// } else {
/// context.targetState.secondaryState = nil
/// }
/// }
/// let result = base.animate(value: targetValue, time: time, context: &context)
/// if let result = result {
/// targetValue = result
/// } else if context.targetState.secondaryState == nil {
/// return nil
/// }
/// return targetValue
/// }
///
/// func shouldMerge<V: VectorArithmetic>(previous: Animation, value: V, time: Double, context: inout AnimationContext<V>) -> Bool {
/// guard let previous = previous.base as? Self else { return false }
/// var secondaryContext = context
/// if let secondaryState = context.targetState.secondaryState {
/// secondaryContext.state = secondaryState
/// context.targetState.valueDelta = secondary.animate(
/// value: value, time: time - context.targetState.timeDelta,
/// context: &secondaryContext) ?? value
/// } else {
/// context.targetState.valueDelta = value
/// }
/// // Reset the target each time a merge occurs.
/// context.targetState.secondaryState = .init()
/// context.targetState.timeDelta = time
/// return base.shouldMerge(
/// previous: previous.base, value: value, time: time,
/// context: &context)
/// }
/// }
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct AnimationState<Value> where Value : VectorArithmetic {
/// Create an empty state container.
///
/// You don't typically create an instance of ``AnimationState`` directly.
/// Instead, the ``AnimationContext`` provides the animation state to an
/// instance of ``CustomAnimation``.
public init()
/// Accesses the state for a custom key.
///
/// Create a custom animation state value by defining a key that conforms
/// to the ``AnimationStateKey`` protocol and provide the
/// ``AnimationStateKey/defaultValue`` for the key. Also include properties
/// to read and write state values that your ``CustomAnimation`` uses. For
/// example, the following code defines a key named `PausableState` that
/// has two state values, `paused` and `pauseTime`:
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// Use that key with the subscript operator of the ``AnimationState``
/// structure to get and set a value for the key. For more convenient
/// access to the key value, extend ``AnimationContext`` with a computed
/// property that gets and sets the key's value.
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// To access the state values in a ``CustomAnimation``, call the custom
/// computed property, then read and write the state values that the
/// custom ``AnimationStateKey`` provides.
///
/// struct PausableAnimation: CustomAnimation {
/// let base: Animation
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
///
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// if pausableState.paused != paused {
/// pauseTime = time - pauseTime
/// context.pausableState = PausableState(paused: paused, pauseTime: pauseTime)
/// }
///
/// let effectiveTime = paused ? pauseTime : time - pauseTime
/// let result = base.animate(value: value, time: effectiveTime, context: &context)
/// return result
/// }
/// }
public subscript<K>(key: K.Type) -> K.Value where K : AnimationStateKey
}
/// A key for accessing animation state values.
///
/// To access animation state from an ``AnimationContext`` in a custom
/// animation, create an `AnimationStateKey`. For example, the following
/// code creates an animation state key named `PausableState` and sets the
/// value for the required ``defaultValue`` property. The code also defines
/// properties for state values that the custom animation needs when
/// calculating animation values. Keeping the state values in the animation
/// state key makes it more convenient to read and write those values in the
/// implementation of a ``CustomAnimation``.
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// To make accessing the value of the animation state key more convenient,
/// define a property for it by extending ``AnimationContext``:
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// Then, you can read and write your state in an instance of `CustomAnimation`
/// using the ``AnimationContext``:
///
/// struct PausableAnimation: CustomAnimation {
/// let base: Animation
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
///
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// if pausableState.paused != paused {
/// pauseTime = time - pauseTime
/// context.pausableState = PausableState(paused: paused, pauseTime: pauseTime)
/// }
///
/// let effectiveTime = paused ? pauseTime : time - pauseTime
/// let result = base.animate(value: value, time: effectiveTime, context: &context)
/// return result
/// }
/// }
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public protocol AnimationStateKey {
/// The associated type representing the type of the animation state key's
/// value.
associatedtype Value
/// The default value for the animation state key.
static var defaultValue: Self.Value { get }
}
/// A pausable schedule of dates updating at a frequency no more quickly than
/// the provided interval.
///
/// You can also use ``TimelineSchedule/animation(minimumInterval:paused:)`` to
/// construct this schedule.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AnimationTimelineSchedule : TimelineSchedule, Sendable {
/// Create a pausable schedule of dates updating at a frequency no more
/// quickly than the provided interval.
///
/// - Parameters:
/// - minimumInterval: The minimum interval to update the schedule at.
/// Pass nil to let the system pick an appropriate update interval.
/// - paused: If the schedule should stop generating updates.
public init(minimumInterval: Double? = nil, paused: Bool = false)
/// Returns entries at the frequency of the animation schedule.
///
/// When in `.lowFrequency` mode, return no entries, effectively pausing the animation.
public func entries(from start: Date, mode: TimelineScheduleMode) -> AnimationTimelineSchedule.Entries
/// The sequence of dates within a schedule.
///
/// The ``TimelineSchedule/entries(from:mode:)`` method returns a value
/// of this type, which is a
/// <doc://com.apple.documentation/documentation/Swift/Sequence>
/// of dates in ascending order. A ``TimelineView`` that you create with a
/// schedule updates its content at the moments in time corresponding to
/// the dates included in the sequence.
public struct Entries : Sequence, IteratorProtocol, Sendable {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying sequence. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// You must not call this method if any other copy of this iterator has been
/// advanced with a call to its `next()` method.
///
/// The following example shows how an iterator can be used explicitly to
/// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and
/// then call the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence, if a next element
/// exists; otherwise, `nil`.
public mutating func next() -> Date?
/// A type representing the sequence's elements.
public typealias Element = Date
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
public typealias Iterator = AnimationTimelineSchedule.Entries
}
}
/// A type-erased gesture.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AnyGesture<Value> : Gesture {
/// Creates an instance from another gesture.
///
/// - Parameter gesture: A gesture that you use to create a new gesture.
public init<T>(_ gesture: T) where Value == T.Value, T : Gesture
/// The type of gesture representing the body of `Self`.
public typealias Body = Never
}
/// A color gradient.
///
/// When used as a ``ShapeStyle``, this type draws a linear gradient
/// with start-point [0.5, 0] and end-point [0.5, 1].
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@frozen public struct AnyGradient : Hashable, ShapeStyle, Sendable {
/// Creates a new instance from the specified gradient.
public init(_ gradient: Gradient)
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: AnyGradient, rhs: AnyGradient) -> Bool
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
public typealias Resolved = Never
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension AnyGradient {
/// Returns a version of the gradient that will use a specified
/// color space for interpolating between its colors.
///
/// Rectangle().fill(.linearGradient(
/// colors: [.white, .blue]).colorSpace(.perceptual))
///
/// - Parameters:
/// - space: The color space the new gradient will use to
/// interpolate its constituent colors.
///
/// - Returns: A new gradient that interpolates its colors in the
/// specified color space.
///
public func colorSpace(_ space: Gradient.ColorSpace) -> AnyGradient
}
/// A type-erased instance of the layout protocol.
///
/// Use an `AnyLayout` instance to enable dynamically changing the
/// type of a layout container without destroying the state of the subviews.
/// For example, you can create a layout that changes between horizontal and
/// vertical layouts based on the current Dynamic Type setting:
///
/// struct DynamicLayoutExample: View {
/// @Environment(\.dynamicTypeSize) var dynamicTypeSize
///
/// var body: some View {
/// let layout = dynamicTypeSize <= .medium ?
/// AnyLayout(HStackLayout()) : AnyLayout(VStackLayout())
///
/// layout {
/// Text("First label")
/// Text("Second label")
/// }
/// }
/// }
///
/// The types that you use with `AnyLayout` must conform to the ``Layout``
/// protocol. The above example chooses between the ``HStackLayout`` and
/// ``VStackLayout`` types, which are versions of the built-in ``HStack``
/// and ``VStack`` containers that conform to the protocol. You can also
/// use custom layout types that you define.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@frozen public struct AnyLayout : Layout {
/// Creates a type-erased value that wraps the specified layout.
///
/// You can switch between type-erased layouts without losing the state
/// of the subviews.
public init<L>(_ layout: L) where L : Layout
/// Cached values associated with the layout instance.
///
/// If you create a cache for your custom layout, you can use
/// a type alias to define this type as your data storage type.
/// Alternatively, you can refer to the data storage type directly in all
/// the places where you work with the cache.
///
/// See ``makeCache(subviews:)-23agy`` for more information.
public struct Cache {
}
/// The type defining the data to animate.
public typealias AnimatableData
/// Creates and initializes a cache for a layout instance.
///
/// You can optionally use a cache to preserve calculated values across
/// calls to a layout container's methods. Many layout types don't need
/// a cache, because SwiftUI automatically reuses both the results of
/// calls into the layout and the values that the layout reads from its
/// subviews. Rely on the protocol's default implementation of this method
/// if you don't need a cache.
///
/// However you might find a cache useful when:
///
/// - The layout container repeats complex, intermediate calculations
/// across calls like ``sizeThatFits(proposal:subviews:cache:)``,
/// ``placeSubviews(in:proposal:subviews:cache:)``, and
/// ``explicitAlignment(of:in:proposal:subviews:cache:)-8ofeu``.
/// You might be able to improve performance by calculating values
/// once and storing them in a cache.
/// - The layout container reads many ``LayoutValueKey`` values from
/// subviews. It might be more efficient to do that once and store the
/// results in the cache, rather than rereading the subviews' values before
/// each layout call.
/// - You want to maintain working storage, like temporary Swift arrays,
/// across calls into the layout, to minimize the number of allocation
/// events.
///
/// Only implement a cache if profiling shows that it improves performance.
///
/// ### Initialize a cache
///
/// Implement the `makeCache(subviews:)` method to create a cache.
/// You can add computed values to the cache right away, using information
/// from the `subviews` input parameter, or you can do that later. The
/// methods of the ``Layout`` protocol that can access the cache
/// take the cache as an in-out parameter, which enables you to modify
/// the cache anywhere that you can read it.
///
/// You can use any storage type that makes sense for your layout
/// algorithm, but be sure that you only store data that you derive
/// from the layout and its subviews (lazily, if possible). For this to
/// work correctly, SwiftUI needs to be able to call this method to
/// recreate the cache without changing the layout result.
///
/// When you return a cache from this method, you implicitly define a type
/// for your cache. Be sure to either make the type of the `cache`
/// parameters on your other ``Layout`` protocol methods match, or use
/// a type alias to define the ``Cache`` associated type.
///
/// ### Update the cache
///
/// If the layout container or any of its subviews change, SwiftUI
/// calls the ``updateCache(_:subviews:)-9hkj9`` method so you can
/// modify or invalidate the contents of the
/// cache. The default implementation of that method calls the
/// `makeCache(subviews:)` method to recreate the cache, but you can
/// provide your own implementation of the update method to take an
/// incremental approach, if appropriate.
///
/// - Parameters:
/// - subviews: A collection of proxy instances that represent the
/// views that the container arranges. You can use the proxies in the
/// collection to get information about the subviews as you
/// calculate values to store in the cache.
///
/// - Returns: Storage for calculated data that you share among
/// the methods of your custom layout container.
public func makeCache(subviews: AnyLayout.Subviews) -> AnyLayout.Cache
/// Updates the layout's cache when something changes.
///
/// If your custom layout container creates a cache by implementing the
/// ``makeCache(subviews:)-23agy`` method, SwiftUI calls the update method
/// when your layout or its subviews change, giving you an opportunity
/// to modify or invalidate the contents of the cache.
/// The method's default implementation recreates the
/// cache by calling the ``makeCache(subviews:)-23agy`` method,
/// but you can provide your own implementation to take an
/// incremental approach, if appropriate.
///
/// - Parameters:
/// - cache: Storage for calculated data that you share among
/// the methods of your custom layout container.
/// - subviews: A collection of proxy instances that represent the
/// views arranged by the container. You can use the proxies in the
/// collection to get information about the subviews as you
/// calculate values to store in the cache.
public func updateCache(_ cache: inout AnyLayout.Cache, subviews: AnyLayout.Subviews)
/// Returns the preferred spacing values of the composite view.
///
/// Implement this method to provide custom spacing preferences
/// for a layout container. The value you return affects
/// the spacing around the container, but it doesn't affect how the
/// container arranges subviews relative to one another inside the
/// container.
///
/// Create a custom ``ViewSpacing`` instance for your container by
/// initializing one with default values, and then merging that with
/// spacing instances of certain subviews. For example, if you define
/// a basic vertical stack that places subviews in a column, you could
/// use the spacing preferences of the subview edges that make
/// contact with the container's edges:
///
/// extension BasicVStack {
/// func spacing(subviews: Subviews, cache: inout ()) -> ViewSpacing {
/// var spacing = ViewSpacing()
///
/// for index in subviews.indices {
/// var edges: Edge.Set = [.leading, .trailing]
/// if index == 0 { edges.formUnion(.top) }
/// if index == subviews.count - 1 { edges.formUnion(.bottom) }
/// spacing.formUnion(subviews[index].spacing, edges: edges)
/// }
///
/// return spacing
/// }
/// }
///
/// In the above example, the first and last subviews contribute to the
/// spacing above and below the container, respectively, while all subviews
/// affect the spacing on the leading and trailing edges.
///
/// If you don't implement this method, the protocol provides a default
/// implementation, namely ``Layout/spacing(subviews:cache:)-1z0gt``,
/// that merges the spacing preferences across all subviews on all edges.
///
/// - Parameters:
/// - subviews: A collection of proxy instances that represent the
/// views that the container arranges. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// how much spacing the container prefers around it.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)-23agy`` for details.
///
/// - Returns: A ``ViewSpacing`` instance that describes the preferred
/// spacing around the container view.
public func spacing(subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache) -> ViewSpacing
/// Returns the size of the composite view, given a proposed size
/// and the view's subviews.
///
/// Implement this method to tell your custom layout container's parent
/// view how much space the container needs for a set of subviews, given
/// a size proposal. The parent might call this method more than once
/// during a layout pass with different proposed sizes to test the
/// flexibility of the container, using proposals like:
///
/// * The ``ProposedViewSize/zero`` proposal; respond with the
/// layout's minimum size.
/// * The ``ProposedViewSize/infinity`` proposal; respond with the
/// layout's maximum size.
/// * The ``ProposedViewSize/unspecified`` proposal; respond with the
/// layout's ideal size.
///
/// The parent might also choose to test flexibility in one dimension at a
/// time. For example, a horizontal stack might propose a fixed height and
/// an infinite width, and then the same height with a zero width.
///
/// The following example calculates the size for a basic vertical stack
/// that places views in a column, with no spacing between the views:
///
/// private struct BasicVStack: Layout {
/// func sizeThatFits(
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGSize {
/// subviews.reduce(CGSize.zero) { result, subview in
/// let size = subview.sizeThatFits(.unspecified)
/// return CGSize(
/// width: max(result.width, size.width),
/// height: result.height + size.height)
/// }
/// }
///
/// // This layout also needs a placeSubviews() implementation.
/// }
///
/// The implementation asks each subview for its ideal size by calling the
/// ``LayoutSubview/sizeThatFits(_:)`` method with an
/// ``ProposedViewSize/unspecified`` proposed size.
/// It then reduces these values into a single size that represents
/// the maximum subview width and the sum of subview heights.
/// Because this example isn't flexible, it ignores its size proposal
/// input and always returns the same value for a given set of subviews.
///
/// SwiftUI views choose their own size, so the layout engine always
/// uses a value that you return from this method as the actual size of the
/// composite view. That size factors into the construction of the `bounds`
/// input to the ``placeSubviews(in:proposal:subviews:cache:)`` method.
///
/// - Parameters:
/// - proposal: A size proposal for the container. The container's parent
/// view that calls this method might call the method more than once
/// with different proposals to learn more about the container's
/// flexibility before deciding which proposal to use for placement.
/// - subviews: A collection of proxies that represent the
/// views that the container arranges. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// how much space the container needs to display them.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)-23agy`` for details.
///
/// - Returns: A size that indicates how much space the container
/// needs to arrange its subviews.
public func sizeThatFits(proposal: ProposedViewSize, subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache) -> CGSize
/// Assigns positions to each of the layout's subviews.
///
/// SwiftUI calls your implementation of this method to tell your
/// custom layout container to place its subviews. From this method, call
/// the ``LayoutSubview/place(at:anchor:proposal:)`` method on each
/// element in `subviews` to tell the subviews where to appear in the
/// user interface.
///
/// For example, you can create a basic vertical stack that places views
/// in a column, with views horizontally aligned on their leading edge:
///
/// struct BasicVStack: Layout {
/// func placeSubviews(
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) {
/// var point = bounds.origin
/// for subview in subviews {
/// subview.place(at: point, anchor: .topLeading, proposal: .unspecified)
/// point.y += subview.dimensions(in: .unspecified).height
/// }
/// }
///
/// // This layout also needs a sizeThatFits() implementation.
/// }
///
/// The example creates a placement point that starts at the origin of the
/// specified `bounds` input and uses that to place the first subview. It
/// then moves the point in the y dimension by the subview's height,
/// which it reads using the ``LayoutSubview/dimensions(in:)`` method.
/// This prepares the point for the next iteration of the loop. All
/// subview operations use an ``ProposedViewSize/unspecified`` size
/// proposal to indicate that subviews should use and report their ideal
/// size.
///
/// A more complex layout container might add space between subviews
/// according to their ``LayoutSubview/spacing`` preferences, or a
/// fixed space based on input configuration. For example, you can extend
/// the basic vertical stack's placement method to calculate the
/// preferred distances between adjacent subviews and store the results in
/// an array:
///
/// let spacing: [CGFloat] = subviews.indices.dropLast().map { index in
/// subviews[index].spacing.distance(
/// to: subviews[index + 1].spacing,
/// along: .vertical)
/// }
///
/// The spacing's ``ViewSpacing/distance(to:along:)`` method considers the
/// preferences of adjacent views on the edge where they meet. It returns
/// the smallest distance that satisfies both views' preferences for the
/// given edge. For example, if one view prefers at least `2` points on its
/// bottom edge, and the next view prefers at least `8` points on its top
/// edge, the distance method returns `8`, because that's the smallest
/// value that satisfies both preferences.
///
/// Update the placement calculations to use the spacing values:
///
/// var point = bounds.origin
/// for (index, subview) in subviews.enumerated() {
/// if index > 0 { point.y += spacing[index - 1] } // Add spacing.
/// subview.place(at: point, anchor: .topLeading, proposal: .unspecified)
/// point.y += subview.dimensions(in: .unspecified).height
/// }
///
/// Be sure that you use computations during placement that are consistent
/// with those in your implementation of other protocol methods for a given
/// set of inputs. For example, if you add spacing during placement,
/// make sure your implementation of
/// ``sizeThatFits(proposal:subviews:cache:)`` accounts for the extra space.
/// Similarly, if the sizing method returns different values for different
/// size proposals, make sure the placement method responds to its
/// `proposal` input in the same way.
///
/// - Parameters:
/// - bounds: The region that the container view's parent allocates to the
/// container view, specified in the parent's coordinate space.
/// Place all the container's subviews within the region.
/// The size of this region matches a size that your container
/// previously returned from a call to the
/// ``sizeThatFits(proposal:subviews:cache:)`` method.
/// - proposal: The size proposal from which the container generated the
/// size that the parent used to create the `bounds` parameter.
/// The parent might propose more than one size before calling the
/// placement method, but it always uses one of the proposals and the
/// corresponding returned size when placing the container.
/// - subviews: A collection of proxies that represent the
/// views that the container arranges. Use the proxies in the collection
/// to get information about the subviews and to tell the subviews
/// where to appear.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)-23agy`` for details.
public func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache)
/// Returns the position of the specified horizontal alignment guide along
/// the x axis.
///
/// Implement this method to return a value for the specified alignment
/// guide of a custom layout container. The value you return affects
/// the placement of the container as a whole, but it doesn't affect how the
/// container arranges subviews relative to one another.
///
/// You can use this method to put an alignment guide in a nonstandard
/// position. For example, you can indent the container's leading edge
/// alignment guide by 10 points:
///
/// extension BasicVStack {
/// func explicitAlignment(
/// of guide: HorizontalAlignment,
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGFloat? {
/// if guide == .leading {
/// return bounds.minX + 10
/// }
/// return nil
/// }
/// }
///
/// The above example returns `nil` for other guides to indicate that they
/// don't have an explicit value. A guide without an explicit value behaves
/// as it would for any other view. If you don't implement the
/// method, the protocol's default implementation merges the
/// subviews' guides.
///
/// - Parameters:
/// - guide: The ``HorizontalAlignment`` guide that the method calculates
/// the position of.
/// - bounds: The region that the container view's parent allocates to the
/// container view, specified in the parent's coordinate space.
/// - proposal: A proposed size for the container.
/// - subviews: A collection of proxy instances that represent the
/// views arranged by the container. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// where to place the guide.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)-23agy`` for details.
///
/// - Returns: The guide's position relative to the `bounds`.
/// Return `nil` to indicate that the guide doesn't have an explicit
/// value.
public func explicitAlignment(of guide: HorizontalAlignment, in bounds: CGRect, proposal: ProposedViewSize, subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache) -> CGFloat?
/// Returns the position of the specified vertical alignment guide along
/// the y axis.
///
/// Implement this method to return a value for the specified alignment
/// guide of a custom layout container. The value you return affects
/// the placement of the container as a whole, but it doesn't affect how the
/// container arranges subviews relative to one another.
///
/// You can use this method to put an alignment guide in a nonstandard
/// position. For example, you can raise the container's bottom edge
/// alignment guide by 10 points:
///
/// extension BasicVStack {
/// func explicitAlignment(
/// of guide: VerticalAlignment,
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGFloat? {
/// if guide == .bottom {
/// return bounds.minY - 10
/// }
/// return nil
/// }
/// }
///
/// The above example returns `nil` for other guides to indicate that they
/// don't have an explicit value. A guide without an explicit value behaves
/// as it would for any other view. If you don't implement the
/// method, the protocol's default implementation merges the
/// subviews' guides.
///
/// - Parameters:
/// - guide: The ``VerticalAlignment`` guide that the method calculates
/// the position of.
/// - bounds: The region that the container view's parent allocates to the
/// container view, specified in the parent's coordinate space.
/// - proposal: A proposed size for the container.
/// - subviews: A collection of proxy instances that represent the
/// views arranged by the container. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// where to place the guide.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)-23agy`` for details.
///
/// - Returns: The guide's position relative to the `bounds`.
/// Return `nil` to indicate that the guide doesn't have an explicit
/// value.
public func explicitAlignment(of guide: VerticalAlignment, in bounds: CGRect, proposal: ProposedViewSize, subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache) -> CGFloat?
/// The data to animate.
public var animatableData: AnyLayout.AnimatableData
}
/// A type-erased shape value.
///
/// 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()))
/// }
/// }
///
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@frozen public struct AnyShape : Shape, @unchecked Sendable {
/// Create an any shape instance from a shape.
public init<S>(_ shape: S) where S : Shape
/// Describes this shape as a path within a rectangular frame of reference.
///
/// - Parameter rect: The frame of reference for describing this shape.
///
/// - Returns: A path that describes this shape.
public func path(in rect: CGRect) -> Path
/// Returns the size of the view that will render the shape, given
/// a proposed size.
///
/// Implement this method to tell the container of the shape how
/// much space the shape needs to render itself, given a size
/// proposal.
///
/// See ``Layout/sizeThatFits(proposal:subviews:cache:)``
/// for more details about how the layout system chooses the size of
/// views.
///
/// - Parameters:
/// - proposal: A size proposal for the container.
///
/// - Returns: A size that indicates how much space the shape needs.
public func sizeThatFits(_ proposal: ProposedViewSize) -> CGSize
/// The type defining the data to animate.
public typealias AnimatableData
/// The data to animate.
public var animatableData: AnyShape.AnimatableData
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body
}
/// A type-erased ShapeStyle value.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public struct AnyShapeStyle : ShapeStyle {
/// Create an instance from `style`.
public init<S>(_ style: S) where S : ShapeStyle
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
public typealias Resolved = Never
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AnyShapeStyle.Storage : @unchecked Sendable {
}
/// A type-erased transition.
///
/// - See Also: `Transition`
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AnyTransition {
/// Create an instance that type-erases `transition`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public init<T>(_ transition: T) where T : Transition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// A transition that inserts by moving in from the leading edge, and
/// removes by moving out towards the trailing edge.
///
/// - SeeAlso: `AnyTransition.move(edge:)`
public static var slide: AnyTransition { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension AnyTransition {
/// Creates a transition that when added to a view will animate the
/// view's insertion by moving it in from the specified edge while
/// fading it in, and animate its removal by moving it out towards
/// the opposite edge and fading it out.
///
/// - Parameters:
/// - edge: the edge from which the view will be animated in.
///
/// - Returns: A transition that animates a view by moving and
/// fading it.
public static func push(from edge: Edge) -> AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
public static func offset(_ offset: CGSize) -> AnyTransition
public static func offset(x: CGFloat = 0, y: CGFloat = 0) -> AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// Returns a transition that scales the view.
public static var scale: AnyTransition { get }
/// Returns a transition that scales the view by the specified amount.
public static func scale(scale: CGFloat, anchor: UnitPoint = .center) -> AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// A transition from transparent to opaque on insertion, and from opaque to
/// transparent on removal.
public static let opacity: AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// Combines this transition with another, returning a new transition that
/// is the result of both transitions being applied.
public func combined(with other: AnyTransition) -> AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// Returns a transition defined between an active modifier and an identity
/// modifier.
public static func modifier<E>(active: E, identity: E) -> AnyTransition where E : ViewModifier
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// A transition that returns the input view, unmodified, as the output
/// view.
public static let identity: AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// Returns a transition that moves the view away, towards the specified
/// edge of the view.
public static func move(edge: Edge) -> AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// Provides a composite transition that uses a different transition for
/// insertion versus removal.
public static func asymmetric(insertion: AnyTransition, removal: AnyTransition) -> AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// Attaches an animation to this transition.
public func animation(_ animation: Animation?) -> AnyTransition
}
/// A type-erased view.
///
/// 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.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AnyView : View {
/// Create an instance that type-erases `view`.
public init<V>(_ view: V) where V : View
public init<V>(erasing view: V) where V : View
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A type that represents the structure and behavior of an app.
///
/// Create an app by declaring a structure that conforms to the `App` protocol.
/// Implement the required ``SwiftUI/App/body-swift.property`` 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](https://docs.swift.org/swift-book/ReferenceManual/Attributes.html#ID626)
/// attribute to indicate that your custom `App` protocol conformer provides the
/// entry point into your app. The protocol provides a default implementation of
/// the ``SwiftUI/App/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 ``SwiftUI/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 ``SwiftUI/StateObject`` attribute to initialize a
/// data model, and then provide that model on a view input as an
/// ``SwiftUI/ObservedObject`` or through the environment as an
/// ``SwiftUI/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.
/// }
/// }
/// }
///
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public protocol App {
/// The type of scene representing the content of the app.
///
/// When you create a custom app, Swift infers this type from your
/// implementation of the required ``SwiftUI/App/body-swift.property``
/// property.
associatedtype Body : Scene
/// The content and behavior of the app.
///
/// For any app that you create, provide a computed `body` property that
/// defines your app's scenes, which are instances that conform to the
/// ``SwiftUI/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 ``SwiftUI/App/Body-swift.associatedtype``
/// associated type based on the scene provided by the `body` property.
@SceneBuilder @MainActor var body: Self.Body { get }
/// Creates an instance of the app using the body that you define for its
/// content.
///
/// Swift synthesizes a default initializer for structures that don't
/// provide one. You typically rely on the default initializer for
/// your app.
@MainActor init()
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension App {
/// Initializes and runs the app.
///
/// If you precede your ``SwiftUI/App`` conformer's declaration with the
/// [@main](https://docs.swift.org/swift-book/ReferenceManual/Attributes.html#ID626)
/// 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.
@MainActor public static func main()
}
/// A property wrapper type that reflects a value from `UserDefaults` and
/// invalidates a view on a change in value in that user default.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@frozen @propertyWrapper public struct AppStorage<Value> : DynamicProperty {
public var wrappedValue: Value { get nonmutating set }
public var projectedValue: Binding<Value> { get }
}
@available(iOS 17.0, macOS 14.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension AppStorage {
/// Creates a property that can save and restore table column state.
///
/// Table column state is typically not bound from a table directly to
/// `AppStorage`, but instead indirecting through `State` or `SceneStorage`,
/// and using the app storage value as its initial value kept up to date
/// on changes to the direct backing.
///
/// - Parameters:
/// - wrappedValue: The default value if table column state is not
/// available for the given key.
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init<RowValue>(wrappedValue: Value = TableColumnCustomization<RowValue>(), _ key: String, store: UserDefaults? = nil) where Value == TableColumnCustomization<RowValue>, RowValue : Identifiable
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension AppStorage {
/// Creates a property that can read and write to a boolean user default.
///
/// - Parameters:
/// - wrappedValue: The default value if a boolean value is not specified
/// for the given key.
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) where Value == Bool
/// Creates a property that can read and write to an integer user default.
///
/// - Parameters:
/// - wrappedValue: The default value if an integer value is not specified
/// for the given key.
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) where Value == Int
/// Creates a property that can read and write to a double user default.
///
/// - Parameters:
/// - wrappedValue: The default value if a double value is not specified
/// for the given key.
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) where Value == Double
/// Creates a property that can read and write to a string user default.
///
/// - Parameters:
/// - wrappedValue: The default value if a string value is not specified
/// for the given key.
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) where Value == String
/// Creates a property that can read and write to a url user default.
///
/// - Parameters:
/// - wrappedValue: The default value if a url value is not specified for
/// the given key.
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) where Value == URL
/// Creates a property that can read and write to a user default as data.
///
/// Avoid storing large data blobs in user defaults, such as image data,
/// as it can negatively affect performance of your app. On tvOS, a
/// `NSUserDefaultsSizeLimitExceededNotification` notification is posted
/// if the total user default size reaches 512kB.
///
/// - Parameters:
/// - wrappedValue: The default value if a data value is not specified for
/// the given key.
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) where Value == Data
/// Creates a property that can read and write to an integer user default,
/// transforming that to `RawRepresentable` data type.
///
/// A common usage is with enumerations:
///
/// enum MyEnum: Int {
/// case a
/// case b
/// case c
/// }
/// struct MyView: View {
/// @AppStorage("MyEnumValue") private var value = MyEnum.a
/// var body: some View { ... }
/// }
///
/// - Parameters:
/// - wrappedValue: The default value if an integer value
/// is not specified for the given key.
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) where Value : RawRepresentable, Value.RawValue == Int
/// Creates a property that can read and write to a string user default,
/// transforming that to `RawRepresentable` data type.
///
/// A common usage is with enumerations:
///
/// enum MyEnum: String {
/// case a
/// case b
/// case c
/// }
/// struct MyView: View {
/// @AppStorage("MyEnumValue") private var value = MyEnum.a
/// var body: some View { ... }
/// }
///
/// - Parameters:
/// - wrappedValue: The default value if a string value
/// is not specified for the given key.
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) where Value : RawRepresentable, Value.RawValue == String
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension AppStorage where Value : ExpressibleByNilLiteral {
/// Creates a property that can read and write an Optional boolean user
/// default.
///
/// Defaults to nil if there is no restored value.
///
/// - Parameters:
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(_ key: String, store: UserDefaults? = nil) where Value == Bool?
/// Creates a property that can read and write an Optional integer user
/// default.
///
/// Defaults to nil if there is no restored value.
///
/// - Parameters:
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(_ key: String, store: UserDefaults? = nil) where Value == Int?
/// Creates a property that can read and write an Optional double user
/// default.
///
/// Defaults to nil if there is no restored value.
///
/// - Parameters:
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(_ key: String, store: UserDefaults? = nil) where Value == Double?
/// Creates a property that can read and write an Optional string user
/// default.
///
/// Defaults to nil if there is no restored value.
///
/// - Parameters:
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(_ key: String, store: UserDefaults? = nil) where Value == String?
/// Creates a property that can read and write an Optional URL user
/// default.
///
/// Defaults to nil if there is no restored value.
///
/// - Parameters:
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(_ key: String, store: UserDefaults? = nil) where Value == URL?
/// Creates a property that can read and write an Optional data user
/// default.
///
/// Defaults to nil if there is no restored value.
///
/// - Parameters:
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init(_ key: String, store: UserDefaults? = nil) where Value == Data?
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AppStorage {
/// Creates a property that can save and restore an Optional string,
/// transforming it to an Optional `RawRepresentable` data type.
///
/// Defaults to nil if there is no restored value
///
/// A common usage is with enumerations:
///
/// enum MyEnum: String {
/// case a
/// case b
/// case c
/// }
/// struct MyView: View {
/// @AppStorage("MyEnumValue") private var value: MyEnum?
/// var body: some View { ... }
/// }
///
/// - Parameters:
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init<R>(_ key: String, store: UserDefaults? = nil) where Value == R?, R : RawRepresentable, R.RawValue == String
/// Creates a property that can save and restore an Optional integer,
/// transforming it to an Optional `RawRepresentable` data type.
///
/// Defaults to nil if there is no restored value
///
/// A common usage is with enumerations:
///
/// enum MyEnum: Int {
/// case a
/// case b
/// case c
/// }
/// struct MyView: View {
/// @AppStorage("MyEnumValue") private var value: MyEnum?
/// var body: some View { ... }
/// }
///
/// - Parameters:
/// - key: The key to read and write the value to in the user defaults
/// store.
/// - store: The user defaults store to read and write to. A value
/// of `nil` will use the user default store from the environment.
public init<R>(_ key: String, store: UserDefaults? = nil) where Value == R?, R : RawRepresentable, R.RawValue == Int
}
/// A composite `Transition` that uses a different transition for
/// insertion versus removal.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct AsymmetricTransition<Insertion, Removal> : Transition where Insertion : Transition, Removal : Transition {
/// The `Transition` defining the insertion phase of `self`.
public var insertion: Insertion
/// The `Transition` defining the removal phase of `self`.
public var removal: Removal
/// Creates a composite `Transition` that uses a different transition for
/// insertion versus removal.
public init(insertion: Insertion, removal: Removal)
/// Gets the current body of the caller.
///
/// `content` is a proxy for the view that will have the modifier
/// represented by `Self` applied to it.
public func body(content: AsymmetricTransition<Insertion, Removal>.Content, phase: TransitionPhase) -> some View
/// Returns the properties this transition type has.
///
/// Defaults to `TransitionProperties()`.
public static var properties: TransitionProperties { get }
/// The type of view representing the body.
public typealias Body = some View
}
/// A view that asynchronously loads and displays an image.
///
/// This view uses the shared
/// <doc://com.apple.documentation/documentation/Foundation/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.
///
/// ![A diagram that shows a grey box on the left, the SwiftUI icon on the
/// right, and an arrow pointing from the first to the second. The icon
/// is about half the size of the grey box.](AsyncImage-1)
///
/// 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:
///
/// ![A diagram that shows a progress view on the left, the SwiftUI icon on the
/// right, and an arrow pointing from the first to the second.](AsyncImage-2)
///
/// > Important: You can't apply image-specific modifiers, like
/// ``Image/resizable(capInsets:resizingMode:)``, directly to an `AsyncImage`.
/// Instead, apply them to the ``Image`` instance that your `content`
/// closure gets when defining the view's appearance.
///
/// 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.
/// }
/// }
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AsyncImage<Content> : View where Content : View {
/// Loads and displays an image from the specified URL.
///
/// Until the image loads, SwiftUI displays a default placeholder. When
/// the load operation completes successfully, SwiftUI updates the
/// view to show the loaded image. If the operation fails, SwiftUI
/// continues to display the placeholder. The following example loads
/// and displays an icon from an example server:
///
/// AsyncImage(url: URL(string: "https://example.com/icon.png"))
///
/// If you want to customize the placeholder or apply image-specific
/// modifiers --- like ``Image/resizable(capInsets:resizingMode:)`` ---
/// to the loaded image, use the ``init(url:scale:content:placeholder:)``
/// initializer instead.
///
/// - Parameters:
/// - url: The URL of the image to display.
/// - scale: The scale to use for the image. The default is `1`. Set a
/// different value when loading images designed for higher resolution
/// displays. For example, set a value of `2` for an image that you
/// would name with the `@2x` suffix if stored in a file on disk.
public init(url: URL?, scale: CGFloat = 1) where Content == Image
/// Loads and displays a modifiable image from the specified URL using
/// a custom placeholder until the image loads.
///
/// Until the image loads, SwiftUI displays the placeholder view that
/// you specify. When the load operation completes successfully, SwiftUI
/// updates the view to show content that you specify, which you
/// create using the loaded image. For example, you can show a green
/// placeholder, followed by a tiled version of the loaded image:
///
/// AsyncImage(url: URL(string: "https://example.com/icon.png")) { image in
/// image.resizable(resizingMode: .tile)
/// } placeholder: {
/// Color.green
/// }
///
/// If the load operation fails, SwiftUI continues to display the
/// placeholder. To be able to display a different view on a load error,
/// use the ``init(url:scale:transaction:content:)`` initializer instead.
///
/// - Parameters:
/// - url: The URL of the image to display.
/// - scale: The scale to use for the image. The default is `1`. Set a
/// different value when loading images designed for higher resolution
/// displays. For example, set a value of `2` for an image that you
/// would name with the `@2x` suffix if stored in a file on disk.
/// - content: A closure that takes the loaded image as an input, and
/// returns the view to show. You can return the image directly, or
/// modify it as needed before returning it.
/// - placeholder: A closure that returns the view to show until the
/// load operation completes successfully.
public init<I, P>(url: URL?, scale: CGFloat = 1, @ViewBuilder content: @escaping (Image) -> I, @ViewBuilder placeholder: @escaping () -> P) where Content == _ConditionalContent<I, P>, I : View, P : View
/// Loads and displays a modifiable image from the specified URL in phases.
///
/// If you set the asynchronous image's URL to `nil`, or after you set the
/// URL to a value but before the load operation completes, the phase is
/// ``AsyncImagePhase/empty``. After the operation completes, the phase
/// becomes either ``AsyncImagePhase/failure(_:)`` or
/// ``AsyncImagePhase/success(_:)``. In the first case, the phase's
/// ``AsyncImagePhase/error`` value indicates the reason for failure.
/// In the second case, the phase's ``AsyncImagePhase/image`` property
/// contains the loaded image. Use the phase to drive the output of the
/// `content` closure, which defines the view's appearance:
///
/// 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.
/// }
/// }
///
/// To add transitions when you change the URL, apply an identifier to the
/// ``AsyncImage``.
///
/// - Parameters:
/// - url: The URL of the image to display.
/// - scale: The scale to use for the image. The default is `1`. Set a
/// different value when loading images designed for higher resolution
/// displays. For example, set a value of `2` for an image that you
/// would name with the `@2x` suffix if stored in a file on disk.
/// - transaction: The transaction to use when the phase changes.
/// - content: A closure that takes the load phase as an input, and
/// returns the view to display for the specified phase.
public init(url: URL?, scale: CGFloat = 1, transaction: Transaction = Transaction(), @ViewBuilder content: @escaping (AsyncImagePhase) -> Content)
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
/// The current phase of the asynchronous image loading operation.
///
/// When you create an ``AsyncImage`` instance with the
/// ``AsyncImage/init(url:scale:transaction:content:)`` initializer, you define
/// the appearance of the view using a `content` closure. SwiftUI calls the
/// closure with a phase value at different points during the load operation
/// to indicate the current state. Use the phase to decide what to draw.
/// For example, you can draw the loaded image if it exists, a view that
/// indicates an error, or a placeholder:
///
/// 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.
/// }
/// }
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public enum AsyncImagePhase : Sendable {
/// No image is loaded.
case empty
/// An image succesfully loaded.
case success(Image)
/// An image failed to load with an error.
case failure(Error)
/// The loaded image, if any.
///
/// If this value isn't `nil`, the image load operation has finished,
/// and you can use the image to update the view. You can use the image
/// directly, or you can modify it in some way. For example, you can add
/// a ``Image/resizable(capInsets:resizingMode:)`` modifier to make the
/// image resizable.
public var image: Image? { get }
/// The error that occurred when attempting to load an image, if any.
public var error: (Error)? { get }
}
/// The default control group style.
///
/// You can also use ``ControlGroupStyle/automatic`` to construct this style.
@available(iOS 15.0, macOS 12.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public struct AutomaticControlGroupStyle : ControlGroupStyle {
/// Creates a view representing the body of a control group.
///
/// - Parameter configuration: The properties of the control group instance
/// being created.
///
/// This method will be called for each instance of ``ControlGroup`` created
/// within a view hierarchy where this style is the current
/// `ControlGroupStyle`.
@MainActor public func makeBody(configuration: AutomaticControlGroupStyle.Configuration) -> some View
/// A view representing the body of a control group.
public typealias Body = some View
}
/// A disclosure group style that resolves its appearance automatically
/// based on the current context.
///
/// Use ``DisclosureGroupStyle/automatic`` to construct this style.
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct AutomaticDisclosureGroupStyle : DisclosureGroupStyle {
/// Creates an automatic disclosure group style.
public init()
/// Creates a view that represents the body of a disclosure group.
///
/// SwiftUI calls this method for each instance of ``DisclosureGroup``
/// that you create within a view hierarchy where this style is the current
/// ``DisclosureGroupStyle``.
///
/// - Parameter configuration: The properties of the instance being created.
public func makeBody(configuration: AutomaticDisclosureGroupStyle.Configuration) -> some View
/// A view that represents the body of a disclosure group.
public typealias Body = some View
}
/// The default form style.
///
/// Use the ``FormStyle/automatic`` static variable to create this style:
///
/// Form {
/// ...
/// }
/// .formStyle(.automatic)
///
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct AutomaticFormStyle : FormStyle {
/// Creates a default form style.
///
/// Don't call this initializer directly. Instead, use the
/// ``FormStyle/automatic`` static variable to create this style:
///
/// Form {
/// ...
/// }
/// .formStyle(.automatic)
///
public init()
/// Creates a view that represents the body of a form.
///
/// - Parameter configuration: The properties of the form.
/// - Returns: A view that has behavior and appearance that enables it
/// to function as a ``Form``.
public func makeBody(configuration: AutomaticFormStyle.Configuration) -> some View
/// A view that represents the appearance and interaction of a form.
public typealias Body = some View
}
/// The default labeled content style.
///
/// Use ``LabeledContentStyle/automatic`` to construct this style.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct AutomaticLabeledContentStyle : LabeledContentStyle {
/// Creates an automatic labeled content style.
public init()
/// Creates a view that represents the body of labeled content.
public func makeBody(configuration: AutomaticLabeledContentStyle.Configuration) -> some View
/// A view that represents the appearance and behavior of labeled content.
public typealias Body = some View
}
/// The default menu bar extra style.
/// You can also use ``MenuBarExtraStyle/automatic`` to construct this style.
@available(macOS 13.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct AutomaticMenuBarExtraStyle : MenuBarExtraStyle {
/// Creates an automatic menu bar extra style.
public init()
}
/// A navigation split style that resolves its appearance automatically
/// based on the current context.
///
/// Use ``NavigationSplitViewStyle/automatic`` to construct this style.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct AutomaticNavigationSplitViewStyle : NavigationSplitViewStyle {
/// Creates an instance of the automatic navigation split view style.
///
/// Use ``NavigationSplitViewStyle/automatic`` to construct this style.
public init()
/// Creates a view that represents the body of a navigation split view.
///
/// SwiftUI calls this method for each instance of ``NavigationSplitView``,
/// where this style is the current ``NavigationSplitViewStyle``.
///
/// - Parameter configuration: The properties of the instance to create.
public func makeBody(configuration: AutomaticNavigationSplitViewStyle.Configuration) -> some View
/// A view that represents the body of a navigation split view.
public typealias Body = some View
}
/// The default table style in the current context.
///
/// You can also use ``TableStyle/automatic`` to construct this style.
@available(iOS 16.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct AutomaticTableStyle : TableStyle {
/// Creates a view that represents the body of a table.
///
/// The system calls this method for each ``Table`` instance in a view
/// hierarchy where this style is the current table style.
///
/// - Parameter configuration: The properties of the table.
public func makeBody(configuration: AutomaticTableStyle.Configuration) -> some View
/// A view that represents the body of a table.
public typealias Body = some View
}
/// The default text editor style, based on the text editor's context.
///
/// You can also use ``TextEditorStyle/automatic`` to construct this style.
@available(iOS 17.0, macOS 14.0, visionOS 1.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct AutomaticTextEditorStyle : TextEditorStyle {
/// Creates a view that represents the body of a text editor.
///
/// The system calls this method for each ``TextEditor`` instance in a view
/// hierarchy where this style is the current text editor style.
///
/// - Parameter configuration: The properties of the text editor.
public func makeBody(configuration: AutomaticTextEditorStyle.Configuration) -> AutomaticTextEditorStyle.Body
public init()
/// A view that represents the body of a text editor.
public struct Body : View {
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
}
/// The horizontal or vertical dimension in a 2D coordinate system.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public enum Axis : Int8, CaseIterable {
/// The horizontal dimension.
case horizontal
/// The vertical dimension.
case vertical
/// An efficient set of axes.
@frozen public struct Set : OptionSet {
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = Axis.Set
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public let rawValue: Int8
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
public init(rawValue: Int8)
public static let horizontal: Axis.Set
public static let vertical: Axis.Set
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = Axis.Set.Element
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = Int8
}
/// Creates a new instance with the specified raw value.
///
/// If there is no value of the type that corresponds with the specified raw
/// value, this initializer returns `nil`. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// print(PaperSize(rawValue: "Legal"))
/// // Prints "Optional("PaperSize.Legal")"
///
/// print(PaperSize(rawValue: "Tabloid"))
/// // Prints "nil"
///
/// - Parameter rawValue: The raw value to use for the new instance.
public init?(rawValue: Int8)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [Axis]
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = Int8
/// A collection of all values of this type.
public static var allCases: [Axis] { get }
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public var rawValue: Int8 { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : CustomStringConvertible {
/// A textual representation of this instance.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(describing:)`
/// initializer. This initializer works with any type, and uses the custom
/// `description` property for types that conform to
/// `CustomStringConvertible`:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : Hashable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : RawRepresentable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : Sendable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis.Set : Sendable {
}
/// The prominence of backgrounds underneath other views.
///
/// Background prominence should influence foreground styling to maintain
/// sufficient contrast against the background. For example, selected rows in
/// a `List` and `Table` can have increased prominence backgrounds with
/// accent color fills when focused; the foreground content above the background
/// should be adjusted to reflect that level of prominence.
///
/// This can be read and written for views with the
/// `EnvironmentValues.backgroundProminence` property.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct BackgroundProminence : Hashable, Sendable {
/// The standard prominence of a background
///
/// This is the default level of prominence and doesn't require any
/// adjustment to achieve satisfactory contrast with the background.
public static let standard: BackgroundProminence
/// A more prominent background that likely requires some changes to the
/// views above it.
///
/// This is the level of prominence for more highly saturated and full
/// color backgrounds, such as focused/emphasized selected list rows.
/// Typically foreground content should take on monochrome styling to
/// have greater contrast against the background.
public static let increased: BackgroundProminence
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: BackgroundProminence, b: BackgroundProminence) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// The background style in the current context.
///
/// You can also use ``ShapeStyle/background`` to construct this style.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@frozen public struct BackgroundStyle : ShapeStyle {
/// Creates a background style instance.
@inlinable public init()
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
public typealias Resolved = Never
}
/// The kinds of background tasks that your app or extension can handle.
///
/// Use a value of this type with the ``Scene/backgroundTask(_:action:)`` scene
/// modifier to create a handler for background tasks that the system sends
/// to your app or extension. For example, you can use ``urlSession`` to define
/// an asynchronous closure that the system calls when it launches your app or
/// extension to handle a response from a background
/// <doc://com.apple.documentation/documentation/Foundation/URLSession>.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct BackgroundTask<Request, Response> : Sendable {
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension BackgroundTask {
/// A task that responds to background URL sessions.
public static var urlSession: BackgroundTask<String, Void> { get }
/// A task that responds to background URL sessions matching the given
/// identifier.
///
/// - Parameter identifier: The identifier to match.
///
/// - Returns: A background task that you can handle with your app or
/// extension.
public static func urlSession(_ identifier: String) -> BackgroundTask<Void, Void>
/// A task that responds to background URL sessions matching the given
/// predicate.
///
/// - Parameter matching: The predicate to match.
///
/// - Returns: A background task that you can handle with your app or
/// extension.
public static func urlSession(matching: @escaping @Sendable (String) -> Bool) -> BackgroundTask<String, Void>
}
/// The visual prominence of a badge.
///
/// Badges can be used for different kinds of information, from the
/// passive number of items in a container to the number of required
/// actions. The prominence of badges in Lists can be adjusted to reflect
/// this and be made to draw more or less attention to themselves.
///
/// Badges will default to `standard` prominence unless specified.
///
/// The following example shows a ``List`` displaying a list of folders
/// with an informational badge with lower prominence, showing the number
/// of items in the folder.
///
/// List(folders) { folder in
/// Text(folder.name)
/// .badge(folder.numberOfItems)
/// }
/// .badgeProminence(.decreased)
///
@available(iOS 17.0, macOS 14.0, *)
@available(watchOS, unavailable)
@available(tvOS, unavailable)
public struct BadgeProminence : Hashable, Sendable {
/// The lowest level of prominence for a badge.
///
/// This level or prominence should be used for badges that display a value
/// of passive information that requires no user action, such as total
/// number of messages or content.
///
/// In lists on iOS and macOS, this results in badge labels being
/// displayed without any extra decoration. On iOS, this looks the same as
/// `.standard`.
///
/// List(folders) { folder in
/// Text(folder.name)
/// .badge(folder.numberOfItems)
/// }
/// .badgeProminence(.decreased)
///
public static let decreased: BadgeProminence
/// The standard level of prominence for a badge.
///
/// This level of prominence should be used for badges that display a value
/// that suggests user action, such as a count of unread messages or new
/// invitations.
///
/// In lists on macOS, this results in a badge label on a grayscale platter;
/// and in lists on iOS, this prominence of badge has no platter.
///
/// List(mailboxes) { mailbox in
/// Text(mailbox.name)
/// .badge(mailbox.numberOfUnreadMessages)
/// }
/// .badgeProminence(.standard)
///
public static let standard: BadgeProminence
/// The highest level of prominence for a badge.
///
/// This level of prominence should be used for badges that display a value
/// that requires user action, such as number of updates or account errors.
///
/// In lists on iOS and macOS, this results in badge labels being displayed
/// on a red platter.
///
/// ForEach(accounts) { account in
/// Text(account.userName)
/// .badge(account.setupErrors)
/// .badgeProminence(.increased)
/// }
///
public static let increased: BadgeProminence
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: BadgeProminence, b: BadgeProminence) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A navigation split style that reduces the size of the detail content
/// to make room when showing the leading column or columns.
///
/// Use ``NavigationSplitViewStyle/balanced`` to construct this style.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct BalancedNavigationSplitViewStyle : NavigationSplitViewStyle {
/// Creates an instance of ``BalancedNavigationSplitViewStyle``.
///
/// You can also use ``NavigationSplitViewStyle/balanced`` to construct this
/// style.
public init()
/// Creates a view that represents the body of a navigation split view.
///
/// SwiftUI calls this method for each instance of ``NavigationSplitView``,
/// where this style is the current ``NavigationSplitViewStyle``.
///
/// - Parameter configuration: The properties of the instance to create.
public func makeBody(configuration: BalancedNavigationSplitViewStyle.Configuration) -> some View
/// A view that represents the body of a navigation split view.
public typealias Body = some View
}
/// A property wrapper type that supports creating bindings to the mutable
/// properties of observable objects.
///
/// Use this property wrapper to create bindings to mutable properties of a
/// data model object that conforms to the
/// <doc://com.apple.documentation/documentation/Observation/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 <doc://com.apple.documentation/documentation/Observation/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 ``View/body-swift.property``:
///
/// 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)
/// }
/// }
///
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@dynamicMemberLookup @propertyWrapper public struct Bindable<Value> {
/// The wrapped object.
public var wrappedValue: Value
/// The bindable wrapper for the object that creates bindings to its
/// properties using dynamic member lookup.
public var projectedValue: Bindable<Value> { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Bindable where Value : AnyObject {
/// Returns a binding to the value of a given key path.
public subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<Value, Subject>) -> Binding<Subject> { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Bindable where Value : AnyObject, Value : Observable {
/// Creates a bindable object from an observable object.
///
/// You should not call this initializer directly. Instead, declare a
/// property with the `@Bindable` attribute, and provide an initial value.
public init(wrappedValue: Value)
/// Creates a bindable object from an observable object.
///
/// This initializer is equivalent to ``init(wrappedValue:)``, but is more
/// succinct when when creating bindable objects nested within other
/// expressions. For example, you can use the initializer to create a
/// bindable object inline with code that declares a view that takes a
/// binding as a parameter:
///
/// struct TitleEditView: View {
/// @Environment(Book.self) private var book
///
/// var body: some View {
/// TextField("Title", text: Bindable(book).title)
/// }
/// }
///
public init(_ wrappedValue: Value)
/// Creates a bindable from the value of another bindable.
public init(projectedValue: Bindable<Value>)
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Bindable : Identifiable where Value : Identifiable {
/// The stable identity of the entity associated with this instance.
public var id: Value.ID { get }
/// A type representing the stable identity of the entity associated with
/// an instance.
public typealias ID = Value.ID
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Bindable : Sendable where Value : Sendable {
}
/// A property wrapper type that can read and write a value owned by a source of
/// truth.
///
/// 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 ``State/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.
///
/// > Note: To create bindings to properties of a type that conforms to the
/// <doc://com.apple.documentation/documentation/Observation/Observable>
/// protocol, use the ``Bindable`` property wrapper. For more information,
/// see <doc:Migrating-from-the-observable-object-protocol-to-the-observable-macro>.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen @propertyWrapper @dynamicMemberLookup public struct Binding<Value> {
/// The binding's transaction.
///
/// The transaction captures the information needed to update the view when
/// the binding value changes.
public var transaction: Transaction
/// Creates a binding with closures that read and write the binding value.
///
/// - Parameters:
/// - get: A closure that retrieves the binding value. The closure has no
/// parameters, and returns a value.
/// - set: A closure that sets the binding value. The closure has the
/// following parameter:
/// - newValue: The new value of the binding value.
public init(get: @escaping () -> Value, set: @escaping (Value) -> Void)
/// Creates a binding with a closure that reads from the binding value, and
/// a closure that applies a transaction when writing to the binding value.
///
/// - Parameters:
/// - get: A closure to retrieve the binding value. The closure has no
/// parameters, and returns a value.
/// - set: A closure to set the binding value. The closure has the
/// following parameters:
/// - newValue: The new value of the binding value.
/// - transaction: The transaction to apply when setting a new value.
public init(get: @escaping () -> Value, set: @escaping (Value, Transaction) -> Void)
/// Creates a binding with an immutable value.
///
/// Use this method to create a binding to a value that cannot change.
/// This can be useful when using a ``PreviewProvider`` to see how a view
/// represents different values.
///
/// // Example of binding to an immutable value.
/// PlayButton(isPlaying: Binding.constant(true))
///
/// - Parameter value: An immutable value.
public static func constant(_ value: Value) -> Binding<Value>
/// The underlying value referenced by the binding variable.
///
/// This property provides primary access to the value's data. However, you
/// don't access `wrappedValue` directly. Instead, you use the property
/// variable created with the ``Binding`` attribute. In the
/// following code example, the binding variable `isPlaying` returns the
/// value of `wrappedValue`:
///
/// struct PlayButton: View {
/// @Binding var isPlaying: Bool
///
/// var body: some View {
/// Button(isPlaying ? "Pause" : "Play") {
/// isPlaying.toggle()
/// }
/// }
/// }
///
/// When a mutable binding value changes, the new value is immediately
/// available. However, updates to a view displaying the value happens
/// asynchronously, so the view may not show the change immediately.
public var wrappedValue: Value { get nonmutating set }
/// A projection of the binding value that returns a binding.
///
/// Use the projected value to pass a binding value down a view hierarchy.
/// To get the `projectedValue`, prefix the property variable with `$`. For
/// example, in the following code example `PlayerView` projects a binding
/// of the state property `isPlaying` to the `PlayButton` view using
/// `$isPlaying`.
///
/// 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)
/// }
/// }
/// }
///
public var projectedValue: Binding<Value> { get }
/// Creates a binding from the value of another binding.
public init(projectedValue: Binding<Value>)
/// Returns a binding to the resulting value of a given key path.
///
/// - Parameter keyPath: A key path to a specific resulting value.
///
/// - Returns: A new binding.
public subscript<Subject>(dynamicMember keyPath: WritableKeyPath<Value, Subject>) -> Binding<Subject> { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Binding {
/// Creates a binding by projecting the base value to an optional value.
///
/// - Parameter base: A value to project to an optional value.
public init<V>(_ base: Binding<V>) where Value == V?
/// Creates a binding by projecting the base value to an unwrapped value.
///
/// - Parameter base: A value to project to an unwrapped value.
///
/// - Returns: A new binding or `nil` when `base` is `nil`.
public init?(_ base: Binding<Value?>)
/// Creates a binding by projecting the base value to a hashable value.
///
/// - Parameters:
/// - base: A `Hashable` value to project to an `AnyHashable` value.
public init<V>(_ base: Binding<V>) where Value == AnyHashable, V : Hashable
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Binding : Identifiable where Value : Identifiable {
/// The stable identity of the entity associated with this instance,
/// corresponding to the `id` of the binding's wrapped value.
public var id: Value.ID { get }
/// A type representing the stable identity of the entity associated with
/// an instance.
public typealias ID = Value.ID
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Binding : Sequence where Value : MutableCollection {
/// A type representing the sequence's elements.
public typealias Element = Binding<Value.Element>
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
public typealias Iterator = IndexingIterator<Binding<Value>>
/// A collection representing a contiguous subrange of this collection's
/// elements. The subsequence shares indices with the original collection.
///
/// The default subsequence type for collections that don't define their own
/// is `Slice`.
public typealias SubSequence = Slice<Binding<Value>>
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Binding : Collection where Value : MutableCollection {
/// A type that represents a position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript
/// argument.
public typealias Index = Value.Index
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
public typealias Indices = Value.Indices
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
public var startIndex: Binding<Value>.Index { get }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.firstIndex(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
public var endIndex: Binding<Value>.Index { get }
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be nonuniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can result in an unexpected copy of the collection. To avoid
/// the unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
public var indices: Value.Indices { get }
/// Returns the position immediately after the given index.
///
/// The successor of an index must be well defined. For an index `i` into a
/// collection `c`, calling `c.index(after: i)` returns the same index every
/// time.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Binding<Value>.Index) -> Binding<Value>.Index
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
public func formIndex(after i: inout Binding<Value>.Index)
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
///
/// - Complexity: O(1)
public subscript(position: Binding<Value>.Index) -> Binding<Value>.Element { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Binding : BidirectionalCollection where Value : BidirectionalCollection, Value : MutableCollection {
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
public func index(before i: Binding<Value>.Index) -> Binding<Value>.Index
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
public func formIndex(before i: inout Binding<Value>.Index)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Binding : RandomAccessCollection where Value : MutableCollection, Value : RandomAccessCollection {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Binding {
/// Specifies a transaction for the binding.
///
/// - Parameter transaction : An instance of a ``Transaction``.
///
/// - Returns: A new binding.
public func transaction(_ transaction: Transaction) -> Binding<Value>
/// Specifies an animation to perform when the binding value changes.
///
/// - Parameter animation: An animation sequence performed when the binding
/// value changes.
///
/// - Returns: A new binding.
public func animation(_ animation: Animation? = .default) -> Binding<Value>
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Binding : DynamicProperty {
}
/// Modes for compositing a view with overlapping content.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum BlendMode : Sendable {
case normal
case multiply
case screen
case overlay
case darken
case lighten
case colorDodge
case colorBurn
case softLight
case hardLight
case difference
case exclusion
case hue
case saturation
case color
case luminosity
case sourceAtop
case destinationOver
case destinationOut
case plusDarker
case plusLighter
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: BlendMode, b: BlendMode) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension BlendMode : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension BlendMode : Hashable {
}
/// A menu style that displays a bordered button that toggles the display of the
/// menu's contents when pressed.
///
/// Use ``MenuStyle/borderedButton`` to construct this style.
@available(iOS, unavailable)
@available(macOS, introduced: 11.0, deprecated: 100000.0, message: "Use .menuStyle(.button) and .buttonStyle(.bordered).")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct BorderedButtonMenuStyle : MenuStyle {
/// Creates a bordered button menu style.
public init()
/// Creates a view that represents the body of a menu.
///
/// - Parameter configuration: The properties of the menu.
///
/// The system calls this method for each ``Menu`` instance in a view
/// hierarchy where this style is the current menu style.
public func makeBody(configuration: BorderedButtonMenuStyle.Configuration) -> some View
/// A view that represents the body of a menu.
public typealias Body = some View
}
/// A button style that applies standard border artwork based on the button's
/// context.
///
/// You can also use ``PrimitiveButtonStyle/bordered`` to construct this style.
@available(iOS 15.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
public struct BorderedButtonStyle : PrimitiveButtonStyle {
/// Creates a bordered button style.
public init()
/// Creates a view that represents the body of a button.
///
/// The system calls this method for each ``Button`` instance in a view
/// hierarchy where this style is the current button style.
///
/// - Parameter configuration: The properties of the button.
public func makeBody(configuration: BorderedButtonStyle.Configuration) -> some View
/// A view that represents the body of a button.
public typealias Body = some View
}
/// The list style that describes the behavior and appearance of a list with
/// standard border.
///
/// You can also use ``ListStyle/bordered`` to construct this style.
@available(macOS 12.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct BorderedListStyle : ListStyle {
/// Creates a bordered list style.
public init()
/// Creates a bordered list style with optional alternating row backgrounds.
@available(macOS, introduced: 12.0, deprecated: 100000.0, message: "Use the `.bordered` style with the `.alternatingRowBackgrounds()` view modifier")
public init(alternatesRowBackgrounds: Bool)
}
/// A button style that applies standard border prominent artwork based
/// on the button's context.
///
/// Use ``PrimitiveButtonStyle/borderedProminent`` to construct this style.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct BorderedProminentButtonStyle : PrimitiveButtonStyle {
/// Creates a bordered prominent button style.
public init()
/// Creates a view that represents the body of a button.
///
/// The system calls this method for each ``Button`` instance in a view
/// hierarchy where this style is the current button style.
///
/// - Parameter configuration : The properties of the button.
public func makeBody(configuration: BorderedProminentButtonStyle.Configuration) -> some View
/// A view that represents the body of a button.
public typealias Body = some View
}
/// The table style that describes the behavior and appearance of a table with
/// standard border.
///
/// You can also use ``TableStyle/bordered`` to construct this style.
@available(macOS 12.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct BorderedTableStyle : TableStyle {
/// Creates a default bordered table style, with alternating row
/// backgrounds.
public init()
/// Creates a bordered table style with optional alternating row
/// backgrounds.
@available(macOS, introduced: 12.0, deprecated: 100000.0, message: "Use the `.bordered` style with the `.alternatingRowBackgrounds()` view modifier")
public init(alternatesRowBackgrounds: Bool)
/// Creates a view that represents the body of a table.
///
/// The system calls this method for each ``Table`` instance in a view
/// hierarchy where this style is the current table style.
///
/// - Parameter configuration: The properties of the table.
public func makeBody(configuration: BorderedTableStyle.Configuration) -> some View
/// A view that represents the body of a table.
public typealias Body = some View
}
/// A menu button style which manifests as a borderless button with no
/// visual embelishments.
@available(iOS, unavailable)
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `BorderlessButtonMenuStyle` instead.")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct BorderlessButtonMenuButtonStyle : MenuButtonStyle {
public init()
}
/// A menu style that displays a borderless button that toggles the display of
/// the menu's contents when pressed.
///
/// Use ``MenuStyle/borderlessButton`` to construct this style.
@available(iOS, introduced: 14.0, deprecated: 100000.0, message: "Use .menuStyle(.button) and .buttonStyle(.borderless).")
@available(macOS, introduced: 11.0, deprecated: 100000.0, message: "Use .menuStyle(.button) and .buttonStyle(.borderless).")
@available(tvOS, introduced: 17.0, deprecated: 100000.0, message: "Use .menuStyle(.button) and .buttonStyle(.borderless).")
@available(watchOS, unavailable)
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use .menuStyle(.button) and .buttonStyle(.borderless).")
public struct BorderlessButtonMenuStyle : MenuStyle {
/// Creates a borderless button menu style.
public init()
/// Creates a borderless button menu style, specifying whether to show a
/// visual menu indicator.
///
/// - Parameter showsMenuIndicator: A Boolean that indicates whether the
/// button should include a visual indicator that it represents a menu,
/// such as an arrow.
@available(iOS, unavailable)
@available(macOS, introduced: 11.0, deprecated: 12.0, message: "Use ``View/menuIndicator(_)`` instead.")
@available(visionOS, unavailable)
public init(showsMenuIndicator: Bool)
/// Creates a view that represents the body of a menu.
///
/// - Parameter configuration: The properties of the menu.
///
/// The system calls this method for each ``Menu`` instance in a view
/// hierarchy where this style is the current menu style.
public func makeBody(configuration: BorderlessButtonMenuStyle.Configuration) -> some View
/// A view that represents the body of a menu.
public typealias Body = some View
}
/// A button style that doesn't apply a border.
///
/// You can also use ``PrimitiveButtonStyle/borderless`` to construct this
/// style.
@available(iOS 13.0, macOS 10.15, tvOS 17.0, watchOS 8.0, *)
public struct BorderlessButtonStyle : PrimitiveButtonStyle {
/// Creates a borderless button style.
public init()
/// Creates a view that represents the body of a button.
///
/// The system calls this method for each ``Button`` instance in a view
/// hierarchy where this style is the current button style.
///
/// - Parameter configuration : The properties of the button.
public func makeBody(configuration: BorderlessButtonStyle.Configuration) -> some View
/// A view that represents the body of a button.
public typealias Body = some View
}
/// A menu button style which manifests as a borderless pull-down button.
@available(iOS, unavailable)
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `BorderlessButtonMenuStyle` instead.")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct BorderlessPullDownMenuButtonStyle : MenuButtonStyle {
public init()
}
/// A control that initiates an action.
///
/// You create a button by providing an action and a label. The action is either
/// a method or closure property that does something when a user clicks or taps
/// the button. The label is a view that describes the button's action --- for
/// example, by showing text, an icon, or both.
///
/// The label of a button can be any kind of view, such as a ``Text`` view for
/// text-only labels:
///
/// Button(action: signIn) {
/// Text("Sign In")
/// }
///
/// Or a ``Label`` view, for buttons with both a title and an icon:
///
/// Button(action: signIn) {
/// Label("Sign In", systemImage: "arrow.up")
/// }
///
/// For those common cases, you can also use the convenience initializers that
/// take a title string or ``LocalizedStringKey`` as their first parameter, and
/// optionally a system image name or `ImageResource` as their second parameter,
/// instead of a trailing closure:
///
/// Button("Sign In", systemImage: "arrow.up", action: signIn)
///
/// Prefer to use these convenience initializers, or a ``Label`` view, when
/// providing both a title and an icon. This allows the button to dynamically
/// adapt its appearance to render its title and icon correctly in containers
/// such as toolbars and menus. For example, on iOS, buttons only display their
/// icons by default when placed in toolbars, but show both a leading title and
/// trailing icon in menus. Defining labels this way also helps with
/// accessibility --- for example, applying the ``View/labelStyle(_:)`` modifier
/// with an ``LabelStyle/iconOnly`` style to the button will cause it to only
/// visually display its icon, but still use its title to describe the button in
/// accessibility modes like VoiceOver:
///
/// Button("Sign In", systemImage: "arrow.up", action: signIn)
/// .labelStyle(.iconOnly)
///
/// Avoid labels that only use images or exclusively visual components without
/// an accessibility label.
///
/// How the user activates the button varies by platform:
/// - In iOS and watchOS, the user taps the button.
/// - In macOS, the user clicks the button.
/// - In tvOS, the user presses "select" on an
/// external remote, like the Siri Remote, while focusing on the button.
///
/// The appearance of the button depends on factors like where you
/// place it, whether you assign it a role, and how you style it.
///
/// ### Adding buttons to containers
///
/// Use buttons for any user interface element that initiates an action.
/// Buttons automatically adapt their visual style to match the expected style
/// within these different containers and contexts. For example, to create a
/// ``List`` cell that initiates an action when selected by the user, add a
/// button to the list's content:
///
/// List {
/// // Cells that show all the current folders.
/// ForEach(folders) { folder in
/// Text(folder.title)
/// }
///
/// // A cell that, when selected, adds a new folder.
/// Button(action: addItem) {
/// Label("Add Folder", systemImage: "folder.badge.plus")
/// }
/// }
///
/// ![A screenshot of a list of four items. The first three items use a
/// grayscale foreground color and have the text Documents, Downloads,
/// and Recents. The last item has a blue foreground color and shows
/// a folder icon with the text Add Folder.](Button-1)
///
/// Similarly, to create a context menu item that initiates an action, add a
/// button to the ``View/contextMenu(_:)`` modifier's content closure:
///
/// .contextMenu {
/// Button("Cut", action: cut)
/// Button("Copy", action: copy)
/// Button("Paste", action: paste)
/// }
///
/// ![A screenshot of a context menu that contains the three items Cut, Copy,
/// and Paste.](Button-2)
///
/// This pattern extends to most other container views in SwiftUI that have
/// customizable, interactive content, like ``Form`` instances.
///
/// ### Assigning a role
///
/// You can optionally initialize a button with a ``ButtonRole`` that
/// characterizes the button's purpose. For example, you can create a
/// ``ButtonRole/destructive`` button for a deletion action:
///
/// Button("Delete", role: .destructive, action: delete)
///
/// The system uses the button's role to style the button appropriately
/// in every context. For example, a destructive button in a contextual menu
/// appears with a red foreground color:
///
/// ![A screenshot of a context menu that contains the four items Cut, Copy,
/// Paste, and Delete. The last item uses a foreground color of red.](Button-3)
///
/// If you don't specify a role for a button, the system applies an
/// appropriate default appearance.
///
/// ### Styling buttons
///
/// You can customize a button's appearance using one of the standard button
/// styles, like ``PrimitiveButtonStyle/bordered``, and apply the style with the
/// ``View/buttonStyle(_:)-66fbx`` modifier:
///
/// HStack {
/// Button("Sign In", action: signIn)
/// Button("Register", action: register)
/// }
/// .buttonStyle(.bordered)
///
/// If you apply the style to a container view, as in the example above,
/// all the buttons in the container use the style:
///
/// ![A screenshot of two buttons, side by side, each with a capsule shaped
/// background. The label for the first button is Sign In; the right button is
/// Register.](Button-4)
///
/// You can also create custom styles. To add a custom appearance with
/// standard interaction behavior, create a style that conforms to the
/// ``ButtonStyle`` protocol. To customize both appearance and interaction
/// behavior, create a style that conforms to the ``PrimitiveButtonStyle``
/// protocol. Custom styles can also read the button's role and use it to
/// adjust the button's appearance.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct Button<Label> : View where Label : View {
/// Creates a button that displays a custom label.
///
/// - Parameters:
/// - action: The action to perform when the user triggers the button.
/// - label: A view that describes the purpose of the button's `action`.
public init(action: @escaping () -> Void, @ViewBuilder label: () -> Label)
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Button where Label == Text {
/// Creates a button that generates its label from a localized string key.
///
/// This initializer creates a ``Text`` view on your behalf, and treats the
/// localized key similar to ``Text/init(_:tableName:bundle:comment:)``. See
/// ``Text`` for more information about localizing strings.
///
/// To initialize a button with a string variable, use
/// ``Button/init(_:action:)-lpm7`` instead.
///
/// - Parameters:
/// - titleKey: The key for the button's localized title, that describes
/// the purpose of the button's `action`.
/// - action: The action to perform when the user triggers the button.
public init(_ titleKey: LocalizedStringKey, action: @escaping () -> Void)
/// Creates a button that generates its label from a string.
///
/// This initializer creates a ``Text`` view on your behalf, and treats the
/// title similar to ``Text/init(_:)-9d1g4``. See ``Text`` for more
/// information about localizing strings.
///
/// To initialize a button with a localized string key, use
/// ``Button/init(_:action:)-1asy`` instead.
///
/// - Parameters:
/// - title: A string that describes the purpose of the button's `action`.
/// - action: The action to perform when the user triggers the button.
public init<S>(_ title: S, action: @escaping () -> Void) where S : StringProtocol
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Button where Label == Label<Text, Image> {
/// Creates a button that generates its label from a localized string key
/// and system image name.
///
/// This initializer creates a ``Label`` view on your behalf, and treats the
/// localized key similar to ``Text/init(_:tableName:bundle:comment:)``. See
/// ``Text`` for more information about localizing strings.
///
/// - Parameters:
/// - titleKey: The key for the button's localized title, that describes
/// the purpose of the button's `action`.
/// - systemImage: The name of the image resource to lookup.
/// - action: The action to perform when the user triggers the button.
public init(_ titleKey: LocalizedStringKey, systemImage: String, action: @escaping () -> Void)
/// Creates a button that generates its label from a string and
/// system image name.
///
/// This initializer creates a ``Label`` view on your behalf, and treats the
/// title similar to ``Text/init(_:)-9d1g4``. See ``Text`` for more
/// information about localizing strings.
///
/// - Parameters:
/// - title: A string that describes the purpose of the button's `action`.
/// - systemImage: The name of the image resource to lookup.
/// - action: The action to perform when the user triggers the button.
public init<S>(_ title: S, systemImage: String, action: @escaping () -> Void) where S : StringProtocol
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Button where Label == Label<Text, Image> {
/// Creates a button that generates its label from a localized string key
/// and image resource.
///
/// This initializer creates a ``Label`` view on your behalf, and treats the
/// localized key similar to ``Text/init(_:tableName:bundle:comment:)``. See
/// ``Text`` for more information about localizing strings.
///
/// - Parameters:
/// - titleKey: The key for the button's localized title, that describes
/// the purpose of the button's `action`.
/// - image: The image resource to lookup.
/// - action: The action to perform when the user triggers the button.
public init(_ titleKey: LocalizedStringKey, image: ImageResource, action: @escaping () -> Void)
/// Creates a button that generates its label from a string and
/// image resource.
///
/// This initializer creates a ``Label`` view on your behalf, and treats the
/// title similar to ``Text/init(_:)-9d1g4``. See ``Text`` for more
/// information about localizing strings.
///
/// - Parameters:
/// - title: A string that describes the purpose of the button's `action`.
/// - image: The image resource to lookup.
/// - action: The action to perform when the user triggers the button.
public init<S>(_ title: S, image: ImageResource, action: @escaping () -> Void) where S : StringProtocol
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Button where Label == PrimitiveButtonStyleConfiguration.Label {
/// Creates a button based on a configuration for a style with a custom
/// appearance and custom interaction behavior.
///
/// Use this initializer within the
/// ``PrimitiveButtonStyle/makeBody(configuration:)`` method of a
/// ``PrimitiveButtonStyle`` to create an instance of the button that you
/// want to style. This is useful for custom button styles that modify the
/// current button style, rather than implementing a brand new style.
///
/// For example, the following style adds a red border around the button,
/// but otherwise preserves the button's current style:
///
/// struct RedBorderedButtonStyle: PrimitiveButtonStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// Button(configuration)
/// .border(Color.red)
/// }
/// }
///
/// - Parameter configuration: A configuration for a style with a custom
/// appearance and custom interaction behavior.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public init(_ configuration: PrimitiveButtonStyleConfiguration)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Button {
/// Creates a button with a specified role that displays a custom label.
///
/// - Parameters:
/// - role: An optional semantic role that describes the button. A value of
/// `nil` means that the button doesn't have an assigned role.
/// - action: The action to perform when the user interacts with the button.
/// - label: A view that describes the purpose of the button's `action`.
public init(role: ButtonRole?, action: @escaping () -> Void, @ViewBuilder label: () -> Label)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Button where Label == Text {
/// Creates a button with a specified role that generates its label from a
/// localized string key.
///
/// This initializer creates a ``Text`` view on your behalf, and treats the
/// localized key similar to ``Text/init(_:tableName:bundle:comment:)``. See
/// ``Text`` for more information about localizing strings.
///
/// To initialize a button with a string variable, use
/// ``init(_:role:action:)-8y5yk`` instead.
///
/// - Parameters:
/// - titleKey: The key for the button's localized title, that describes
/// the purpose of the button's `action`.
/// - role: An optional semantic role describing the button. A value of
/// `nil` means that the button doesn't have an assigned role.
/// - action: The action to perform when the user triggers the button.
public init(_ titleKey: LocalizedStringKey, role: ButtonRole?, action: @escaping () -> Void)
/// Creates a button with a specified role that generates its label from a
/// string.
///
/// This initializer creates a ``Text`` view on your behalf, and treats the
/// title similar to ``Text/init(_:)-9d1g4``. See ``Text`` for more
/// information about localizing strings.
///
/// To initialize a button with a localized string key, use
/// ``init(_:role:action:)-93ek6`` instead.
///
/// - Parameters:
/// - title: A string that describes the purpose of the button's `action`.
/// - role: An optional semantic role describing the button. A value of
/// `nil` means that the button doesn't have an assigned role.
/// - action: The action to perform when the user interacts with the button.
public init<S>(_ title: S, role: ButtonRole?, action: @escaping () -> Void) where S : StringProtocol
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Button where Label == Label<Text, Image> {
/// Creates a button with a specified role that generates its label from a
/// localized string key and a system image.
///
/// This initializer creates a ``Label`` view on your behalf, and treats the
/// localized key similar to ``Text/init(_:tableName:bundle:comment:)``. See
/// ``Text`` for more information about localizing strings.
///
/// - Parameters:
/// - titleKey: The key for the button's localized title, that describes
/// the purpose of the button's `action`.
/// - systemImage: The name of the image resource to lookup.
/// - role: An optional semantic role describing the button. A value of
/// `nil` means that the button doesn't have an assigned role.
/// - action: The action to perform when the user triggers the button.
public init(_ titleKey: LocalizedStringKey, systemImage: String, role: ButtonRole?, action: @escaping () -> Void)
/// Creates a button with a specified role that generates its label from a
/// string and a system image and an image resource.
///
/// This initializer creates a ``Label`` view on your behalf, and treats the
/// title similar to ``Text/init(_:)-9d1g4``. See ``Text`` for more
/// information about localizing strings.
///
/// - Parameters:
/// - title: A string that describes the purpose of the button's `action`.
/// - systemImage: The name of the image resource to lookup.
/// - role: An optional semantic role describing the button. A value of
/// `nil` means that the button doesn't have an assigned role.
/// - action: The action to perform when the user interacts with the button.
public init<S>(_ title: S, systemImage: String, role: ButtonRole?, action: @escaping () -> Void) where S : StringProtocol
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Button where Label == Label<Text, Image> {
/// Creates a button with a specified role that generates its label from a
/// localized string key and an image resource.
///
/// This initializer creates a ``Label`` view on your behalf, and treats the
/// localized key similar to ``Text/init(_:tableName:bundle:comment:)``. See
/// ``Text`` for more information about localizing strings.
///
/// - Parameters:
/// - titleKey: The key for the button's localized title, that describes
/// the purpose of the button's `action`.
/// - image: The image resource to lookup.
/// - role: An optional semantic role describing the button. A value of
/// `nil` means that the button doesn't have an assigned role.
/// - action: The action to perform when the user triggers the button.
public init(_ titleKey: LocalizedStringKey, image: ImageResource, role: ButtonRole?, action: @escaping () -> Void)
/// Creates a button with a specified role that generates its label from a
/// string and an image resource.
///
/// This initializer creates a ``Label`` view on your behalf, and treats the
/// title similar to ``Text/init(_:)-9d1g4``. See ``Text`` for more
/// information about localizing strings.
///
/// - Parameters:
/// - title: A string that describes the purpose of the button's `action`.
/// - image: The image resource to lookup.
/// - role: An optional semantic role describing the button. A value of
/// `nil` means that the button doesn't have an assigned role.
/// - action: The action to perform when the user interacts with the button.
public init<S>(_ title: S, image: ImageResource, role: ButtonRole?, action: @escaping () -> Void) where S : StringProtocol
}
/// A shape that is used to draw a button's border.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct ButtonBorderShape : Equatable, Sendable {
/// A shape that defers to the system to determine an appropriate shape
/// for the given context and platform.
public static let automatic: ButtonBorderShape
/// A capsule shape.
///
/// - Note: This has no effect on non-widget system buttons on macOS.
@available(macOS 14.0, tvOS 17.0, *)
public static let capsule: ButtonBorderShape
/// A rounded rectangle shape.
public static let roundedRectangle: ButtonBorderShape
/// A rounded rectangle shape.
///
/// - Parameter radius: the corner radius of the rectangle.
/// - Note: This has no effect on non-widget system buttons on macOS.
@available(macOS 14.0, tvOS 17.0, *)
public static func roundedRectangle(radius: CGFloat) -> ButtonBorderShape
@available(iOS 17.0, macOS 14.0, tvOS 16.4, watchOS 10.0, *)
public static let circle: ButtonBorderShape
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ButtonBorderShape, b: ButtonBorderShape) -> Bool
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension ButtonBorderShape : Shape {
/// Describes this shape as a path within a rectangular frame of reference.
///
/// - Parameter rect: The frame of reference for describing this shape.
///
/// - Returns: A path that describes this shape.
public func path(in rect: CGRect) -> Path
/// The type defining the data to animate.
public typealias AnimatableData = EmptyAnimatableData
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension ButtonBorderShape : InsettableShape {
/// Returns `self` inset by `amount`.
@inlinable public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
public typealias InsetShape = some InsettableShape
}
/// A menu style that displays a button that toggles the display of the
/// menu's contents when pressed.
///
/// Use ``MenuStyle/button`` to construct this style.
@available(iOS 16.0, macOS 13.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public struct ButtonMenuStyle : MenuStyle {
/// Creates a button menu style.
public init()
/// Creates a view that represents the body of a menu.
///
/// - Parameter configuration: The properties of the menu.
///
/// The system calls this method for each ``Menu`` instance in a view
/// hierarchy where this style is the current menu style.
public func makeBody(configuration: ButtonMenuStyle.Configuration) -> some View
/// A view that represents the body of a menu.
public typealias Body = some View
}
/// The options for controlling the repeatability of button actions.
///
/// Use values of this type with the ``View/buttonRepeatBehavior(_:)``
/// modifier.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct ButtonRepeatBehavior : Hashable, Sendable {
/// The automatic repeat behavior.
public static let automatic: ButtonRepeatBehavior
/// Repeating button actions will be enabled.
public static let enabled: ButtonRepeatBehavior
/// Repeating button actions will be disabled.
public static let disabled: ButtonRepeatBehavior
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ButtonRepeatBehavior, b: ButtonRepeatBehavior) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A value that describes the purpose of a button.
///
/// A button role provides a description of a button's purpose. For example,
/// the ``ButtonRole/destructive`` role indicates that a button performs
/// a destructive action, like delete user data:
///
/// Button("Delete", role: .destructive) { delete() }
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct ButtonRole : Equatable, Sendable {
/// A role that indicates a destructive button.
///
/// Use this role for a button that deletes user data, or performs an
/// irreversible operation. A destructive button signals by its appearance
/// that the user should carefully consider whether to tap or click the
/// button. For example, SwiftUI presents a destructive button that you add
/// with the ``View/swipeActions(edge:allowsFullSwipe:content:)``
/// modifier using a red background:
///
/// List {
/// ForEach(items) { item in
/// Text(item.title)
/// .swipeActions {
/// Button(role: .destructive) { delete() } label: {
/// Label("Delete", systemImage: "trash")
/// }
/// }
/// }
/// }
/// .navigationTitle("Shopping List")
///
/// ![A screenshot of a list of three items, where the second item is
/// shifted to the left, and the row displays a red button with a trash
/// icon on the right side.](ButtonRole-destructive-1)
public static let destructive: ButtonRole
/// A role that indicates a button that cancels an operation.
///
/// Use this role for a button that cancels the current operation.
public static let cancel: ButtonRole
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ButtonRole, b: ButtonRole) -> Bool
}
/// A type that applies standard interaction behavior and a custom appearance to
/// all buttons within a view hierarchy.
///
/// To configure the current button style for a view hierarchy, use the
/// ``View/buttonStyle(_:)-7qx1`` modifier. Specify a style that conforms to
/// `ButtonStyle` when creating a button that uses the standard button
/// interaction behavior defined for each platform. To create a button with
/// custom interaction behavior, use ``PrimitiveButtonStyle`` instead.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol ButtonStyle {
/// A view that represents the body of a button.
associatedtype Body : View
/// Creates a view that represents the body of a button.
///
/// The system calls this method for each ``Button`` instance in a view
/// hierarchy where this style is the current button style.
///
/// - Parameter configuration : The properties of the button.
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a button.
typealias Configuration = ButtonStyleConfiguration
}
/// The properties of a button.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct ButtonStyleConfiguration {
/// A type-erased label of a button.
public struct Label : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// An optional semantic role that describes the button's purpose.
///
/// A value of `nil` means that the Button doesn't have an assigned role. If
/// the button does have a role, use it to make adjustments to the button's
/// appearance. The following example shows a custom style that uses
/// bold text when the role is ``ButtonRole/cancel``,
/// ``ShapeStyle/red`` text when the role is ``ButtonRole/destructive``,
/// and adds no special styling otherwise:
///
/// struct MyButtonStyle: ButtonStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// configuration.label
/// .font(
/// configuration.role == .cancel ? .title2.bold() : .title2)
/// .foregroundColor(
/// configuration.role == .destructive ? Color.red : nil)
/// }
/// }
///
/// You can create one of each button using this style to see the effect:
///
/// VStack(spacing: 20) {
/// Button("Cancel", role: .cancel) {}
/// Button("Delete", role: .destructive) {}
/// Button("Continue") {}
/// }
/// .buttonStyle(MyButtonStyle())
///
/// ![A screenshot of three buttons stacked vertically. The first says
/// Cancel in black, bold letters. The second says Delete in red, regular
/// weight letters. The third says Continue in black, regular weight
/// letters.](ButtonStyleConfiguration-role-1)
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public let role: ButtonRole?
/// A view that describes the effect of pressing the button.
public let label: ButtonStyleConfiguration.Label
/// A Boolean that indicates whether the user is currently pressing the
/// button.
public let isPressed: Bool
}
/// A toggle style that displays as a button with its label as the title.
///
/// You can also use ``ToggleStyle/button`` to construct this style.
///
/// Toggle(isOn: $isFlagged) {
/// Label("Flag", systemImage: "flag.fill")
/// }
/// .toggleStyle(.button)
///
@available(iOS 15.0, macOS 12.0, watchOS 9.0, *)
@available(tvOS, unavailable)
public struct ButtonToggleStyle : ToggleStyle {
/// Creates a button toggle style.
///
/// Don't call this initializer directly. Instead, use the
/// ``ToggleStyle/button`` static variable to create this style:
///
/// Toggle(isOn: $isFlagged) {
/// Label("Flag", systemImage: "flag.fill")
/// }
/// .toggleStyle(.button)
///
public init()
/// Creates a view that represents the body of a toggle button.
///
/// SwiftUI implements this required method of the ``ToggleStyle``
/// protocol to define the behavior and appearance of the
/// ``ToggleStyle/button`` toggle style. Don't call this method
/// directly; the system calls this method for each
/// ``Toggle`` instance in a view hierarchy that's styled as
/// a button.
///
/// - Parameter configuration: The properties of the toggle, including a
/// label and a binding to the toggle's state.
/// - Returns: A view that acts as a button that controls a Boolean state.
public func makeBody(configuration: ButtonToggleStyle.Configuration) -> some View
/// A view that represents the appearance and interaction of a toggle.
///
/// SwiftUI infers this type automatically based on the ``View``
/// instance that you return from your implementation of the
/// ``makeBody(configuration:)`` method.
public typealias Body = some View
}
/// A view type that supports immediate mode drawing.
///
/// 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
/// <doc://com.apple.documentation/documentation/CoreFoundation/CGSize> value
/// that you can use to customize what you draw. For example, you can use the
/// context's ``GraphicsContext/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:
///
/// ![A screenshot of a canvas view that shows the green outline of an
/// ellipse inside a blue rectangle.](Canvas-1)
///
/// 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.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct Canvas<Symbols> where Symbols : View {
/// A view that provides child views that you can use in the drawing
/// callback.
///
/// Uniquely tag each child view using the ``View/tag(_:)`` modifier,
/// so that you can find them from within your renderer using the
/// ``GraphicsContext/resolveSymbol(id:)`` method.
public var symbols: Symbols
/// The drawing callback that you use to draw into the canvas.
///
/// - Parameters:
/// - context: The graphics context to draw into.
/// - size: The current size of the view.
public var renderer: (inout GraphicsContext, CGSize) -> Void
/// A Boolean that indicates whether the canvas is fully opaque.
///
/// You might be able to improve performance by setting this value to
/// `true`, making the canvas is fully opaque. However, in that case,
/// the result of drawing a non-opaque image into the canvas is undefined.
public var isOpaque: Bool
/// The working color space and storage format of the canvas.
public var colorMode: ColorRenderingMode
/// A Boolean that indicates whether the canvas can present its contents
/// to its parent view asynchronously.
public var rendersAsynchronously: Bool
/// Creates and configures a canvas that you supply with renderable
/// child views.
///
/// This initializer behaves like the
/// ``init(opaque:colorMode:rendersAsynchronously:renderer:)`` initializer,
/// except that you also provide a collection of SwiftUI views for the
/// renderer to use as drawing elements.
///
/// SwiftUI stores a rendered version of each child view that you specify
/// in the `symbols` view builder and makes these available to the canvas.
/// Tag each child view so that you can retrieve it from within the
/// renderer using the ``GraphicsContext/resolveSymbol(id:)`` method.
/// For example, you can create a scatter plot using a passed-in child view
/// as the mark for each data point:
///
/// struct ScatterPlotView<Mark: View>: View {
/// let rects: [CGRect]
/// let mark: Mark
///
/// enum SymbolID: Int {
/// case mark
/// }
///
/// var body: some View {
/// Canvas { context, size in
/// if let mark = context.resolveSymbol(id: SymbolID.mark) {
/// for rect in rects {
/// context.draw(mark, in: rect)
/// }
/// }
/// } symbols: {
/// mark.tag(SymbolID.mark)
/// }
/// .frame(width: 300, height: 200)
/// .border(Color.blue)
/// }
/// }
///
/// You can use any SwiftUI view for the `mark` input:
///
/// ScatterPlotView(rects: rects, mark: Image(systemName: "circle"))
///
/// If the `rects` input contains 50 randomly arranged
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGRect>
/// instances, SwiftUI draws a plot like this:
///
/// ![A screenshot of a scatter plot inside a blue rectangle, containing
/// about fifty small circles scattered randomly throughout.](Canvas-init-1)
///
/// The symbol inputs, like all other elements that you draw to the
/// canvas, lack individual accessibility and interactivity, even if the
/// original SwiftUI view has these attributes. However, you can add
/// accessibility and interactivity modifers to the canvas as a whole.
///
/// - Parameters:
/// - opaque: A Boolean that indicates whether the canvas is fully
/// opaque. You might be able to improve performance by setting this
/// value to `true`, but then drawing a non-opaque image into the
/// context produces undefined results. The default is `false`.
/// - colorMode: A working color space and storage format of the canvas.
/// The default is ``ColorRenderingMode/nonLinear``.
/// - rendersAsynchronously: A Boolean that indicates whether the canvas
/// can present its contents to its parent view asynchronously. The
/// default is `false`.
/// - renderer: A closure in which you conduct immediate mode drawing.
/// The closure takes two inputs: a context that you use to issue
/// drawing commands and a size --- representing the current
/// size of the canvas --- that you can use to customize the content.
/// The canvas calls the renderer any time it needs to redraw the
/// content.
/// - symbols: A ``ViewBuilder`` that you use to supply SwiftUI views to
/// the canvas for use during drawing. Uniquely tag each view
/// using the ``View/tag(_:)`` modifier, so that you can find them from
/// within your renderer using the ``GraphicsContext/resolveSymbol(id:)``
/// method.
public init(opaque: Bool = false, colorMode: ColorRenderingMode = .nonLinear, rendersAsynchronously: Bool = false, renderer: @escaping (inout GraphicsContext, CGSize) -> Void, @ViewBuilder symbols: () -> Symbols)
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Canvas where Symbols == EmptyView {
/// Creates and configures a canvas.
///
/// Use this initializer to create a new canvas that you can draw into.
/// For example, you can draw a path:
///
/// 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:
///
/// ![A screenshot of a canvas view that shows the green outline of an
/// ellipse inside a blue rectangle.](Canvas-1)
///
/// For information about using a context to draw into a canvas, see
/// ``GraphicsContext``. If you want to provide SwiftUI views for the
/// renderer to use as drawing elements, use
/// ``init(opaque:colorMode:rendersAsynchronously:renderer:symbols:)``
/// instead.
///
/// - Parameters:
/// - opaque: A Boolean that indicates whether the canvas is fully
/// opaque. You might be able to improve performance by setting this
/// value to `true`, but then drawing a non-opaque image into the
/// context produces undefined results. The default is `false`.
/// - colorMode: A working color space and storage format of the canvas.
/// The default is ``ColorRenderingMode/nonLinear``.
/// - rendersAsynchronously: A Boolean that indicates whether the canvas
/// can present its contents to its parent view asynchronously. The
/// default is `false`.
/// - renderer: A closure in which you conduct immediate mode drawing.
/// The closure takes two inputs: a context that you use to issue
/// drawing commands and a size --- representing the current
/// size of the canvas --- that you can use to customize the content.
/// The canvas calls the renderer any time it needs to redraw the
/// content.
public init(opaque: Bool = false, colorMode: ColorRenderingMode = .nonLinear, rendersAsynchronously: Bool = false, renderer: @escaping (inout GraphicsContext, CGSize) -> Void)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Canvas : View {
}
/// A capsule shape aligned inside the frame of the view containing it.
///
/// A capsule shape is equivalent to a rounded rectangle where the corner radius
/// is chosen as half the length of the rectangle's smallest edge.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Capsule : Shape {
public var style: RoundedCornerStyle
/// Creates a new capsule shape.
///
/// - Parameters:
/// - style: the style of corners drawn by the shape.
@inlinable public init(style: RoundedCornerStyle = .continuous)
/// Describes this shape as a path within a rectangular frame of reference.
///
/// - Parameter rect: The frame of reference for describing this shape.
///
/// - Returns: A path that describes this shape.
public func path(in r: CGRect) -> Path
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public var layoutDirectionBehavior: LayoutDirectionBehavior { get }
/// The type defining the data to animate.
public typealias AnimatableData = EmptyAnimatableData
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Capsule : InsettableShape {
/// Returns `self` inset by `amount`.
@inlinable public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
public typealias InsetShape = some InsettableShape
}
/// A toggle style that displays a checkbox followed by its label.
///
/// Use the ``ToggleStyle/checkbox`` static variable to create this style:
///
/// Toggle("Close windows when quitting an app", isOn: $doesClose)
/// .toggleStyle(.checkbox)
///
@available(macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct CheckboxToggleStyle : ToggleStyle {
/// Creates a checkbox toggle style.
///
/// Don't call this initializer directly. Instead, use the
/// ``ToggleStyle/checkbox`` static variable to create this style:
///
/// Toggle("Close windows when quitting an app", isOn: $doesClose)
/// .toggleStyle(.checkbox)
///
public init()
/// Creates a view that represents the body of a toggle checkbox.
///
/// SwiftUI implements this required method of the ``ToggleStyle``
/// protocol to define the behavior and appearance of the
/// ``ToggleStyle/checkbox`` toggle style. Don't call this method
/// directly. Rather, the system calls this method for each
/// ``Toggle`` instance in a view hierarchy that's styled as
/// a checkbox.
///
/// - Parameter configuration: The properties of the toggle, including a
/// label and a binding to the toggle's state.
/// - Returns: A view that represents a checkbox.
public func makeBody(configuration: CheckboxToggleStyle.Configuration) -> some View
/// A view that represents the appearance and interaction of a toggle.
///
/// SwiftUI infers this type automatically based on the ``View``
/// instance that you return from your implementation of the
/// ``makeBody(configuration:)`` method.
public typealias Body = some View
}
/// A circle centered on the frame of the view containing it.
///
/// The circle's radius equals half the length of the frame rectangle's smallest
/// edge.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Circle : Shape {
/// Describes this shape as a path within a rectangular frame of reference.
///
/// - Parameter rect: The frame of reference for describing this shape.
///
/// - Returns: A path that describes this shape.
public func path(in rect: CGRect) -> Path
/// Creates a new circle shape.
@inlinable public init()
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public var layoutDirectionBehavior: LayoutDirectionBehavior { get }
/// The type defining the data to animate.
public typealias AnimatableData = EmptyAnimatableData
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Circle {
/// Returns the size of the view that will render the shape, given
/// a proposed size.
///
/// Implement this method to tell the container of the shape how
/// much space the shape needs to render itself, given a size
/// proposal.
///
/// See ``Layout/sizeThatFits(proposal:subviews:cache:)``
/// for more details about how the layout system chooses the size of
/// views.
///
/// - Parameters:
/// - proposal: A size proposal for the container.
///
/// - Returns: A size that indicates how much space the shape needs.
public func sizeThatFits(_ proposal: ProposedViewSize) -> CGSize
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Circle : InsettableShape {
/// Returns `self` inset by `amount`.
@inlinable public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
public typealias InsetShape = some InsettableShape
}
/// A progress view that uses a circular gauge to indicate the partial
/// completion of an activity.
///
/// On watchOS, and in widgets and complications, a circular progress view
/// appears as a gauge with the ``GaugeStyle/accessoryCircularCapacity``
/// style. If the progress view is indeterminate, the gauge is empty.
///
/// In cases where no determinate circular progress view style is available,
/// circular progress views use an indeterminate style.
///
/// Use ``ProgressViewStyle/circular`` to construct the circular progress view
/// style.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct CircularProgressViewStyle : ProgressViewStyle {
/// Creates a circular progress view style.
public init()
/// Creates a circular progress view style with a tint color.
@available(iOS, introduced: 14.0, deprecated: 100000.0, message: "Use ``View/tint(_)`` instead.")
@available(macOS, introduced: 11.0, deprecated: 100000.0, message: "Use ``View/tint(_)`` instead.")
@available(tvOS, introduced: 14.0, deprecated: 100000.0, message: "Use ``View/tint(_)`` instead.")
@available(watchOS, introduced: 7.0, deprecated: 100000.0, message: "Use ``View/tint(_)`` instead.")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use ``View/tint(_)`` instead.")
public init(tint: Color)
/// Creates a view representing the body of a progress view.
///
/// - Parameter configuration: The properties of the progress view being
/// created.
///
/// The view hierarchy calls this method for each progress view where this
/// style is the current progress view style.
///
/// - Parameter configuration: The properties of the progress view, such as
/// its preferred progress type.
public func makeBody(configuration: CircularProgressViewStyle.Configuration) -> some View
/// A view representing the body of a progress view.
public typealias Body = some View
}
/// A representation of a color that adapts to a given context.
///
/// 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
/// <doc://com.apple.documentation/documentation/UIKit/UIColor> or an
/// <doc://com.apple.documentation/documentation/AppKit/NSColor>:
/// ```
/// #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 ``ShapeStyle/black``,
/// ``ShapeStyle/green``, and ``ShapeStyle/purple``.
///
/// Some view modifiers can take a color as an argument. For example,
/// ``View/foregroundStyle(_:)`` uses the color you provide to set the
/// foreground color for view elements, like text or
/// [SF Symbols](https://developer.apple.com/design/human-interface-guidelines/sf-symbols/overview/):
///
/// Image(systemName: "leaf.fill")
/// .foregroundStyle(Color.green)
///
/// ![A screenshot of a green leaf.](Color-1)
///
/// 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:
///
/// ![A screenshot of a yellow sun on a blue background.](Color-2)
///
/// 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.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Color : Hashable, CustomStringConvertible, Sendable {
/// Creates a color that represents the specified custom color.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public init<T>(_ color: T) where T : Hashable, T : ShapeStyle, T.Resolved == Color.Resolved
/// Evaluates this color to a resolved color given the current
/// `context`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func resolve(in environment: EnvironmentValues) -> Color.Resolved
/// A Core Graphics representation of the color, if available.
///
/// You can get a
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGColor>
/// instance from a constant SwiftUI color. This includes colors you create
/// from a Core Graphics color, from RGB or HSB components, or from constant
/// UIKit and AppKit colors.
///
/// For a dynamic color, like one you load from an Asset Catalog using
/// ``init(_:bundle:)``, or one you create from a dynamic UIKit or AppKit
/// color, this property is `nil`. To evaluate all types of colors, use the
/// `resolve(in:)` method.
@available(iOS, introduced: 14.0, deprecated: 100000.0, renamed: "resolve(in:)")
@available(macOS, introduced: 11.0, deprecated: 100000.0, renamed: "resolve(in:)")
@available(tvOS, introduced: 14.0, deprecated: 100000.0, renamed: "resolve(in:)")
@available(watchOS, introduced: 7.0, deprecated: 100000.0, renamed: "resolve(in:)")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, renamed: "resolve(in:)")
public var cgColor: CGColor? { get }
/// Hashes the essential components of the color by feeding them into the
/// given hash function.
///
/// - Parameters:
/// - hasher: The hash function to use when combining the components of
/// the color.
public func hash(into hasher: inout Hasher)
/// Indicates whether two colors are equal.
///
/// - Parameters:
/// - lhs: The first color to compare.
/// - rhs: The second color to compare.
/// - Returns: A Boolean that's set to `true` if the two colors are equal.
public static func == (lhs: Color, rhs: Color) -> Bool
/// A textual representation of the color.
///
/// Use this method to get a string that represents the color.
/// The <doc://com.apple.documentation/documentation/Swift/1541053-print>
/// function uses this property to get a string representing an instance:
///
/// print(Color.red)
/// // Prints "red"
public var description: String { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color {
/// A concrete color value.
///
/// `Color.Resolved` is a set of RGBA values that represent a color that can
/// be shown. The values are in Linear sRGB color space, extended range. This is
/// a low-level type, most colors are represented by the `Color` type.
///
/// - SeeAlso: `Color`
@frozen public struct Resolved : Hashable {
/// The amount of red in the color in the sRGB linear color space.
public var linearRed: Float
/// The amount of green in the color in the sRGB linear color space.
public var linearGreen: Float
/// The amount of blue in the color in the sRGB linear color space.
public var linearBlue: Float
/// The degree of opacity in the color, given in the range `0` to `1`.
///
/// A value of `0` means 100% transparency, while a value of `1` means
/// 100% opacity.
public var opacity: Float
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Color.Resolved, b: Color.Resolved) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// Creates a constant color with the values specified by the resolved
/// color.
public init(_ resolved: Color.Resolved)
}
@available(iOS, introduced: 14.0, deprecated: 100000.0, message: "Use Color(cgColor:) when converting a CGColor, or create a standard Color directly")
@available(macOS, introduced: 11.0, deprecated: 100000.0, message: "Use Color(cgColor:) when converting a CGColor, or create a standard Color directly")
@available(tvOS, introduced: 14.0, deprecated: 100000.0, message: "Use Color(cgColor:) when converting a CGColor, or create a standard Color directly")
@available(watchOS, introduced: 7.0, deprecated: 100000.0, message: "Use Color(cgColor:) when converting a CGColor, or create a standard Color directly")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use Color(cgColor:) when converting a CGColor, or create a standard Color directly")
extension Color {
/// Creates a color from a Core Graphics color.
///
/// - Parameter color: A
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGColor> instance
/// from which to create a color.
public init(_ cgColor: CGColor)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Color {
/// Creates a color from a Core Graphics color.
///
/// - Parameter color: A
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGColor> instance
/// from which to create a color.
public init(cgColor: CGColor)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color {
/// Creates a color from a color set that you indicate by name.
///
/// Use this initializer to load a color from a color set stored in an
/// Asset Catalog. The system determines which color within the set to use
/// based on the environment at render time. For example, you
/// can provide light and dark versions for background and foreground
/// colors:
///
/// ![A screenshot of color sets for foreground and background colors,
/// each with light and dark variants,
/// in an Asset Catalog.](Color-init-1)
///
/// You can then instantiate colors by referencing the names of the assets:
///
/// struct Hello: View {
/// var body: some View {
/// ZStack {
/// Color("background")
/// Text("Hello, world!")
/// .foregroundStyle(Color("foreground"))
/// }
/// .frame(width: 200, height: 100)
/// }
/// }
///
/// SwiftUI renders the appropriate colors for each appearance:
///
/// ![A side by side comparison of light and dark appearance screenshots
/// of the same content. The light variant shows dark text on a light
/// background, while the dark variant shows light text on a dark
/// background.](Color-init-2)
///
/// - Parameters:
/// - name: The name of the color resource to look up.
/// - bundle: The bundle in which to search for the color resource.
/// If you don't indicate a bundle, the initializer looks in your app's
/// main bundle by default.
public init(_ name: String, bundle: Bundle? = nil)
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color {
/// Initialize a `Color` with a color resource.
public init(_ resource: ColorResource)
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Color : Transferable {
/// One group of colors–constant colors–created with explicitly specified
/// component values are transferred as is.
///
/// Another group of colors–standard colors, like `Color.mint`,
/// and semantic colors, like `Color.accentColor`–are rendered on screen
/// differently depending on the current ``SwiftUI/Environment``. For transferring,
/// they are resolved against the default environment and might produce
/// a slightly different result at the destination if the source of drag
/// or copy uses a non-default environment.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public static var transferRepresentation: some TransferRepresentation { get }
/// The type of the representation used to import and export the item.
///
/// Swift infers this type from the return value of the
/// ``transferRepresentation`` property.
public typealias Representation = some TransferRepresentation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color {
/// A profile that specifies how to interpret a color value for display.
public enum RGBColorSpace : Sendable {
/// The extended red, green, blue (sRGB) color space.
///
/// For information about the sRGB colorimetry and nonlinear
/// transform function, see the IEC 61966-2-1 specification.
///
/// Standard sRGB color spaces clamp the red, green, and blue
/// components of a color to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so you can use component values
/// outside that range.
case sRGB
/// The extended sRGB color space with a linear transfer function.
///
/// This color space has the same colorimetry as ``sRGB``, but uses
/// a linear transfer function.
///
/// Standard sRGB color spaces clamp the red, green, and blue
/// components of a color to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so you can use component values
/// outside that range.
case sRGBLinear
/// The Display P3 color space.
///
/// This color space uses the Digital Cinema Initiatives - Protocol 3
/// (DCI-P3) primary colors, a D65 white point, and the ``sRGB``
/// transfer function.
case displayP3
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Color.RGBColorSpace, b: Color.RGBColorSpace) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// Creates a constant color from red, green, and blue component values.
///
/// This initializer creates a constant color that doesn't change based
/// on context. For example, it doesn't have distinct light and dark
/// appearances, unlike various system-defined colors, or a color that
/// you load from an Asset Catalog with ``init(_:bundle:)``.
///
/// A standard sRGB color space clamps each color component — `red`,
/// `green`, and `blue` — to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so
/// you can use component values outside that range. This makes it
/// possible to create colors using the ``RGBColorSpace/sRGB`` or
/// ``RGBColorSpace/sRGBLinear`` color space that make full use of the wider
/// gamut of a diplay that supports ``RGBColorSpace/displayP3``.
///
/// - Parameters:
/// - colorSpace: The profile that specifies how to interpret the color
/// for display. The default is ``RGBColorSpace/sRGB``.
/// - red: The amount of red in the color.
/// - green: The amount of green in the color.
/// - blue: The amount of blue in the color.
/// - opacity: An optional degree of opacity, given in the range `0` to
/// `1`. A value of `0` means 100% transparency, while a value of `1`
/// means 100% opacity. The default is `1`.
public init(_ colorSpace: Color.RGBColorSpace = .sRGB, red: Double, green: Double, blue: Double, opacity: Double = 1)
/// Creates a constant grayscale color.
///
/// This initializer creates a constant color that doesn't change based
/// on context. For example, it doesn't have distinct light and dark
/// appearances, unlike various system-defined colors, or a color that
/// you load from an Asset Catalog with ``init(_:bundle:)``.
///
/// A standard sRGB color space clamps the `white` component
/// to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so
/// you can use component values outside that range. This makes it
/// possible to create colors using the ``RGBColorSpace/sRGB`` or
/// ``RGBColorSpace/sRGBLinear`` color space that make full use of the wider
/// gamut of a diplay that supports ``RGBColorSpace/displayP3``.
///
/// - Parameters:
/// - colorSpace: The profile that specifies how to interpret the color
/// for display. The default is ``RGBColorSpace/sRGB``.
/// - white: A value that indicates how white
/// the color is, with higher values closer to 100% white, and lower
/// values closer to 100% black.
/// - opacity: An optional degree of opacity, given in the range `0` to
/// `1`. A value of `0` means 100% transparency, while a value of `1`
/// means 100% opacity. The default is `1`.
public init(_ colorSpace: Color.RGBColorSpace = .sRGB, white: Double, opacity: Double = 1)
/// Creates a constant color from hue, saturation, and brightness values.
///
/// This initializer creates a constant color that doesn't change based
/// on context. For example, it doesn't have distinct light and dark
/// appearances, unlike various system-defined colors, or a color that
/// you load from an Asset Catalog with ``init(_:bundle:)``.
///
/// - Parameters:
/// - hue: A value in the range `0` to `1` that maps to an angle
/// from 0° to 360° to represent a shade on the color wheel.
/// - saturation: A value in the range `0` to `1` that indicates
/// how strongly the hue affects the color. A value of `0` removes the
/// effect of the hue, resulting in gray. As the value increases,
/// the hue becomes more prominent.
/// - brightness: A value in the range `0` to `1` that indicates
/// how bright a color is. A value of `0` results in black, regardless
/// of the other components. The color lightens as you increase this
/// component.
/// - opacity: An optional degree of opacity, given in the range `0` to
/// `1`. A value of `0` means 100% transparency, while a value of `1`
/// means 100% opacity. The default is `1`.
public init(hue: Double, saturation: Double, brightness: Double, opacity: Double = 1)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color {
/// Multiplies the opacity of the color by the given amount.
///
/// - Parameter opacity: The amount by which to multiply the opacity of the
/// color.
/// - Returns: A view with modified opacity.
public func opacity(_ opacity: Double) -> Color
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color {
/// A color that reflects the accent color of the system or app.
///
/// The accent color is a broad theme color applied to
/// views and controls. You can set it at the application level by specifying
/// an accent color in your app's asset catalog.
///
/// > Note: In macOS, SwiftUI applies customization of the accent color
/// only if the user chooses Multicolor under General > Accent color
/// in System Preferences.
///
/// The following code renders a ``Text`` view using the app's accent color:
///
/// Text("Accent Color")
/// .foregroundStyle(Color.accentColor)
///
public static var accentColor: Color { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color : ShapeStyle {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color {
/// A context-dependent red color suitable for use in UI elements.
public static let red: Color
/// A context-dependent orange color suitable for use in UI elements.
public static let orange: Color
/// A context-dependent yellow color suitable for use in UI elements.
public static let yellow: Color
/// A context-dependent green color suitable for use in UI elements.
public static let green: Color
/// A context-dependent mint color suitable for use in UI elements.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public static let mint: Color
/// A context-dependent teal color suitable for use in UI elements.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public static let teal: Color
/// A context-dependent cyan color suitable for use in UI elements.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public static let cyan: Color
/// A context-dependent blue color suitable for use in UI elements.
public static let blue: Color
/// A context-dependent indigo color suitable for use in UI elements.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public static let indigo: Color
/// A context-dependent purple color suitable for use in UI elements.
public static let purple: Color
/// A context-dependent pink color suitable for use in UI elements.
public static let pink: Color
/// A context-dependent brown color suitable for use in UI elements.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public static let brown: Color
/// A white color suitable for use in UI elements.
public static let white: Color
/// A context-dependent gray color suitable for use in UI elements.
public static let gray: Color
/// A black color suitable for use in UI elements.
public static let black: Color
/// A clear color suitable for use in UI elements.
public static let clear: Color
/// The color to use for primary content.
public static let primary: Color
/// The color to use for secondary content.
public static let secondary: Color
}
@available(iOS, unavailable)
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use Color(nsColor:) when converting a NSColor, or create a standard Color directly")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
extension Color {
/// Creates a color from an AppKit color.
///
/// Use this method to create a SwiftUI color from an
/// <doc://com.apple.documentation/documentation/AppKit/NSColor> instance.
/// The new color preserves the adaptability of the original.
/// For example, you can create a rectangle using
/// <doc://com.apple.documentation/documentation/AppKit/NSColor/2998828-linkColor>
/// to see how the shade adjusts to match the user's system settings:
///
/// struct Box: View {
/// var body: some View {
/// Color(NSColor.linkColor)
/// .frame(width: 200, height: 100)
/// }
/// }
///
/// The `Box` view defined above automatically changes its
/// appearance when the user turns on Dark Mode. With the light and dark
/// appearances placed side by side, you can see the subtle difference
/// in shades:
///
/// ![A side by side comparison of light and dark appearance screenshots of
/// rectangles rendered with the link color. The light variant appears on
/// the left, and the dark variant on the right.](Color-init-4)
///
/// > Note: Use this initializer only if you need to convert an existing
/// <doc://com.apple.documentation/documentation/AppKit/NSColor> to a
/// SwiftUI color. Otherwise, create a SwiftUI ``Color`` using an
/// initializer like ``init(_:red:green:blue:opacity:)``, or use a system
/// color like ``ShapeStyle/blue``.
///
/// - Parameter color: An
/// <doc://com.apple.documentation/documentation/AppKit/NSColor> instance
/// from which to create a color.
public init(_ color: NSColor)
}
@available(macOS 12.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
extension Color {
/// Creates a color from an AppKit color.
///
/// Use this method to create a SwiftUI color from an
/// <doc://com.apple.documentation/documentation/AppKit/NSColor> instance.
/// The new color preserves the adaptability of the original.
/// For example, you can create a rectangle using
/// <doc://com.apple.documentation/documentation/AppKit/NSColor/2998828-linkColor>
/// to see how the shade adjusts to match the user's system settings:
///
/// struct Box: View {
/// var body: some View {
/// Color(nsColor: .linkColor)
/// .frame(width: 200, height: 100)
/// }
/// }
///
/// The `Box` view defined above automatically changes its
/// appearance when the user turns on Dark Mode. With the light and dark
/// appearances placed side by side, you can see the subtle difference
/// in shades:
///
/// ![A side by side comparison of light and dark appearance screenshots of
/// rectangles rendered with the link color. The light variant appears on
/// the left, and the dark variant on the right.](Color-init-4)
///
/// > Note: Use this initializer only if you need to convert an existing
/// <doc://com.apple.documentation/documentation/AppKit/NSColor> to a
/// SwiftUI color. Otherwise, create a SwiftUI ``Color`` using an
/// initializer like ``init(_:red:green:blue:opacity:)``, or use a system
/// color like ``ShapeStyle/blue``.
///
/// - Parameter color: An
/// <doc://com.apple.documentation/documentation/AppKit/NSColor> instance
/// from which to create a color.
public init(nsColor: NSColor)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Color {
/// Returns the standard gradient for the color `self`.
///
/// For example, filling a rectangle with a gradient derived from
/// the standard blue color:
///
/// Rectangle().fill(.blue.gradient)
///
public var gradient: AnyGradient { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved : ShapeStyle {
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
public typealias Resolved = Never
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved : CustomStringConvertible {
/// A textual representation of this instance.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(describing:)`
/// initializer. This initializer works with any type, and uses the custom
/// `description` property for types that conform to
/// `CustomStringConvertible`:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved : Animatable {
/// The type defining the data to animate.
public typealias AnimatableData = AnimatablePair<Float, AnimatablePair<Float, AnimatablePair<Float, Float>>>
/// The data to animate.
public var animatableData: Color.Resolved.AnimatableData
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved {
/// Creates a resolved color from red, green, and blue component values.
///
/// A standard sRGB color space clamps each color component — `red`,
/// `green`, and `blue` — to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so
/// you can use component values outside that range. This makes it
/// possible to create colors using the ``RGBColorSpace/sRGB`` or
/// ``RGBColorSpace/sRGBLinear`` color space that make full use of the
/// wider gamut of a diplay that supports ``RGBColorSpace/displayP3``.
///
/// - Parameters:
/// - colorSpace: The profile that specifies how to interpret the
/// color for display. The default is ``RGBColorSpace/sRGB``.
/// - red: The amount of red in the color.
/// - green: The amount of green in the color.
/// - blue: The amount of blue in the color.
/// - opacity: An optional degree of opacity, given in the range `0`
/// to `1`. A value of `0` means 100% transparency, while a value of
/// `1` means 100% opacity. The default is `1`.
public init(colorSpace: Color.RGBColorSpace = .sRGB, red: Float, green: Float, blue: Float, opacity: Float = 1)
/// The amount of red in the color in the sRGB color space.
public var red: Float
/// The amount of green in the color in the sRGB color space.
public var green: Float
/// The amount of blue in the color in the sRGB color space.
public var blue: Float
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved : Codable {
/// Encodes this value into the given encoder.
///
/// If the value fails to encode anything, `encoder` will encode an empty
/// keyed container in its place.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved {
/// A Core Graphics representation of the color.
///
/// You can get a
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGColor>
/// instance from a resolved color.
public var cgColor: CGColor { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color.RGBColorSpace : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color.RGBColorSpace : Hashable {
}
/// A matrix to use in an RGBA color transformation.
///
/// The matrix has five columns, each with a red, green, blue, and alpha
/// component. You can use the matrix for tasks like creating a color
/// transformation ``GraphicsContext/Filter`` for a ``GraphicsContext`` using
/// the ``GraphicsContext/Filter/colorMatrix(_:)`` method.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public struct ColorMatrix : Equatable {
public var r1: Float
public var r2: Float
public var r3: Float
public var r4: Float
public var r5: Float
public var g1: Float
public var g2: Float
public var g3: Float
public var g4: Float
public var g5: Float
public var b1: Float
public var b2: Float
public var b3: Float
public var b4: Float
public var b5: Float
public var a1: Float
public var a2: Float
public var a3: Float
public var a4: Float
public var a5: Float
/// Creates the identity matrix.
@inlinable public init()
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ColorMatrix, b: ColorMatrix) -> Bool
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ColorMatrix : Sendable {
}
/// A control used to select a color from the system color picker UI.
///
/// 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)
/// }
/// }
/// }
///
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct ColorPicker<Label> : View where Label : View {
/// Creates an instance that selects a color.
///
/// - Parameters:
/// - selection: A ``Binding`` to the variable that displays the
/// selected ``Color``.
/// - supportsOpacity: A Boolean value that indicates whether the color
/// picker allows adjusting the selected color's opacity; the default
/// is `true`.
/// - label: A view that describes the use of the selected color.
/// The system color picker UI sets it's title using the text from
/// this view.
///
public init(selection: Binding<Color>, supportsOpacity: Bool = true, @ViewBuilder label: () -> Label)
/// Creates an instance that selects a color.
///
/// - Parameters:
/// - selection: A ``Binding`` to the variable that displays the
/// selected ``CGColor``.
/// - supportsOpacity: A Boolean value that indicates whether the color
/// picker allows adjusting the selected color's opacity; the default
/// is `true`.
/// - label: A view that describes the use of the selected color.
/// The system color picker UI sets it's title using the text from
/// this view.
///
public init(selection: Binding<CGColor>, supportsOpacity: Bool = true, @ViewBuilder label: () -> Label)
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ColorPicker where Label == Text {
/// Creates a color picker with a text label generated from a title string key.
///
/// Use ``ColorPicker`` to create a color well that your app uses to allow
/// the selection of a ``Color``. The example below creates a color well
/// using a ``Binding`` to a property stored in a settings object and title
/// you provide:
///
/// final class Settings: ObservableObject {
/// @Published var alignmentGuideColor =
/// Color(.sRGB, red: 0.98, green: 0.9, blue: 0.2)
/// }
///
/// struct FormattingControls: View {
/// @State private var settings = Settings()
///
/// var body: some View {
/// VStack {
/// // Other formatting controls.
/// ColorPicker("Alignment Guides",
/// selection: $settings.alignmentGuideColor
/// )
/// }
/// }
/// }
///
/// - Parameters:
/// - titleKey: The key for the localized title of the picker.
/// - selection: A ``Binding`` to the variable that displays the
/// selected ``Color``.
/// - supportsOpacity: A Boolean value that indicates whether the color
/// picker allows adjustments to the selected color's opacity; the
/// default is `true`.
public init(_ titleKey: LocalizedStringKey, selection: Binding<Color>, supportsOpacity: Bool = true)
/// Creates a color picker with a text label generated from a title string.
///
/// Use ``ColorPicker`` to create a color well that your app uses to allow
/// the selection of a ``Color``. The example below creates a color well
/// using a ``Binding`` and title you provide:
///
/// func showColorPicker(_ title: String, color: Binding<Color>) {
/// ColorPicker(title, selection: color)
/// }
///
/// - Parameters:
/// - title: The title displayed by the color picker.
/// - selection: A ``Binding`` to the variable containing a ``Color``.
/// - supportsOpacity: A Boolean value that indicates whether the color
/// picker allows adjustments to the selected color's opacity; the
/// default is `true`.
public init<S>(_ title: S, selection: Binding<Color>, supportsOpacity: Bool = true) where S : StringProtocol
/// Creates a color picker with a text label generated from a title string key.
///
/// - Parameters:
/// - titleKey: The key for the localized title of the picker.
/// - selection: A ``Binding`` to the variable that displays the
/// selected ``CGColor``.
/// - supportsOpacity: A Boolean value that indicates whether the color
/// picker allows adjustments to the selected color's opacity; the
/// default is `true`.
public init(_ titleKey: LocalizedStringKey, selection: Binding<CGColor>, supportsOpacity: Bool = true)
/// Creates a color picker with a text label generated from a title string.
///
/// - Parameters:
/// - title: The title displayed by the color picker.
/// - selection: A ``Binding`` to the variable containing a ``CGColor``.
/// - supportsOpacity: A Boolean value that indicates whether the color
/// picker allows adjustments to the selected color's opacity; the
/// default is `true`.
public init<S>(_ title: S, selection: Binding<CGColor>, supportsOpacity: Bool = true) where S : StringProtocol
}
/// The set of possible working color spaces for color-compositing operations.
///
/// Each color space guarantees the preservation of a particular range of color
/// values.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum ColorRenderingMode : Sendable {
/// The non-linear sRGB working color space.
///
/// Color component values outside the range `[0, 1]` produce undefined
/// results. This color space is gamma corrected.
case nonLinear
/// The linear sRGB working color space.
///
/// Color component values outside the range `[0, 1]` produce undefined
/// results. This color space isn't gamma corrected.
case linear
/// The extended linear sRGB working color space.
///
/// Color component values outside the range `[0, 1]` are preserved.
/// This color space isn't gamma corrected.
case extendedLinear
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ColorRenderingMode, b: ColorRenderingMode) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorRenderingMode : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorRenderingMode : Hashable {
}
/// The possible color schemes, corresponding to the light and dark appearances.
///
/// You receive a color scheme value when you read the
/// ``EnvironmentValues/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 ``View/preferredColorScheme(_:)``
/// view modifier.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum ColorScheme : CaseIterable, Sendable {
/// The color scheme that corresponds to a light appearance.
case light
/// The color scheme that corresponds to a dark appearance.
case dark
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ColorScheme, b: ColorScheme) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [ColorScheme]
/// A collection of all values of this type.
public static var allCases: [ColorScheme] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorScheme : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorScheme : Hashable {
}
/// The contrast between the app's foreground and background colors.
///
/// You receive a contrast value when you read the
/// ``EnvironmentValues/colorSchemeContrast`` environment value. The value
/// tells you if a standard or increased contrast currently applies to the view.
/// SwiftUI updates the value whenever the contrast changes, and redraws
/// views that depend on the value. For example, the following ``Text`` view
/// automatically updates when the user enables increased contrast:
///
/// @Environment(\.colorSchemeContrast) private var colorSchemeContrast
///
/// var body: some View {
/// Text(colorSchemeContrast == .standard ? "Standard" : "Increased")
/// }
///
/// The user sets the contrast by selecting the Increase Contrast option in
/// Accessibility > Display in System Preferences on macOS, or
/// Accessibility > Display & Text Size in the Settings app on iOS.
/// Your app can't override the user's choice. For
/// information about using color and contrast in your app, see
/// [Color and Contrast](https://developer.apple.com/design/human-interface-guidelines/accessibility/overview/color-and-contrast).
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum ColorSchemeContrast : CaseIterable, Sendable {
/// SwiftUI displays views with standard contrast between the app's
/// foreground and background colors.
case standard
/// SwiftUI displays views with increased contrast between the app's
/// foreground and background colors.
case increased
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ColorSchemeContrast, b: ColorSchemeContrast) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [ColorSchemeContrast]
/// A collection of all values of this type.
public static var allCases: [ColorSchemeContrast] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorSchemeContrast : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorSchemeContrast : Hashable {
}
/// A navigation view style represented by a series of views in columns.
///
/// You can also use ``NavigationViewStyle/columns`` to construct this style.
@available(iOS, introduced: 15.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationSplitView")
@available(macOS, introduced: 12.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationSplitView")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationSplitView")
public struct ColumnNavigationViewStyle : NavigationViewStyle {
}
/// A non-scrolling form style with a trailing aligned column of labels
/// next to a leading aligned column of values.
///
/// Use the ``FormStyle/columns`` static variable to create this style:
///
/// Form {
/// ...
/// }
/// .formStyle(.columns)
///
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct ColumnsFormStyle : FormStyle {
/// A non-scrolling form style with a trailing aligned column of labels
/// next to a leading aligned column of values.
///
/// Don't call this initializer directly. Instead, use the
/// ``FormStyle/columns`` static variable to create this style:
///
/// Form {
/// ...
/// }
/// .formStyle(.columns)
///
public init()
/// Creates a view that represents the body of a form.
///
/// - Parameter configuration: The properties of the form.
/// - Returns: A view that has behavior and appearance that enables it
/// to function as a ``Form``.
public func makeBody(configuration: ColumnsFormStyle.Configuration) -> some View
/// A view that represents the appearance and interaction of a form.
public typealias Body = some View
}
/// Groups of controls that you can add to existing command menus.
///
/// In macOS, SwiftUI realizes command groups as collections of menu items in a
/// menu bar menu. In iOS, iPadOS, and tvOS, SwiftUI creates key commands for
/// each of a group's commands that has a keyboard shortcut.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct CommandGroup<Content> : Commands where Content : View {
/// A value describing the addition of the given views to the beginning of
/// the indicated group.
public init(before group: CommandGroupPlacement, @ViewBuilder addition: () -> Content)
/// A value describing the addition of the given views to the end of the
/// indicated group.
public init(after group: CommandGroupPlacement, @ViewBuilder addition: () -> Content)
/// A value describing the complete replacement of the contents of the
/// indicated group with the given views.
public init(replacing group: CommandGroupPlacement, @ViewBuilder addition: () -> Content)
/// The contents of the command hierarchy.
///
/// For any commands that you create, provide a computed `body` property
/// that defines the scene as a composition of other scenes. You can
/// assemble a command hierarchy from built-in commands that SwiftUI
/// provides, as well as other commands that you've defined.
public var body: some Commands { get }
/// The type of commands that represents the body of this command hierarchy.
///
/// When you create custom commands, Swift infers this type from your
/// implementation of the required ``SwiftUI/Commands/body-swift.property``
/// property.
public typealias Body = some Commands
}
/// The standard locations that you can place new command groups relative to.
///
/// The names of these placements aren't visible in the user interface, but
/// the discussion for each placement lists the items that it includes.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct CommandGroupPlacement {
/// Placement for commands that provide information about the app,
/// the terms of the user's license agreement, and so on.
///
/// By default, this group includes the following command in macOS:
/// * About App
public static let appInfo: CommandGroupPlacement
/// Placement for commands that expose app settings and
/// preferences.
///
/// By default, this group includes the following command in macOS:
/// * Preferences
public static let appSettings: CommandGroupPlacement
/// Placement for commands that expose services other apps provide.
///
/// By default, this group includes the following command in macOS:
/// * Services submenu (managed automatically)
public static let systemServices: CommandGroupPlacement
/// Placement for commands that control the visibility of running
/// apps.
///
/// By default, this group includes the following commands in macOS:
/// * Hide App
/// * Hide Others
/// * Show All
public static let appVisibility: CommandGroupPlacement
/// Placement for commands that result in app termination.
///
/// By default, this group includes the following command in macOS:
/// * Quit App
public static let appTermination: CommandGroupPlacement
/// Placement for commands that create and open different kinds of
/// documents.
///
/// By default, this group includes the following commands in macOS:
/// * New
/// * Open
/// * Open Recent submenu (managed automatically)
public static let newItem: CommandGroupPlacement
/// Placement for commands that save open documents and close
/// windows.
///
/// By default, this group includes the following commands in macOS:
/// * Close
/// * Save
/// * Save As/Duplicate
/// * Revert to Saved
public static let saveItem: CommandGroupPlacement
/// Placement for commands that relate to importing and exporting
/// data using formats that the app doesn't natively support.
///
/// Empty by default in macOS.
public static let importExport: CommandGroupPlacement
/// Placement for commands related to printing app content.
///
/// By default, this group includes the following commands in macOS:
/// * Page Setup
/// * Print
public static let printItem: CommandGroupPlacement
/// Placement for commands that control the Undo Manager.
///
/// By default, this group includes the following commands in macOS:
/// * Undo
/// * Redo
public static let undoRedo: CommandGroupPlacement
/// Placement for commands that interact with the Clipboard and
/// manipulate content that is currently selected in the app's view
/// hierarchy.
///
/// By default, this group includes the following commands in macOS:
/// * Cut
/// * Copy
/// * Paste
/// * Paste and Match Style
/// * Delete
/// * Select All
public static let pasteboard: CommandGroupPlacement
/// Placement for commands that manipulate and transform text
/// selections.
///
/// By default, this group includes the following commands in macOS:
/// * Find submenu
/// * Spelling and Grammar submenu
/// * Substitutions submenu
/// * Transformations submenu
/// * Speech submenu
public static let textEditing: CommandGroupPlacement
/// Placement for commands that manipulate and transform the styles
/// applied to text selections.
///
/// By default, this group includes the following commands in macOS:
/// * Font submenu
/// * Text submenu
public static let textFormatting: CommandGroupPlacement
/// Placement for commands that manipulate the toolbar.
///
/// By default, this group includes the following commands in macOS:
/// * Show/Hide Toolbar
/// * Customize Toolbar
public static let toolbar: CommandGroupPlacement
/// Placement for commands that control the app's sidebar and full-screen
/// modes.
///
/// By default, this group includes the following commands in macOS:
/// * Show/Hide Sidebar
/// * Enter/Exit Full Screen
public static let sidebar: CommandGroupPlacement
/// Placement for commands that control the size of the window.
///
/// By default, this group includes the following commands in macOS:
/// * Minimize
/// * Zoom
public static let windowSize: CommandGroupPlacement
/// Placement for commands that describe and reveal the app's open
/// windows.
///
/// SwiftUI manages this group automatically in macOS.
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(visionOS, unavailable)
public static let windowList: CommandGroupPlacement
/// Placement for commands that describe and reveal any windows that the
/// app defines.
@available(macOS 13.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public static let singleWindowList: CommandGroupPlacement
/// Placement for commands that arrange all of an app's windows.
///
/// By default, this group includes the following command in macOS:
/// * Bring All to Front
public static let windowArrangement: CommandGroupPlacement
/// Placement for commands that present documentation and helpful
/// information to people.
///
/// By default, this group includes the following command in macOS:
/// * App Help
public static let help: CommandGroupPlacement
}
/// Command menus are stand-alone, top-level containers for controls that
/// perform related, app-specific commands.
///
/// 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.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct CommandMenu<Content> : Commands where Content : View {
/// 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).
public init(_ nameKey: LocalizedStringKey, @ViewBuilder content: () -> Content)
/// Creates a new menu 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).
public init(_ name: Text, @ViewBuilder content: () -> Content)
/// Creates a new menu 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).
public init<S>(_ name: S, @ViewBuilder content: () -> Content) where S : StringProtocol
/// The contents of the command hierarchy.
///
/// For any commands that you create, provide a computed `body` property
/// that defines the scene as a composition of other scenes. You can
/// assemble a command hierarchy from built-in commands that SwiftUI
/// provides, as well as other commands that you've defined.
public var body: some Commands { get }
/// The type of commands that represents the body of this command hierarchy.
///
/// When you create custom commands, Swift infers this type from your
/// implementation of the required ``SwiftUI/Commands/body-swift.property``
/// property.
public typealias Body = some 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.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public protocol Commands {
/// The type of commands that represents the body of this command hierarchy.
///
/// When you create custom commands, Swift infers this type from your
/// implementation of the required ``SwiftUI/Commands/body-swift.property``
/// property.
associatedtype Body : Commands
/// The contents of the command hierarchy.
///
/// For any commands that you create, provide a computed `body` property
/// that defines the scene as a composition of other scenes. You can
/// assemble a command hierarchy from built-in commands that SwiftUI
/// provides, as well as other commands that you've defined.
@CommandsBuilder var body: Self.Body { get }
}
/// Constructs command sets from multi-expression closures. Like `ViewBuilder`,
/// it supports up to ten expressions in the closure body.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@resultBuilder public struct CommandsBuilder {
/// Builds an expression within the builder.
public static func buildExpression<Content>(_ content: Content) -> Content where Content : Commands
/// Builds an empty command set from a block containing no statements.
public static func buildBlock() -> EmptyCommands
/// Passes a single command group written as a child group through
/// modified.
public static func buildBlock<C>(_ content: C) -> C where C : Commands
}
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
/// Provides support for "if" statements in multi-statement closures,
/// producing an optional value that is visible only when the condition
/// evaluates to `true`.
public static func buildIf<C>(_ content: C?) -> C? where C : Commands
/// Provides support for "if" statements in multi-statement closures,
/// producing conditional content for the "then" branch.
public static func buildEither<T, F>(first: T) -> _ConditionalContent<T, F> where T : Commands, F : Commands
/// Provides support for "if-else" statements in multi-statement closures,
/// producing conditional content for the "else" branch.
public static func buildEither<T, F>(second: F) -> _ConditionalContent<T, F> where T : Commands, F : Commands
/// Provides support for "if" statements with `#available()` clauses in
/// multi-statement closures, producing conditional content for the "then"
/// branch, i.e. the conditionally-available branch.
public static func buildLimitedAvailability<C>(_ content: C) -> some Commands where C : Commands
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
public static func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> some Commands where C0 : Commands, C1 : Commands
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
public static func buildBlock<C0, C1, C2>(_ c0: C0, _ c1: C1, _ c2: C2) -> some Commands where C0 : Commands, C1 : Commands, C2 : Commands
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
public static func buildBlock<C0, C1, C2, C3>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3) -> some Commands where C0 : Commands, C1 : Commands, C2 : Commands, C3 : Commands
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
public static func buildBlock<C0, C1, C2, C3, C4>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4) -> some Commands where C0 : Commands, C1 : Commands, C2 : Commands, C3 : Commands, C4 : Commands
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5) -> some Commands where C0 : Commands, C1 : Commands, C2 : Commands, C3 : Commands, C4 : Commands, C5 : Commands
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5, C6>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6) -> some Commands where C0 : Commands, C1 : Commands, C2 : Commands, C3 : Commands, C4 : Commands, C5 : Commands, C6 : Commands
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5, C6, C7>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6, _ c7: C7) -> some Commands where C0 : Commands, C1 : Commands, C2 : Commands, C3 : Commands, C4 : Commands, C5 : Commands, C6 : Commands, C7 : Commands
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5, C6, C7, C8>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6, _ c7: C7, _ c8: C8) -> some Commands where C0 : Commands, C1 : Commands, C2 : Commands, C3 : Commands, C4 : Commands, C5 : Commands, C6 : Commands, C7 : Commands, C8 : Commands
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension CommandsBuilder {
public static func buildBlock<C0, C1, C2, C3, C4, C5, C6, C7, C8, C9>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6, _ c7: C7, _ c8: C8, _ c9: C9) -> some Commands where C0 : Commands, C1 : Commands, C2 : Commands, C3 : Commands, C4 : Commands, C5 : Commands, C6 : Commands, C7 : Commands, C8 : Commands, C9 : Commands
}
/// A date picker style that displays the components in a compact, textual
/// format.
///
/// You can also use ``DatePickerStyle/compact`` to construct this style.
@available(iOS 14.0, macCatalyst 13.4, macOS 10.15.4, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct CompactDatePickerStyle : DatePickerStyle {
/// Creates an instance of the compact date picker style.
public init()
/// Returns the appearance and interaction content for a `DatePicker`.
///
/// The system calls this method for each ``DatePicker`` instance in a view
/// hierarchy where this style is the current date picker style.
///
/// - Parameter configuration : The properties of the date picker.
@available(iOS 16.0, macOS 13.0, *)
public func makeBody(configuration: CompactDatePickerStyle.Configuration) -> some View
/// A view representing the appearance and interaction of a `DatePicker`.
public typealias Body = some View
}
/// A control group style that presents its content as a compact menu when the user
/// presses the control, or as a submenu when nested within a larger menu.
///
/// Use ``ControlGroupStyle/compactMenu`` to construct this style.
@available(iOS 16.4, macOS 13.3, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct CompactMenuControlGroupStyle : ControlGroupStyle {
/// Creates a compact menu control group style.
public init()
/// Creates a view representing the body of a control group.
///
/// - Parameter configuration: The properties of the control group instance
/// being created.
///
/// This method will be called for each instance of ``ControlGroup`` created
/// within a view hierarchy where this style is the current
/// `ControlGroupStyle`.
@MainActor public func makeBody(configuration: CompactMenuControlGroupStyle.Configuration) -> some View
/// A view representing the body of a control group.
public typealias Body = some View
}
/// The placement of a container background.
///
/// This method controls where to place a background that you specify with the
/// ``View/containerBackground(_:for:)`` or
/// ``View/containerBackground(for:alignment:content:)`` modifier.
@available(iOS 17.0, tvOS 17.0, macOS 14.0, watchOS 10.0, *)
public struct ContainerBackgroundPlacement : Sendable, Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ContainerBackgroundPlacement, b: ContainerBackgroundPlacement) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// 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.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@frozen public struct ContainerRelativeShape : Shape {
/// Describes this shape as a path within a rectangular frame of reference.
///
/// - Parameter rect: The frame of reference for describing this shape.
///
/// - Returns: A path that describes this shape.
public func path(in rect: CGRect) -> Path
@inlinable public init()
/// The type defining the data to animate.
public typealias AnimatableData = EmptyAnimatableData
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ContainerRelativeShape : InsettableShape {
/// Returns `self` inset by `amount`.
@inlinable public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
public typealias InsetShape = some InsettableShape
}
/// The placement of margins.
///
/// Different views can support customizating margins that appear in
/// different parts of that view. Use values of this type to customize
/// those margins of a particular placement.
///
/// For example, use a ``ContentMarginPlacement/scrollIndicators``
/// placement to customize the margins of scrollable view's scroll
/// indicators separately from the margins of a scrollable view's
/// content.
///
/// Use this type with the ``View/contentMargins(_:for:)`` modifier.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct ContentMarginPlacement {
/// The automatic placement.
///
/// Views that support margin customization can automatically use
/// margins with this placement. For example, a ``ScrollView`` will
/// use this placement to automatically inset both its content and
/// scroll indicators by the specified amount.
public static var automatic: ContentMarginPlacement { get }
/// The scroll content placement.
///
/// Scrollable views like ``ScrollView`` will use this placement to
/// inset their content, but not their scroll indicators.
public static var scrollContent: ContentMarginPlacement { get }
/// The scroll indicators placement.
///
/// Scrollable views like ``ScrollView`` will use this placement to
/// inset their scroll indicators, but not their content.
public static var scrollIndicators: ContentMarginPlacement { get }
}
/// Constants that define how a view's content fills the available space.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public enum ContentMode : Hashable, CaseIterable {
/// An option that resizes the content so it's all within the available space,
/// both vertically and horizontally.
///
/// This mode preserves the content's aspect ratio.
/// If the content doesn't have the same aspect ratio as the available
/// space, the content becomes the same size as the available space on
/// one axis and leaves empty space on the other.
case fit
/// An option that resizes the content so it occupies all available space,
/// both vertically and horizontally.
///
/// This mode preserves the content's aspect ratio.
/// If the content doesn't have the same aspect ratio as the available
/// space, the content becomes the same size as the available space on
/// one axis, and larger on the other axis.
case fill
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ContentMode, b: ContentMode) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [ContentMode]
/// A collection of all values of this type.
public static var allCases: [ContentMode] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ContentMode : Sendable {
}
/// A kind for the content shape of a view.
///
/// The kind is used by the system to influence various effects, hit-testing,
/// and more.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct ContentShapeKinds : OptionSet, Sendable {
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public var rawValue: Int
/// Creates a content shape kind.
public init(rawValue: Int)
/// The kind for hit-testing and accessibility.
///
/// Setting a content shape with this kind causes the view to hit-test
/// using the specified shape.
public static let interaction: ContentShapeKinds
/// The kind for drag and drop previews.
///
/// When using this kind, only the preview shape is affected. To control the
/// shape used to hit-test and start the drag preview, use the `interaction`
/// kind.
@available(watchOS, unavailable)
@available(tvOS, unavailable)
public static let dragPreview: ContentShapeKinds
/// The kind for the focus effect.
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(visionOS, unavailable)
public static let focusEffect: ContentShapeKinds
/// The kind for accessibility visuals and sorting.
///
/// Setting a content shape with this kind causes the accessibility frame
/// and path of the view's underlying accessibility element to match the
/// shape without adjusting the hit-testing shape, updating the visual focus
/// ring that assistive apps, such as VoiceOver, draw, as well as how the
/// element is sorted. Updating the accessibility shape is only required if
/// the shape or size used to hit-test significantly diverges from the visual
/// shape of the view.
///
/// To control the shape for accessibility and hit-testing, use the `interaction` kind.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public static let accessibility: ContentShapeKinds
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = ContentShapeKinds
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = ContentShapeKinds
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = Int
}
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
public enum ContentSizeCategory : Hashable, CaseIterable {
case extraSmall
case small
case medium
case large
case extraLarge
case extraExtraLarge
case extraExtraExtraLarge
case accessibilityMedium
case accessibilityLarge
case accessibilityExtraLarge
case accessibilityExtraExtraLarge
case accessibilityExtraExtraExtraLarge
/// A Boolean value indicating whether the content size category is one that
/// is associated with accessibility.
@available(iOS 13.4, macOS 10.15.4, tvOS 13.4, watchOS 6.2, *)
public var isAccessibilityCategory: Bool { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ContentSizeCategory, b: ContentSizeCategory) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [ContentSizeCategory]
/// A collection of all values of this type.
public static var allCases: [ContentSizeCategory] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ContentSizeCategory {
/// Returns a Boolean value indicating whether the value of the first argument is less than that of the second argument.
public static func < (lhs: ContentSizeCategory, rhs: ContentSizeCategory) -> Bool
/// Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.
public static func <= (lhs: ContentSizeCategory, rhs: ContentSizeCategory) -> Bool
/// Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.
public static func > (lhs: ContentSizeCategory, rhs: ContentSizeCategory) -> Bool
/// Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.
public static func >= (lhs: ContentSizeCategory, rhs: ContentSizeCategory) -> Bool
}
/// A kind of transition that applies to the content within a single view,
/// rather than to the insertion or removal of a view.
///
/// Set the behavior of content transitions within a view with the
/// ``View/contentTransition(_:)`` modifier, passing in one of the defined
/// transitions, such as ``opacity`` or ``interpolate`` as the parameter.
///
/// > Tip: Content transitions only take effect within transactions that apply
/// an ``Animation`` to the views inside the ``View/contentTransition(_:)``
/// modifier.
///
/// Content transitions only take effect within the context of an
/// ``Animation`` block.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct ContentTransition : Equatable, Sendable {
/// The identity content transition, which indicates that content changes
/// shouldn't animate.
///
/// You can pass this value to a ``View/contentTransition(_:)``
/// modifier to selectively disable animations that would otherwise
/// be applied by a ``withAnimation(_:_:)`` block.
public static let identity: ContentTransition
/// A content transition that indicates content fades from transparent
/// to opaque on insertion, and from opaque to transparent on removal.
public static let opacity: ContentTransition
/// A content transition that indicates the views attempt to interpolate
/// their contents during transitions, where appropriate.
///
/// Text views can interpolate transitions when the text views have
/// identical strings. Matching glyph pairs can animate changes to their
/// color, position, size, and any variable properties. Interpolation can
/// apply within a ``Font/Design`` case, but not between cases, or between
/// entirely different fonts. For example, you can interpolate a change
/// between ``Font/Weight/thin`` and ``Font/Weight/black`` variations of a
/// font, since these are both cases of ``Font/Weight``. However, you can't
/// interpolate between the default design of a font and its Italic version,
/// because these are different fonts. Any changes that can't show an
/// interpolated animation use an opacity animation instead.
///
/// Symbol images created with the ``Image/init(systemName:)`` initializer
/// work the same way as text: changes within the same symbol attempt to
/// interpolate the symbol's paths. When interpolation is unavailable, the
/// system uses an opacity transition instead.
public static let interpolate: ContentTransition
/// Creates a content transition intended to be used with `Text`
/// views displaying numeric text. In certain environments changes
/// to the text will enable a nonstandard transition tailored to
/// numeric characters that count up or down.
///
/// - Parameters:
/// - countsDown: true if the numbers represented by the text
/// are counting downwards.
///
/// - Returns: a new content transition.
public static func numericText(countsDown: Bool = false) -> ContentTransition
/// Creates a content transition intended to be used with `Text`
/// views displaying numbers.
///
/// The example below creates a text view displaying a particular
/// value, assigning the same value to the associated transition:
///
/// Text("\(value)")
/// .contentTransition(.numericText(value: value))
///
/// - Parameters:
/// - value: the value represented by the `Text` view being
/// animated. The difference between the old and new values
/// when the text changes will be used to determine the
/// animation direction.
///
/// - Returns: a new content transition.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public static func numericText(value: Double) -> ContentTransition
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ContentTransition, b: ContentTransition) -> Bool
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension ContentTransition {
/// Creates a content transition that applies the symbol Replace
/// animation to symbol images that it is applied to.
///
/// - Parameter config: the animation configuration value.
///
/// - Returns: a new content transition.
public static func symbolEffect<T>(_ effect: T, options: SymbolEffectOptions = .default) -> ContentTransition where T : ContentTransitionSymbolEffect, T : SymbolEffect
/// A content transition that applies the default symbol effect
/// transition to symbol images within the inserted or removed view
/// hierarchy. Other views are unaffected by this transition.
public static var symbolEffect: ContentTransition { get }
}
/// An interface, consisting of a label and additional content, that you
/// display when the content of your app is unavailable to users.
///
/// 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
/// ``ContentUnavailableView/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
/// }
/// }
/// }
/// }
/// }
///
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct ContentUnavailableView<Label, Description, Actions> : View where Label : View, Description : View, Actions : View {
/// Creates an interface, consisting of a label and additional content, that you
/// display when the content of your app is unavailable to users.
///
/// - Parameters:
/// - label: The label that describes the view.
/// - description: The view that describes the interface.
/// - actions: The content of the interface actions.
public init(@ViewBuilder label: () -> Label, @ViewBuilder description: () -> Description = { EmptyView() }, @ViewBuilder actions: () -> Actions = { EmptyView() })
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension ContentUnavailableView where Label == Label<Text, Image>, Description == Text?, Actions == EmptyView {
/// 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.
///
/// - Parameters:
/// - title: A title generated from a localized string.
/// - image: The name of the image resource to lookup.
/// - description: The view that describes the interface.
public init(_ title: LocalizedStringKey, image name: String, description: Text? = nil)
/// 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.
///
/// - Parameters:
/// - title: A title generated from a localized string.
/// - systemImage: The name of the system symbol image resource to lookup.
/// Use the SF Symbols app to look up the names of system symbol images.
/// - description: The view that describes the interface.
public init(_ title: LocalizedStringKey, systemImage name: String, description: Text? = nil)
/// Creates an interface, consisting of a title generated from a string,
/// an image and additional content, that you display when the content of
/// your app is unavailable to users.
///
/// - Parameters:
/// - title: A string used as the title.
/// - image: The name of the image resource to lookup.
/// - description: The view that describes the interface.
public init<S>(_ title: S, image name: String, description: Text? = nil) where S : StringProtocol
/// Creates an interface, consisting of a title generated from a string,
/// a system icon image and additional content, that you display when the
/// content of your app is unavailable to users.
///
/// - Parameters:
/// - title: A string used as the title.
/// - systemImage: The name of the system symbol image resource to lookup.
/// Use the SF Symbols app to look up the names of system symbol images.
/// - description: The view that describes the interface.
public init<S>(_ title: S, systemImage name: String, description: Text? = nil) where S : StringProtocol
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension ContentUnavailableView where Label == SearchUnavailableContent.Label, Description == SearchUnavailableContent.Description, Actions == SearchUnavailableContent.Actions {
/// Creates a `ContentUnavailableView` instance that conveys a search state.
///
/// A `ContentUnavailableView` initialized with this static member is expected to
/// be contained within a searchable view hierarchy. Such a configuration
/// enables the search query to be parsed into the view's description.
///
/// For example, consider the usage of this static member in *ContactsListView*:
///
/// struct ContactsListView: 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
/// }
/// }
/// }
/// }
/// }
///
public static var search: ContentUnavailableView<SearchUnavailableContent.Label, SearchUnavailableContent.Description, SearchUnavailableContent.Actions> { get }
/// Creates a `ContentUnavailableView` instance that conveys a search state.
///
/// For example, consider the usage of this static member in *ContactsListView*:
///
/// struct ContactsListView: View {
/// @ObservedObject private var viewModel = ContactsViewModel()
///
/// var body: some View {
/// NavigationStack {
/// CustomSearchBar(query: $viewModel.searchText)
/// List {
/// ForEach(viewModel.searchResults) { contact in
/// NavigationLink {
/// ContactsView(contact)
/// } label: {
/// Text(contact.name)
/// }
/// }
/// }
/// .navigationTitle("Contacts")
/// .overlay {
/// if viewModel.searchResults.isEmpty {
/// ContentUnavailableView
/// .search(text: viewModel.searchText)
/// }
/// }
/// }
/// }
/// }
///
/// - Parameter text: The search text query.
public static func search(text: String) -> ContentUnavailableView<Label, Description, Actions>
}
/// A container for views that you present as menu items in a context menu.
///
/// A context menu view allows you to present a situationally specific menu
/// that enables taking actions relevant to the current task.
///
/// You can create a context menu by first defining a `ContextMenu` container
/// with the controls that represent the actions that people can take,
/// and then using the ``View/contextMenu(_:)`` view modifier to apply the
/// menu to a view.
///
/// The example below creates and applies a two item context menu container
/// to a ``Text`` view. The Boolean value `shouldShowMenu`, which defaults to
/// true, controls the availability of context menu:
///
/// private let menuItems = 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")
/// }
/// }
///
/// private struct ContextMenuMenuItems: View {
/// @State private var shouldShowMenu = true
///
/// var body: some View {
/// Text("Turtle Rock")
/// .contextMenu(shouldShowMenu ? menuItems : nil)
/// }
/// }
///
/// ![A screenshot of a context menu showing two menu items: Add to
/// Favorites, and Show in Maps.](View-contextMenu-1-iOS)
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Use `contextMenu(menuItems:)` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `contextMenu(menuItems:)` instead.")
@available(tvOS, unavailable)
@available(watchOS, introduced: 6.0, deprecated: 7.0)
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use `contextMenu(menuItems:)` instead.")
public struct ContextMenu<MenuItems> where MenuItems : View {
public init(@ViewBuilder menuItems: () -> MenuItems)
}
@available(macCatalyst 13.0, macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public enum ControlActiveState : Equatable, CaseIterable, Sendable {
case key
case active
case inactive
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ControlActiveState, b: ControlActiveState) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [ControlActiveState]
/// A collection of all values of this type.
public static var allCases: [ControlActiveState] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(macCatalyst 13.0, macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
extension ControlActiveState : Hashable {
}
/// A container view that displays semantically-related controls
/// in a visually-appropriate manner for the context
///
/// 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")
/// }
/// }
/// }
///
@available(iOS 15.0, macOS 12.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public struct ControlGroup<Content> : View where Content : View {
/// Creates a new ControlGroup with the specified children
///
/// - Parameters:
/// - content: the children to display
public init(@ViewBuilder content: () -> Content)
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
@available(iOS 15.0, macOS 12.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension ControlGroup where Content == ControlGroupStyleConfiguration.Content {
/// Creates a control group based on a style configuration.
///
/// Use this initializer within the
/// ``ControlGroupStyle/makeBody(configuration:)`` method of a
/// ``ControlGroupStyle`` instance to create an instance of the control group
/// being styled. This is useful for custom control group styles that modify
/// the current control group style.
///
/// For example, the following code creates a new, custom style that places a
/// red border around the current control group:
///
/// struct RedBorderControlGroupStyle: ControlGroupStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// ControlGroup(configuration)
/// .border(Color.red)
/// }
/// }
///
public init(_ configuration: ControlGroupStyleConfiguration)
}
@available(iOS 16.0, macOS 13.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension ControlGroup {
/// Creates a new control group with the specified content and a label.
///
/// - Parameters:
/// - content: The content to display.
/// - label: A view that describes the purpose of the group.
public init<C, L>(@ViewBuilder content: () -> C, @ViewBuilder label: () -> L) where Content == LabeledControlGroupContent<C, L>, C : View, L : View
}
@available(iOS 16.0, macOS 13.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension ControlGroup {
/// Creates a new control group with the specified content that generates
/// its label from a localized string key.
///
/// - Parameters:
/// - titleKey: The key for the group's localized title, that describes
/// the contents of the group.
/// - label: A view that describes the purpose of the group.
public init<C>(_ titleKey: LocalizedStringKey, @ViewBuilder content: () -> C) where Content == LabeledControlGroupContent<C, Text>, C : View
/// Creates a new control group with the specified content that generates
/// its label from a string.
///
/// - Parameters:
/// - title: A string that describes the contents of the group.
/// - label: A view that describes the purpose of the group.
public init<C, S>(_ title: S, @ViewBuilder content: () -> C) where Content == LabeledControlGroupContent<C, Text>, C : View, S : StringProtocol
}
@available(iOS 16.0, macOS 13.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension ControlGroup {
/// Creates a new control group with the specified content that generates
/// its label from a localized string key and image name.
///
/// - Parameters:
/// - titleKey: The key for the group's localized title, that describes
/// the contents of the group.
/// - systemImage: The name of the image resource to lookup.
/// - label: A view that describes the purpose of the group.
public init<C>(_ titleKey: LocalizedStringKey, systemImage: String, @ViewBuilder content: () -> C) where Content == LabeledControlGroupContent<C, Label<Text, Image>>, C : View
/// Creates a new control group with the specified content that generates
/// its label from a string and image name.
///
/// - Parameters:
/// - title: A string that describes the contents of the group.
/// - systemImage: The name of the image resource to lookup.
/// - label: A view that describes the purpose of the group.
public init<C, S>(_ title: S, systemImage: String, @ViewBuilder content: () -> C) where Content == LabeledControlGroupContent<C, Label<Text, Image>>, C : View, S : StringProtocol
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension ControlGroup {
/// Creates a new control group with the specified content that generates
/// its label from a localized string key and image resource.
///
/// - Parameters:
/// - titleKey: The key for the group's localized title, that describes
/// the contents of the group.
/// - systemImage: The name of the image resource to lookup.
/// - label: A view that describes the purpose of the group.
public init<C>(_ titleKey: LocalizedStringKey, image: ImageResource, @ViewBuilder content: () -> C) where Content == LabeledControlGroupContent<C, Label<Text, Image>>, C : View
/// Creates a new control group with the specified content that generates
/// its label from a string and image name.
///
/// - Parameters:
/// - title: A string that describes the contents of the group.
/// - systemImage: The name of the image resource to lookup.
/// - label: A view that describes the purpose of the group.
public init<C, S>(_ title: S, image: ImageResource, @ViewBuilder content: () -> C) where Content == LabeledControlGroupContent<C, Label<Text, Image>>, C : View, S : StringProtocol
}
/// Defines the implementation of all control groups within a view
/// hierarchy.
///
/// To configure the current `ControlGroupStyle` for a view hierarchy, use the
/// ``View/controlGroupStyle(_:)`` modifier.
@available(iOS 15.0, macOS 12.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public protocol ControlGroupStyle {
/// A view representing the body of a control group.
associatedtype Body : View
/// Creates a view representing the body of a control group.
///
/// - Parameter configuration: The properties of the control group instance
/// being created.
///
/// This method will be called for each instance of ``ControlGroup`` created
/// within a view hierarchy where this style is the current
/// `ControlGroupStyle`.
@ViewBuilder @MainActor func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a `ControlGroup` instance being created.
typealias Configuration = ControlGroupStyleConfiguration
}
@available(iOS 17.0, macOS 14.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ControlGroupStyle where Self == PaletteControlGroupStyle {
/// A control group style that presents its content as a palette.
///
/// - Note: When used outside of menus, this style is rendered as a
/// segmented control.
///
/// Use this style to render a multi-select or a stateless palette.
/// The following example creates a control group that contains both type of shelves:
///
/// Menu {
/// // A multi select palette
/// ControlGroup {
/// ForEach(ColorTags.allCases) { colorTag in
/// Toggle(isOn: $selectedColorTags[colorTag]) {
/// Label(colorTag.name, systemImage: "circle")
/// }
/// .tint(colorTag.color)
/// }
/// }
/// .controlGroupStyle(.palette)
/// .paletteSelectionEffect(.symbolVariant(.fill))
///
/// // A momentary / stateless palette
/// ControlGroup {
/// ForEach(Emotes.allCases) { emote in
/// Button {
/// sendEmote(emote)
/// } label: {
/// Label(emote.name, systemImage: emote.systemImage)
/// }
/// }
/// }
/// .controlGroupStyle(.palette)
/// }
///
/// To apply this style to a control group, or to a view that contains
/// control groups, use the ``View/controlGroupStyle(_:)`` modifier.
public static var palette: PaletteControlGroupStyle { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension ControlGroupStyle where Self == AutomaticControlGroupStyle {
/// The default control group style.
///
/// The default control group style can vary by platform. By default, both
/// platforms use a momentary segmented control style that's appropriate for
/// the environment in which it is rendered.
///
/// You can override a control group's style. To apply the default style to
/// a control group or to a view that contains a control group, use
/// the ``View/controlGroupStyle(_:)`` modifier.
public static var automatic: AutomaticControlGroupStyle { get }
}
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ControlGroupStyle where Self == NavigationControlGroupStyle {
/// The navigation control group style.
///
/// Use this style to group controls related to navigation, such as
/// back/forward buttons or timeline navigation controls.
///
/// The navigation control group style can vary by platform. On iOS, it
/// renders as individual borderless buttons, while on macOS, it displays as
/// a separated momentary segmented control.
///
/// To apply this style to a control group or to a view that contains a
/// control group, use the ``View/controlGroupStyle(_:)`` modifier.
public static var navigation: NavigationControlGroupStyle { get }
}
@available(iOS 16.4, macOS 13.3, tvOS 17.0, *)
@available(watchOS, unavailable)
extension ControlGroupStyle where Self == MenuControlGroupStyle {
/// A control group style that presents its content as a menu when the user
/// presses the control, or as a submenu when nested within a larger menu.
///
/// To apply this style to a control group, or to a view that contains
/// control groups, use the ``View/controlGroupStyle(_:)`` modifier.
public static var menu: MenuControlGroupStyle { get }
}
@available(iOS 16.4, macOS 13.3, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ControlGroupStyle where Self == CompactMenuControlGroupStyle {
/// A control group style that presents its content as a compact menu when the user
/// presses the control, or as a submenu when nested within a larger menu.
///
/// To apply this style to a control group, or to a view that contains
/// control groups, use the ``View/controlGroupStyle(_:)`` modifier.
public static var compactMenu: CompactMenuControlGroupStyle { get }
}
/// The properties of a control group.
@available(iOS 15.0, macOS 12.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public struct ControlGroupStyleConfiguration {
/// A type-erased content of a `ControlGroup`.
public struct Content : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A view that represents the content of the `ControlGroup`.
public let content: ControlGroupStyleConfiguration.Content
/// A type-erased label of a ``ControlGroup``.
@available(iOS 16.0, macOS 13.0, *)
public struct Label : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A view that provides the optional label of the ``ControlGroup``.
@available(iOS 16.0, macOS 13.0, *)
public let label: ControlGroupStyleConfiguration.Label
}
/// The size classes, like regular or small, that you can apply to controls
/// within a view.
@available(iOS 15.0, macOS 10.15, watchOS 9.0, *)
@available(tvOS, unavailable)
public enum ControlSize : CaseIterable, Sendable {
/// A control version that is minimally sized.
case mini
/// A control version that is proportionally smaller size for space-constrained views.
case small
/// A control version that is the default size.
case regular
/// A control version that is prominently sized.
@available(macOS 11.0, *)
case large
@available(iOS 17.0, macOS 14.0, watchOS 10.0, visionOS 1.0, *)
case extraLarge
/// A collection of all values of this type.
public static var allCases: [ControlSize] { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ControlSize, b: ControlSize) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [ControlSize]
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 15.0, macOS 10.15, watchOS 9.0, *)
@available(tvOS, unavailable)
extension ControlSize : Equatable {
}
@available(iOS 15.0, macOS 10.15, watchOS 9.0, *)
@available(tvOS, unavailable)
extension ControlSize : Hashable {
}
/// A resolved coordinate space created by `CoordinateSpaceProtocol`.
///
/// You don't typically use `CoordinateSpace` directly. Instead, use the static
/// properties and functions of `CoordinateSpaceProtocol` such as `.global`,
/// `.local`, and `.named(_:)`.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum CoordinateSpace {
/// The global coordinate space at the root of the view hierarchy.
case global
/// The local coordinate space of the current view.
case local
/// A named reference to a view's local coordinate space.
case named(AnyHashable)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension CoordinateSpace {
public var isGlobal: Bool { get }
public var isLocal: Bool { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension CoordinateSpace : Equatable, Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: CoordinateSpace, rhs: CoordinateSpace) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A frame of reference within the layout system.
///
/// All geometric properties of a view, including size, position, and
/// transform, are defined within the local coordinate space of the view's
/// parent. These values can be converted into other coordinate spaces
/// by passing types conforming to this protocol into functions such as
/// `GeometryProxy.frame(in:)`.
///
/// For example, a named coordinate space allows you to convert the frame
/// of a view into the local coordinate space of an ancestor view by defining
/// a named coordinate space using the `coordinateSpace(_:)` modifier, then
/// passing that same named coordinate space into the `frame(in:)` function.
///
/// VStack {
/// GeometryReader { geometryProxy in
/// let distanceFromTop = geometryProxy.frame(in: "container").origin.y
/// Text("This view is \(distanceFromTop) points from the top of the VStack")
/// }
/// .padding()
/// }
/// .coordinateSpace(.named("container"))
///
/// You don't typically create types conforming to this protocol yourself.
/// Instead, use the system-provided `.global`, `.local`, and `.named(_:)`
/// implementations.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public protocol CoordinateSpaceProtocol {
/// The resolved coordinate space.
var coordinateSpace: CoordinateSpace { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CoordinateSpaceProtocol where Self == NamedCoordinateSpace {
/// The named coordinate space that is added by the system for the innermost
/// containing scroll view that allows scrolling along the provided axis.
public static func scrollView(axis: Axis) -> Self
/// The named coordinate space that is added by the system for the innermost
/// containing scroll view.
public static var scrollView: NamedCoordinateSpace { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CoordinateSpaceProtocol where Self == NamedCoordinateSpace {
/// Creates a named coordinate space using the given value.
///
/// Use the `coordinateSpace(_:)` modifier to assign a name to the local
/// coordinate space of a parent view. Child views can then refer to that
/// coordinate space using `.named(_:)`.
///
/// - Parameter name: A unique value that identifies the coordinate space.
///
/// - Returns: A named coordinate space identified by the given value.
public static func named(_ name: some Hashable) -> NamedCoordinateSpace
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CoordinateSpaceProtocol where Self == LocalCoordinateSpace {
/// The local coordinate space of the current view.
public static var local: LocalCoordinateSpace { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CoordinateSpaceProtocol where Self == GlobalCoordinateSpace {
/// The global coordinate space at the root of the view hierarchy.
public static var global: GlobalCoordinateSpace { get }
}
/// A keyframe that uses a cubic curve to smoothly interpolate between values.
///
/// If you don't specify a start or end velocity, SwiftUI automatically
/// computes a curve that maintains smooth motion between keyframes.
///
/// Adjacent cubic keyframes result in a Catmull-Rom spline.
///
/// If a cubic keyframe follows a different type of keyframe, such as a linear
/// keyframe, the end velocity of the segment defined by the previous keyframe
/// will be used as the starting velocity.
///
/// Likewise, if a cubic keyframe is followed by a different type of keyframe,
/// the initial velocity of the next segment is used as the end velocity of the
/// segment defined by this keyframe.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct CubicKeyframe<Value> : KeyframeTrackContent where Value : Animatable {
/// Creates a new keyframe using the given value and timestamp.
///
/// - Parameters:
/// - to: The value of the keyframe.
/// - startVelocity: The velocity of the value at the beginning of the
/// segment, or `nil` to automatically compute the velocity to maintain
/// smooth motion.
/// - endVelocity: The velocity of the value at the end of the segment,
/// or `nil` to automatically compute the velocity to maintain smooth
/// motion.
/// - duration: The duration of the segment defined by this keyframe.
public init(_ to: Value, duration: TimeInterval, startVelocity: Value? = nil, endVelocity: Value? = nil)
public typealias Body = CubicKeyframe<Value>
}
/// A type that defines how an animatable value changes over time.
///
/// Use this protocol to create a type that changes an animatable value over
/// time, which produces a custom visual transition of a view. For example, the
/// follow code changes an animatable value using an elastic ease-in ease-out
/// function:
///
/// struct ElasticEaseInEaseOutAnimation: CustomAnimation {
/// let duration: TimeInterval
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// if time > duration { return nil } // The animation has finished.
///
/// let p = time / duration
/// let s = sin((20 * p - 11.125) * ((2 * Double.pi) / 4.5))
/// if p < 0.5 {
/// return value.scaled(by: -(pow(2, 20 * p - 10) * s) / 2)
/// } else {
/// return value.scaled(by: (pow(2, -20 * p + 10) * s) / 2 + 1)
/// }
/// }
/// }
///
/// > Note: To maintain state during the life span of a custom animation, use
/// the ``AnimationContext/state`` property available on the `context`
/// parameter value. You can also use context's
/// ``AnimationContext/environment`` property to retrieve environment values
/// from the view that created the custom animation. For more information, see
/// ``AnimationContext``.
///
/// To create an ``Animation`` instance of a custom animation, use the
/// ``Animation/init(_:)`` initializer, passing in an instance of a custom
/// animation; for example:
///
/// Animation(ElasticEaseInEaseOutAnimation(duration: 5.0))
///
/// To help make view code more readable, extend ``Animation`` and add a static
/// property and function that returns an `Animation` instance of a custom
/// animation. For example, the following code adds the static property
/// `elasticEaseInEaseOut` that returns the elastic ease-in ease-out animation
/// with a default duration of `0.35` seconds. Next, the code adds a method
/// that returns the animation with a specified duration.
///
/// extension Animation {
/// static var elasticEaseInEaseOut: Animation { elasticEaseInEaseOut(duration: 0.35) }
/// static func elasticEaseInEaseOut(duration: TimeInterval) -> Animation {
/// Animation(ElasticEaseInEaseOutAnimation(duration: duration))
/// }
/// }
///
/// To animate a view with the elastic ease-in ease-out animation, a view calls
/// either `.elasticEaseInEaseOut` or `.elasticEaseInEaseOut(duration:)`. For
/// example, the follow code includes an Animate button that, when clicked,
/// animates a circle as it moves from one edge of the view to the other,
/// using the elastic ease-in ease-out animation with a duration of `5`
/// seconds:
///
/// struct ElasticEaseInEaseOutView: View {
/// @State private var isActive = false
///
/// var body: some View {
/// VStack(alignment: isActive ? .trailing : .leading) {
/// Circle()
/// .frame(width: 100.0)
/// .foregroundColor(.accentColor)
///
/// Button("Animate") {
/// withAnimation(.elasticEaseInEaseOut(duration: 5.0)) {
/// isActive.toggle()
/// }
/// }
/// .frame(maxWidth: .infinity)
/// }
/// .padding()
/// }
/// }
///
/// @Video(source: "animation-20-elastic.mp4", poster: "animation-20-elastic.png", alt: "A video that shows a circle that moves from one edge of the view to the other using an elastic ease-in ease-out animation. The circle's initial position is near the leading edge of the view. The circle begins moving slightly towards the leading, then towards trail edges of the view before it moves off the leading edge showing only two-thirds of the circle. The circle then moves quickly to the trailing edge of the view, going slightly beyond the edge so that only two-thirds of the circle is visible. The circle bounces back into full view before settling into position near the trailing edge of the view. The circle repeats this animation in reverse, going from the trailing edge of the view to the leading edge.")
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public protocol CustomAnimation : Hashable {
/// Calculates the value of the animation at the specified time.
///
/// Implement this method to calculate and return the value of the
/// animation at a given point in time. If the animation has finished,
/// return `nil` as the value. This signals to the system that it can
/// remove the animation.
///
/// If your custom animation needs to maintain state between calls to the
/// `animate(value:time:context:)` method, store the state data in
/// `context`. This makes the data available to the method next time
/// the system calls it. To learn more about managing state data in a
/// custom animation, see ``AnimationContext``.
///
/// - Parameters:
/// - value: The vector to animate towards.
/// - time: The elapsed time since the start of the animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: The current value of the animation, or `nil` if the
/// animation has finished.
func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic
/// Calculates the velocity of the animation at a specified time.
///
/// Implement this method to provide the velocity of the animation at a
/// given time. Should subsequent animations merge with the animation,
/// the system preserves continuity of the velocity between animations.
///
/// The default implementation of this method returns `nil`.
///
/// > Note: State and environment data is available to this method via the
/// `context` parameter, but `context` is read-only. This behavior is
/// different than with ``animate(value:time:context:)`` and
/// ``shouldMerge(previous:value:time:context:)-7f4ts`` where `context` is
/// an `inout` parameter, letting you change the context including state
/// data of the animation. For more information about managing state data
/// in a custom animation, see ``AnimationContext``.
///
/// - Parameters:
/// - value: The vector to animate towards.
/// - time: The amount of time since the start of the animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: The current velocity of the animation, or `nil` if the
/// animation has finished.
func velocity<V>(value: V, time: TimeInterval, context: AnimationContext<V>) -> V? where V : VectorArithmetic
/// Determines whether an instance of the animation can merge with other
/// instance of the same type.
///
/// When a view creates a new animation on an animatable value that already
/// has a running animation of the same animation type, the system calls
/// the `shouldMerge(previous:value:time:context:)` method on the new
/// instance to determine whether it can merge the two instance. Implement
/// this method if the animation can merge with another instance. The
/// default implementation returns `false`.
///
/// If `shouldMerge(previous:value:time:context:)` returns `true`, the
/// system merges the new animation instance with the previous animation.
/// The system provides to the new instance the state and elapsed time from
/// the previous one. Then it removes the previous animation.
///
/// If this method returns `false`, the system doesn't merge the animation
/// with the previous one. Instead, both animations run together and the
/// system combines their results.
///
/// If your custom animation needs to maintain state between calls to the
/// `shouldMerge(previous:value:time:context:)` method, store the state
/// data in `context`. This makes the data available to the method next
/// time the system calls it. To learn more, see ``AnimationContext``.
///
/// - Parameters:
/// - previous: The previous running animation.
/// - value: The vector to animate towards.
/// - time: The amount of time since the start of the previous animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: A Boolean value of `true` if the animation should merge with
/// the previous animation; otherwise, `false`.
func shouldMerge<V>(previous: Animation, value: V, time: TimeInterval, context: inout AnimationContext<V>) -> Bool where V : VectorArithmetic
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CustomAnimation {
/// Calculates the velocity of the animation at a specified time.
///
/// Implement this method to provide the velocity of the animation at a
/// given time. Should subsequent animations merge with the animation,
/// the system preserves continuity of the velocity between animations.
///
/// The default implementation of this method returns `nil`.
///
/// > Note: State and environment data is available to this method via the
/// `context` parameter, but `context` is read-only. This behavior is
/// different than with ``animate(value:time:context:)`` and
/// ``shouldMerge(previous:value:time:context:)-7f4ts`` where `context` is
/// an `inout` parameter, letting you change the context including state
/// data of the animation. For more information about managing state data
/// in a custom animation, see ``AnimationContext``.
///
/// - Parameters:
/// - value: The vector to animate towards.
/// - time: The amount of time since the start of the animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: The current velocity of the animation, or `nil` if the
/// animation has finished.
public func velocity<V>(value: V, time: TimeInterval, context: AnimationContext<V>) -> V? where V : VectorArithmetic
/// Determines whether an instance of the animation can merge with other
/// instance of the same type.
///
/// When a view creates a new animation on an animatable value that already
/// has a running animation of the same animation type, the system calls
/// the `shouldMerge(previous:value:time:context:)` method on the new
/// instance to determine whether it can merge the two instance. Implement
/// this method if the animation can merge with another instance. The
/// default implementation returns `false`.
///
/// If `shouldMerge(previous:value:time:context:)` returns `true`, the
/// system merges the new animation instance with the previous animation.
/// The system provides to the new instance the state and elapsed time from
/// the previous one. Then it removes the previous animation.
///
/// If this method returns `false`, the system doesn't merge the animation
/// with the previous one. Instead, both animations run together and the
/// system combines their results.
///
/// If your custom animation needs to maintain state between calls to the
/// `shouldMerge(previous:value:time:context:)` method, store the state
/// data in `context`. This makes the data available to the method next
/// time the system calls it. To learn more, see ``AnimationContext``.
///
/// - Parameters:
/// - previous: The previous running animation.
/// - value: The vector to animate towards.
/// - time: The amount of time since the start of the previous animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: A Boolean value of `true` if the animation should merge with
/// the previous animation; otherwise, `false`.
public func shouldMerge<V>(previous: Animation, value: V, time: TimeInterval, context: inout AnimationContext<V>) -> Bool where V : VectorArithmetic
}
/// The definition of a custom detent with a calculated height.
///
/// 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 {
/// static func height(in context: Context) -> CGFloat? {
/// 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)
/// }
/// }
/// }
///
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public protocol CustomPresentationDetent {
/// Calculates and returns a height based on the context.
///
/// - Parameter context: Information that can help to determine the
/// height of the detent.
///
/// - Returns: The height of the detent, or `nil` if the detent should be
/// inactive based on the `contenxt` input.
static func height(in context: Self.Context) -> CGFloat?
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension CustomPresentationDetent {
/// Information that you can use to calculate the height of a custom detent.
public typealias Context = PresentationDetent.Context
}
/// Conforming types represent items that can be placed in various locations
/// in a customizable toolbar.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public protocol CustomizableToolbarContent : ToolbarContent where Self.Body : CustomizableToolbarContent {
}
extension CustomizableToolbarContent {
/// Configures the customization behavior of customizable toolbar content.
///
/// Customizable toolbar items support different kinds of customization:
/// * A user can add an an item that is not in the toolbar.
/// * A user can remove an item that is in the toolbar.
/// * A user can move an item within the toolbar.
///
/// Based on the customization behavior of the toolbar items, different
/// edits will be supported.
///
/// Use this modifier to the customization behavior a user can
/// perform on your toolbar items. In the following example, the
/// customizable toolbar item supports all of the different kinds of
/// toolbar customizations and starts in the toolbar.
///
/// ContentView()
/// .toolbar(id: "main") {
/// ToolbarItem(id: "new") {
/// // new button here
/// }
/// }
///
/// You can create an item that can not be removed from the toolbar
/// or moved within the toolbar by passing a value of
/// ``ToolbarCustomizationBehavior/disabled`` to this modifier.
///
/// ContentView()
/// .toolbar(id: "main") {
/// ToolbarItem(id: "new") {
/// // new button here
/// }
/// .customizationBehavior(.disabled)
/// }
///
/// You can create an item that can not be removed from the toolbar, but
/// can be moved by passing a value of
/// ``ToolbarCustomizationBehavior/reorderable``.
///
/// ContentView()
/// .toolbar(id: "main") {
/// ToolbarItem(id: "new") {
/// // new button here
/// }
/// .customizationBehavior(.reorderable)
/// }
///
/// - Parameter behavior: The customization behavior of the customizable
/// toolbar content.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public func customizationBehavior(_ behavior: ToolbarCustomizationBehavior) -> some CustomizableToolbarContent
}
extension CustomizableToolbarContent {
/// Configures the way customizable toolbar items with the default
/// behavior behave.
///
/// Default customizable items support a variety of edits by the user.
/// * A user can add an an item that is not in the toolbar.
/// * A user can remove an item that is in the toolbar.
/// * A user can move an item within the toolbar.
///
/// By default, all default customizable items will be initially
/// present in the toolbar. Provide a value of
/// ``Visibility/hidden`` to this modifier to specify that items should
/// initially be hidden from the user, and require them to add those items
/// to the toolbar if desired.
///
/// ContentView()
/// .toolbar(id: "main") {
/// ToolbarItem(id: "new") {
/// // new button here
/// }
/// .defaultCustomization(.hidden)
/// }
///
/// You can ensure that the user can always use an item with default
/// customizability, even if it's removed from the customizable toolbar. To
/// do this, provide the ``ToolbarCustomizationOptions/alwaysAvailable``
/// option. Unlike a customizable item with a customization behavior of
/// ``ToolbarCustomizationBehavior/none`` which always remain in the toolbar
/// itself, these items will remain in the overflow if the user removes them
/// from the toolbar.
///
/// Provide a value of ``ToolbarCustomizationOptions/alwaysAvailable`` to
/// the options parameter of this modifier to receive this behavior.
///
/// ContentView()
/// .toolbar(id: "main") {
/// ToolbarItem(id: "new") {
/// // new button here
/// }
/// .defaultCustomization(options: .alwaysAvailable)
/// }
///
/// - Parameters:
/// - defaultVisibility: The default visibility of toolbar content
/// with the default customization behavior.
/// - options: The customization options to configure the behavior
/// of toolbar content with the default customization behavior.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public func defaultCustomization(_ defaultVisibility: Visibility = .automatic, options: ToolbarCustomizationOptions = []) -> some CustomizableToolbarContent
/// Configures customizable toolbar content with the default visibility
/// and options.
///
/// Use the ``CustomizableToolbarContent/defaultCustomization(_:options:)``
/// modifier providing either a `defaultVisibility` or `options` instead.
@available(iOS, introduced: 16.0, deprecated: 16.0, message: "Please provide either a visibility or customization options")
@available(macOS, introduced: 13.0, deprecated: 13.0, message: "Please provide either a visibility or customization options")
@available(tvOS, introduced: 16.0, deprecated: 16.0, message: "Please provide either a visibility or customization options")
@available(watchOS, introduced: 9.0, deprecated: 9.0, message: "Please provide either a visibility or customization options")
public func defaultCustomization() -> some CustomizableToolbarContent
}
/// A control for selecting an absolute date.
///
/// 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
/// <doc://com.apple.documentation/documentation/Foundation/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
/// <doc://com.apple.documentation/documentation/Foundation/Date>.
///
/// @State private var date = Date()
///
/// var body: some View {
/// DatePicker(
/// "Start Date",
/// selection: $date,
/// displayedComponents: [.date]
/// )
/// }
///
/// ![An iOS date picker, consisting of a label that says Start Date, and a
/// label showing the date Apr 1, 1976.](SwiftUI-DatePicker-basic.png)
///
/// 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).
///
/// @State private var date = Date()
/// let dateRange: ClosedRange<Date> = {
/// 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]
/// )
/// }
///
/// ![A SwiftUI standard date picker on iOS, with the label Start Date, and
/// buttons for the time 5:15 PM and the date Jul 31,
/// 2021.](SwiftUI-DatePicker-selectFromRange.png)
///
/// ### Styling date pickers
///
/// To use a different style of date picker, use the
/// ``View/datePickerStyle(_:)`` view modifier. The following example shows the
/// graphical date picker style.
///
/// @State private var date = Date()
///
/// var body: some View {
/// DatePicker(
/// "Start Date",
/// selection: $date,
/// displayedComponents: [.date]
/// )
/// .datePickerStyle(.graphical)
/// }
///
/// ![A SwiftUI date picker using the graphical style, with the label Start Date
/// and wheels for the month, day, and year, showing the selection
/// October 22, 2021.](SwiftUI-DatePicker-graphicalStyle.png)
///
@available(iOS 13.0, macOS 10.15, watchOS 10.0, *)
@available(tvOS, unavailable)
public struct DatePicker<Label> : View where Label : View {
public typealias Components = DatePickerComponents
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
@available(iOS 13.0, macOS 10.15, watchOS 10.0, *)
@available(tvOS, unavailable)
extension DatePicker {
/// Creates an instance that selects a `Date` with an unbounded range.
///
/// - Parameters:
/// - selection: The date value being displayed and selected.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
/// - label: A view that describes the use of the date.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init(selection: Binding<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date], @ViewBuilder label: () -> Label)
/// Creates an instance that selects a `Date` in a closed range.
///
/// - Parameters:
/// - selection: The date value being displayed and selected.
/// - range: The inclusive range of selectable dates.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
/// - label: A view that describes the use of the date.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init(selection: Binding<Date>, in range: ClosedRange<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date], @ViewBuilder label: () -> Label)
/// Creates an instance that selects a `Date` on or after some start date.
///
/// - Parameters:
/// - selection: The date value being displayed and selected.
/// - range: The open range from some selectable start date.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
/// - label: A view that describes the use of the date.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init(selection: Binding<Date>, in range: PartialRangeFrom<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date], @ViewBuilder label: () -> Label)
/// Creates an instance that selects a `Date` on or before some end date.
///
/// - Parameters:
/// - selection: The date value being displayed and selected.
/// - range: The open range before some selectable end date.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
/// - label: A view that describes the use of the date.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init(selection: Binding<Date>, in range: PartialRangeThrough<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date], @ViewBuilder label: () -> Label)
}
@available(iOS 13.0, macOS 10.15, watchOS 10.0, *)
@available(tvOS, unavailable)
extension DatePicker where Label == Text {
/// Creates an instance that selects a `Date` with an unbounded range.
///
/// - Parameters:
/// - titleKey: The key for the localized title of `self`, describing
/// its purpose.
/// - selection: The date value being displayed and selected.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init(_ titleKey: LocalizedStringKey, selection: Binding<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date])
/// Creates an instance that selects a `Date` in a closed range.
///
/// - Parameters:
/// - titleKey: The key for the localized title of `self`, describing
/// its purpose.
/// - selection: The date value being displayed and selected.
/// - range: The inclusive range of selectable dates.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init(_ titleKey: LocalizedStringKey, selection: Binding<Date>, in range: ClosedRange<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date])
/// Creates an instance that selects a `Date` on or after some start date.
///
/// - Parameters:
/// - titleKey: The key for the localized title of `self`, describing
/// its purpose.
/// - selection: The date value being displayed and selected.
/// - range: The open range from some selectable start date.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init(_ titleKey: LocalizedStringKey, selection: Binding<Date>, in range: PartialRangeFrom<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date])
/// Creates an instance that selects a `Date` on or before some end date.
///
/// - Parameters:
/// - titleKey: The key for the localized title of `self`, describing
/// its purpose.
/// - selection: The date value being displayed and selected.
/// - range: The open range before some selectable end date.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init(_ titleKey: LocalizedStringKey, selection: Binding<Date>, in range: PartialRangeThrough<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date])
/// Creates an instance that selects a `Date` within the given range.
///
/// - Parameters:
/// - title: The title of `self`, describing its purpose.
/// - selection: The date value being displayed and selected.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init<S>(_ title: S, selection: Binding<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date]) where S : StringProtocol
/// Creates an instance that selects a `Date` in a closed range.
///
/// - Parameters:
/// - title: The title of `self`, describing its purpose.
/// - selection: The date value being displayed and selected.
/// - range: The inclusive range of selectable dates.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init<S>(_ title: S, selection: Binding<Date>, in range: ClosedRange<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date]) where S : StringProtocol
/// Creates an instance that selects a `Date` on or after some start date.
///
/// - Parameters:
/// - title: The title of `self`, describing its purpose.
/// - selection: The date value being displayed and selected.
/// - range: The open range from some selectable start date.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init<S>(_ title: S, selection: Binding<Date>, in range: PartialRangeFrom<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date]) where S : StringProtocol
/// Creates an instance that selects a `Date` on or before some end date.
///
/// - Parameters:
/// - title: The title of `self`, describing its purpose.
/// - selection: The date value being displayed and selected.
/// - range: The open range before some selectable end date.
/// - displayedComponents: The date components that user is able to
/// view and edit. Defaults to `[.hourAndMinute, .date]`. On watchOS,
/// if `.hourAndMinute` or `.hourMinuteAndSecond` are included with
/// `.date`, only `.date` is displayed.
@available(watchOS 10.0, *)
@available(tvOS, unavailable)
public init<S>(_ title: S, selection: Binding<Date>, in range: PartialRangeThrough<Date>, displayedComponents: DatePicker<Label>.Components = [.hourAndMinute, .date]) where S : StringProtocol
}
@available(iOS 13.0, macOS 10.15, watchOS 10.0, *)
@available(tvOS, unavailable)
public struct DatePickerComponents : OptionSet, Sendable {
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public let rawValue: UInt
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
public init(rawValue: UInt)
/// Displays hour and minute components based on the locale
public static let hourAndMinute: DatePickerComponents
/// Displays day, month, and year based on the locale
public static let date: DatePickerComponents
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = DatePickerComponents
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = DatePickerComponents
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = UInt
}
/// A type that specifies the appearance and interaction of all date pickers
/// within a view hierarchy.
///
/// To configure the current date picker style for a view hierarchy, use the
/// ``View/datePickerStyle(_:)`` modifier.
@available(iOS 13.0, macOS 10.15, watchOS 10.0, *)
@available(tvOS, unavailable)
public protocol DatePickerStyle {
/// A view representing the appearance and interaction of a `DatePicker`.
associatedtype Body : View
/// Returns the appearance and interaction content for a `DatePicker`.
///
/// The system calls this method for each ``DatePicker`` instance in a view
/// hierarchy where this style is the current date picker style.
///
/// - Parameter configuration : The properties of the date picker.
@available(iOS 16.0, macOS 13.0, *)
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
/// A type alias for the properties of a `DatePicker`.
@available(iOS 16.0, macOS 13.0, *)
typealias Configuration = DatePickerStyleConfiguration
}
@available(iOS 13.0, macOS 10.15, watchOS 10.0, *)
@available(tvOS, unavailable)
extension DatePickerStyle where Self == DefaultDatePickerStyle {
/// The default style for date pickers.
public static var automatic: DefaultDatePickerStyle { get }
}
@available(macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
extension DatePickerStyle where Self == StepperFieldDatePickerStyle {
/// A system style that displays the components in an editable field, with
/// adjoining stepper that can increment/decrement the selected component.
///
/// This style is useful when space is constrained and users expect to
/// make specific date and time selections.
public static var stepperField: StepperFieldDatePickerStyle { get }
}
@available(macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
extension DatePickerStyle where Self == FieldDatePickerStyle {
/// A date picker style that displays the components in an editable field.
///
/// You can use this style when space is constrained and users expect to make
/// specific date and time selections. However, you should generally use
/// ``DatePickerStyle/stepperField`` instead of this style, unless your your app
/// requires hiding the stepper.
public static var field: FieldDatePickerStyle { get }
}
@available(iOS 14.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DatePickerStyle where Self == GraphicalDatePickerStyle {
/// A date picker style that displays an interactive calendar or clock.
///
/// This style is useful when you want to allow browsing through days in a
/// calendar, or when the look of a clock face is appropriate.
public static var graphical: GraphicalDatePickerStyle { get }
}
@available(iOS 14.0, macCatalyst 13.4, macOS 10.15.4, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DatePickerStyle where Self == CompactDatePickerStyle {
/// A date picker style that displays the components in a compact, textual
/// format.
///
/// Use this style when space is constrained and users expect to make
/// specific date and time selections. Some variants may include rich
/// editing controls in a pop up.
public static var compact: CompactDatePickerStyle { get }
}
/// The properties of a `DatePicker`.
@available(iOS 16.0, macOS 13.0, watchOS 10.0, *)
@available(tvOS, unavailable)
public struct DatePickerStyleConfiguration {
/// A type-erased label of a `DatePicker`.
public struct Label : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A description of the `DatePicker`.
public let label: DatePickerStyleConfiguration.Label
/// The date value being displayed and selected.
@Binding public var selection: Date { get nonmutating set }
public var $selection: Binding<Date> { get }
/// The oldest selectable date.
public var minimumDate: Date?
/// The most recent selectable date.
public var maximumDate: Date?
/// The date components that the user is able to view and edit.
public var displayedComponents: DatePickerComponents
}
/// The default button style, based on the button's context.
///
/// You can also use ``PrimitiveButtonStyle/automatic`` to construct this style.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct DefaultButtonStyle : PrimitiveButtonStyle {
/// Creates a default button style.
public init()
/// Creates a view that represents the body of a button.
///
/// The system calls this method for each ``Button`` instance in a view
/// hierarchy where this style is the current button style.
///
/// - Parameter configuration : The properties of the button.
public func makeBody(configuration: DefaultButtonStyle.Configuration) -> some View
/// A view that represents the body of a button.
public typealias Body = some View
}
/// The default style for date pickers.
///
/// You can also use ``DatePickerStyle/automatic`` to construct this style.
@available(iOS 13.0, macOS 10.15, watchOS 10.0, *)
@available(tvOS, unavailable)
public struct DefaultDatePickerStyle : DatePickerStyle {
/// Creates an instance of the default date picker style.
public init()
/// Returns the appearance and interaction content for a `DatePicker`.
///
/// The system calls this method for each ``DatePicker`` instance in a view
/// hierarchy where this style is the current date picker style.
///
/// - Parameter configuration : The properties of the date picker.
@available(iOS 16.0, macOS 13.0, *)
public func makeBody(configuration: DefaultDatePickerStyle.Configuration) -> some View
/// A view representing the appearance and interaction of a `DatePicker`.
public typealias Body = some View
}
/// The default type of the current value label when used by a date-relative
/// progress view.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct DefaultDateProgressLabel : View {
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
/// Prioritizations for default focus preferences when evaluating where
/// to move focus in different circumstances.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct DefaultFocusEvaluationPriority : Sendable {
/// Use the default focus preference when focus moves into the affected
/// branch automatically, but ignore it when the movement is driven by a
/// user-initiated navigation command.
public static let automatic: DefaultFocusEvaluationPriority
/// Always use the default focus preference when focus moves into the
/// affected branch.
public static let userInitiated: DefaultFocusEvaluationPriority
}
/// The default gauge view style in the current context of the view being
/// styled.
///
/// You can also use ``GaugeStyle/automatic`` to construct this style.
@available(iOS 16.0, macOS 13.0, watchOS 7.0, *)
@available(tvOS, unavailable)
public struct DefaultGaugeStyle : GaugeStyle {
/// Creates a default gauge style.
public init()
/// Creates a view representing the body of a gauge.
///
/// The system calls this modifier on each instance of gauge within a view
/// hierarchy where this style is the current gauge style.
///
/// - Parameter configuration: The properties to apply to the gauge instance.
public func makeBody(configuration: DefaultGaugeStyle.Configuration) -> some View
/// A view representing the body of a gauge.
public typealias Body = some View
}
/// The default style for group box views.
///
/// You can also use ``GroupBoxStyle/automatic`` to construct this style.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DefaultGroupBoxStyle : GroupBoxStyle {
public init()
/// Creates a view representing the body of a group box.
///
/// SwiftUI calls this method for each instance of ``SwiftUI/GroupBox``
/// created within a view hierarchy where this style is the current
/// group box style.
///
/// - Parameter configuration: The properties of the group box instance being
/// created.
public func makeBody(configuration: DefaultGroupBoxStyle.Configuration) -> some View
/// A view that represents the body of a group box.
public typealias Body = some View
}
/// The default label style in the current context.
///
/// You can also use ``LabelStyle/automatic`` to construct this style.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct DefaultLabelStyle : LabelStyle {
/// Creates an automatic label style.
public init()
/// Creates a view that represents the body of a label.
///
/// The system calls this method for each ``Label`` instance in a view
/// hierarchy where this style is the current label style.
///
/// - Parameter configuration: The properties of the label.
public func makeBody(configuration: DefaultLabelStyle.Configuration) -> some View
/// A view that represents the body of a label.
public typealias Body = some View
}
/// The list style that describes a platform's default behavior and appearance
/// for a list.
///
/// You can also use ``ListStyle/automatic`` to construct this style.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct DefaultListStyle : ListStyle {
/// Creates a default list style.
public init()
}
/// The default menu button style.
@available(iOS, unavailable)
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `menuStyle(.automatic)` instead.")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct DefaultMenuButtonStyle : MenuButtonStyle {
public init()
}
/// The default menu style, based on the menu's context.
///
/// You can also use ``MenuStyle/automatic`` to construct this style.
@available(iOS 14.0, macOS 11.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public struct DefaultMenuStyle : MenuStyle {
/// Creates a default menu style.
public init()
/// Creates a view that represents the body of a menu.
///
/// - Parameter configuration: The properties of the menu.
///
/// The system calls this method for each ``Menu`` instance in a view
/// hierarchy where this style is the current menu style.
public func makeBody(configuration: DefaultMenuStyle.Configuration) -> some View
/// A view that represents the body of a menu.
public typealias Body = some View
}
/// The default navigation view style.
///
/// You can also use ``NavigationViewStyle/automatic`` to construct this style.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationStack or NavigationSplitView instead")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "replace styled NavigationView with NavigationSplitView instead")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationStack or NavigationSplitView instead")
@available(watchOS, introduced: 7.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationStack or NavigationSplitView instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationStack or NavigationSplitView instead")
public struct DefaultNavigationViewStyle : NavigationViewStyle {
public init()
}
/// The default picker style, based on the picker's context.
///
/// You can also use ``PickerStyle/automatic`` to construct this style.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct DefaultPickerStyle : PickerStyle {
/// Creates a default picker style.
public init()
}
/// The default progress view style in the current context of the view being
/// styled.
///
/// Use ``ProgressViewStyle/automatic`` to construct this style.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct DefaultProgressViewStyle : ProgressViewStyle {
/// Creates a default progress view style.
public init()
/// Creates a view representing the body of a progress view.
///
/// - Parameter configuration: The properties of the progress view being
/// created.
///
/// The view hierarchy calls this method for each progress view where this
/// style is the current progress view style.
///
/// - Parameter configuration: The properties of the progress view, such as
/// its preferred progress type.
public func makeBody(configuration: DefaultProgressViewStyle.Configuration) -> some View
/// A view representing the body of a progress view.
public typealias Body = some View
}
/// The default label to use for a settings link.
///
/// You don't use this type directly. Instead, the system creates it
/// automatically when you construct a ``SettingsLink`` with the default label.
@available(macOS 14.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct DefaultSettingsLinkLabel : View {
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
/// The default label used for a share link.
///
/// You don't use this type directly. Instead, ``ShareLink`` uses it
/// automatically depending on how you create a share link.
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
public struct DefaultShareLinkLabel : View {
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
/// The default `TabView` style.
///
/// You can also use ``TabViewStyle/automatic`` to construct this style.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct DefaultTabViewStyle : TabViewStyle {
public init()
}
/// The default text field style, based on the text field's context.
///
/// You can also use ``TextFieldStyle/automatic`` to construct this style.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct DefaultTextFieldStyle : TextFieldStyle {
public init()
}
/// The default toggle style.
///
/// Use the ``ToggleStyle/automatic`` static variable to create this style:
///
/// Toggle("Enhance Sound", isOn: $isEnhanced)
/// .toggleStyle(.automatic)
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct DefaultToggleStyle : ToggleStyle {
/// Creates a default toggle style.
///
/// Don't call this initializer directly. Instead, use the
/// ``ToggleStyle/automatic`` static variable to create this style:
///
/// Toggle("Enhance Sound", isOn: $isEnhanced)
/// .toggleStyle(.automatic)
///
public init()
/// Creates a view that represents the body of a toggle.
///
/// SwiftUI implements this required method of the ``ToggleStyle``
/// protocol to define the behavior and appearance of the
/// ``ToggleStyle/automatic`` toggle style. Don't call this method
/// directly. Rather, the system calls this method for each
/// ``Toggle`` instance in a view hierarchy that needs the default
/// style.
///
/// - Parameter configuration: The properties of the toggle, including a
/// label and a binding to the toggle's state.
/// - Returns: A view that acts as a toggle.
public func makeBody(configuration: DefaultToggleStyle.Configuration) -> some View
/// A view that represents the appearance and interaction of a toggle.
///
/// SwiftUI infers this type automatically based on the ``View``
/// instance that you return from your implementation of the
/// ``makeBody(configuration:)`` method.
public typealias Body = some View
}
/// The default window style.
///
/// You can also use ``WindowStyle/automatic`` to construct this style.
@available(macOS 11.0, visionOS 1.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DefaultWindowStyle : WindowStyle {
public init()
}
/// The default window toolbar style.
///
/// You can also use ``WindowToolbarStyle/automatic`` to construct this style.
@available(macOS 11.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct DefaultWindowToolbarStyle : WindowToolbarStyle {
/// Creates a default window toolbar style.
public init()
}
/// The severity of an alert or confirmation dialog.
///
/// 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.
@available(iOS 17.0, macOS 13.0, tvOS 17.0, watchOS 10.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
public struct DialogSeverity : Equatable {
/// The default dialog severity. Alerts that present an error will use `.critical`
/// and all others will use `.standard`.
public static let automatic: 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.
///
/// On macOS, a dialog with critical severity will display a large caution
/// symbol with the app icon as an overlay.
public static let critical: DialogSeverity
/// A severity that indicates the dialog is being displayed for the purpose
/// of presenting information to the user.
@available(macOS 14.0, *)
public static let standard: DialogSeverity
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: DialogSeverity, b: DialogSeverity) -> Bool
}
/// A selectability type that disables text selection by the person using your app.
///
/// Don't use this type directly. Instead, use ``TextSelectability/disabled``.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DisabledTextSelectability : TextSelectability {
/// A Boolean value that indicates whether the selectability type allows
/// selection.
///
/// Conforming types, such as ``EnabledTextSelectability`` and
/// ``DisabledTextSelectability``, return `true` or `false` for this
/// property as appropriate. SwiftUI expects this value for a given
/// selectability type to be constant, unaffected by global state.
public static let allowsSelection: Bool
}
/// A view that shows or hides another content view, based on the state of a
/// disclosure control.
///
/// 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")
/// }
/// }
/// }
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DisclosureGroup<Label, Content> : View where Label : View, Content : View {
/// Creates a disclosure group with the given label and content views.
///
/// - Parameters:
/// - content: The content shown when the disclosure group expands.
/// - label: A view that describes the content of the disclosure group.
public init(@ViewBuilder content: @escaping () -> Content, @ViewBuilder label: () -> Label)
/// Creates a disclosure group with the given label and content views, and
/// a binding to the expansion state (expanded or collapsed).
///
/// - Parameters:
/// - isExpanded: A binding to a Boolean value that determines the group's
/// expansion state (expanded or collapsed).
/// - content: The content shown when the disclosure group expands.
/// - label: A view that describes the content of the disclosure group.
public init(isExpanded: Binding<Bool>, @ViewBuilder content: @escaping () -> Content, @ViewBuilder label: () -> Label)
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DisclosureGroup where Label == Text {
/// Creates a disclosure group, using a provided localized string key to
/// create a text view for the label.
///
/// - Parameters:
/// - titleKey: The key for the localized label of `self` that describes
/// the content of the disclosure group.
/// - content: The content shown when the disclosure group expands.
public init(_ titleKey: LocalizedStringKey, @ViewBuilder content: @escaping () -> 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).
///
/// - Parameters:
/// - titleKey: The key for the localized label of `self` that describes
/// the content of the disclosure group.
/// - isExpanded: A binding to a Boolean value that determines the group's
/// expansion state (expanded or collapsed).
/// - content: The content shown when the disclosure group expands.
public init(_ titleKey: LocalizedStringKey, isExpanded: Binding<Bool>, @ViewBuilder content: @escaping () -> Content)
/// Creates a disclosure group, using a provided string to create a
/// text view for the label.
///
/// - Parameters:
/// - label: A description of the content of the disclosure group.
/// - content: The content shown when the disclosure group expands.
public init<S>(_ label: S, @ViewBuilder content: @escaping () -> Content) where S : StringProtocol
/// Creates a disclosure group, using a provided string to create a
/// text view for the label, and a binding to the expansion state (expanded
/// or collapsed).
///
/// - Parameters:
/// - label: A description of the content of the disclosure group.
/// - isExpanded: A binding to a Boolean value that determines the group's
/// expansion state (expanded or collapsed).
/// - content: The content shown when the disclosure group expands.
public init<S>(_ label: S, isExpanded: Binding<Bool>, @ViewBuilder content: @escaping () -> Content) where S : StringProtocol
}
/// A type that specifies the appearance and interaction of disclosure groups
/// within a view hierarchy.
///
/// To configure the disclosure group style for a view hierarchy, use the
/// ``View/disclosureGroupStyle(_:)`` modifier.
///
/// To create a custom disclosure group style, declare a type that conforms
/// to `DisclosureGroupStyle`. Implement the
/// ``DisclosureGroupStyle/makeBody(configuration:)`` method to return a view
/// that composes the elements of the `configuration` that SwiftUI provides to
/// your method.
///
/// struct MyDisclosureStyle: DisclosureGroupStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// VStack {
/// Button {
/// withAnimation {
/// configuration.isExpanded.toggle()
/// }
/// } label: {
/// HStack(alignment: .firstTextBaseline) {
/// configuration.label
/// Spacer()
/// Text(configuration.isExpanded ? "hide" : "show")
/// .foregroundColor(.accentColor)
/// .font(.caption.lowercaseSmallCaps())
/// .animation(nil, value: configuration.isExpanded)
/// }
/// .contentShape(Rectangle())
/// }
/// .buttonStyle(.plain)
/// if configuration.isExpanded {
/// configuration.content
/// }
/// }
/// }
/// }
///
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public protocol DisclosureGroupStyle {
/// A view that represents the body of a disclosure group.
associatedtype Body : View
/// Creates a view that represents the body of a disclosure group.
///
/// SwiftUI calls this method for each instance of ``DisclosureGroup``
/// that you create within a view hierarchy where this style is the current
/// ``DisclosureGroupStyle``.
///
/// - Parameter configuration: The properties of the instance being created.
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a disclosure group instance.
typealias Configuration = DisclosureGroupStyleConfiguration
}
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DisclosureGroupStyle where Self == AutomaticDisclosureGroupStyle {
/// A disclosure group style that resolves its appearance automatically
/// based on the current context.
public static var automatic: AutomaticDisclosureGroupStyle { get }
}
/// The properties of a disclosure group instance.
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DisclosureGroupStyleConfiguration {
/// A type-erased label of a disclosure group.
public struct Label : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// The label for the disclosure group.
public let label: DisclosureGroupStyleConfiguration.Label
/// A type-erased content of a disclosure group.
public struct Content : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// The content of the disclosure group.
public let content: DisclosureGroupStyleConfiguration.Content
/// A binding to a Boolean that indicates whether the disclosure
/// group is expanded.
@Binding public var isExpanded: Bool { get nonmutating set }
public var $isExpanded: Binding<Bool> { get }
}
/// A kind of table row that shows or hides additional rows based on the state
/// of a disclosure control.
///
/// A disclosure group row consists of a label row that is always visible, and
/// some content rows that are conditionally visible depending on the state.
/// Toggling the control will flip the state between "expanded" and "collapsed".
///
/// In the following example, a disclosure group has `allDevices` as the label
/// row, and exposes its expanded state with the bound property, `expanded`.
/// Upon toggling the disclosure control, the user can update the expanded state
/// which will in turn show or hide the three content rows for `iPhone`, `iPad`,
/// and `Mac`.
///
/// private struct DeviceStats: Identifiable {
/// // ...
/// }
/// @State private var expanded: Bool = true
/// @State private var allDevices: DeviceStats = /* ... */
/// @State private var iPhone: DeviceStats = /* ... */
/// @State private var iPad: DeviceStats = /* ... */
/// @State private var Mac: DeviceStats = /* ... */
///
/// var body: some View {
/// Table(of: DeviceStats.self) {
/// // ...
/// } rows: {
/// DisclosureTableRow(allDevices, isExpanded: $expanded) {
/// TableRow(iPhone)
/// TableRow(iPad)
/// TableRow(Mac)
/// }
/// }
/// }
@available(iOS 17.0, macOS 14.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DisclosureTableRow<Label, Content> : TableRowContent where Label : TableRowContent, Content : TableRowContent, Label.TableRowValue == Content.TableRowValue {
/// The type of value represented by this table row content.
public typealias TableRowValue = Label.TableRowValue
/// Creates a disclosure group with the given value and table rows, and a
/// binding to the expansion state (expanded or collapsed).
///
/// - Parameters:
/// - value: The value of the disclosable table row.
/// - isExpanded: A binding to a Boolean value that determines the group's
/// expansion state (expanded or collapsed).
/// - content: The table row shown when the disclosure group expands.
public init<Value>(_ value: Value, isExpanded: Binding<Bool>? = nil, @TableRowBuilder<Value> content: @escaping () -> Content) where Label == TableRow<Value>, Value == Content.TableRowValue
/// The composition of content that comprise the table row content.
public var tableRowBody: some TableRowContent { get }
/// The type of content representing the body of this table row content.
public typealias TableRowBody = some TableRowContent
}
/// An action that dismisses a presentation.
///
/// Use the ``EnvironmentValues/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 ``DismissAction/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``.
/// * Close a window that you create with ``WindowGroup`` or ``Window``.
///
/// 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
/// ``View/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 ``EnvironmentValues/isPresented`` environment value.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct DismissAction {
/// Dismisses the view if it is currently presented.
///
/// Don't call this method directly. SwiftUI calls it for you when you
/// call the ``DismissAction`` structure that you get from the
/// ``Environment``:
///
/// private struct SheetContents: View {
/// @Environment(\.dismiss) private var dismiss
///
/// var body: some View {
/// Button("Done") {
/// dismiss() // Implicitly calls dismiss.callAsFunction()
/// }
/// }
/// }
///
/// For information about how Swift uses the `callAsFunction()` method to
/// simplify call site syntax, see
/// [Methods with Special Names](https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID622)
/// in *The Swift Programming Language*.
public func callAsFunction()
}
/// Programmatic window dismissal behaviors.
///
/// 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")
/// }
/// }
/// }
/// }
///
@available(iOS 17.0, macOS 14.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DismissBehavior : Sendable {
/// The interactive dismiss behavior.
///
/// Use this behavior when you want to dismiss a window in a manner that is
/// similar to the standard system affordances for window dismissal - for
/// example, when a user clicks the close button.
///
/// This is the default behavior on macOS and iOS.
///
/// On macOS, dismissing a window using this behavior will not dismiss a
/// window which is currently showing a modal presentation, such as a sheet
/// or alert. Additionally, a document window that is dismissed with this
/// behavior will show the save dialog if there are unsaved changes to the
/// document.
///
/// On iOS, dismissing a window using this behavior will dismiss it
/// regardless of any modal presentations being shown.
public static let interactive: DismissBehavior
/// The destructive dismiss behavior.
///
/// Use this behavior when you want to dismiss a window regardless of
/// any conditions that would normally prevent the dismissal. Dismissing
/// windows in this matter may result in loss of state.
///
/// On macOS, this behavior will cause windows to dismiss even when they are
/// currently showing a modal presentation, such as a sheet or alert.
/// Additionally, a document window will not show the save dialog when
/// there are unsaved changes and the window is dismissed with this
/// behavior.
///
/// On iOS, this behavior behaves the same as `interactive`.
public static let destructive: DismissBehavior
}
/// An action that can end a search interaction.
///
/// Use the ``EnvironmentValues/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 ``DismissSearchAction/callAsFunction()``
/// method that Swift calls when you call the instance.
///
/// When you dismiss search, SwiftUI:
///
/// * Sets ``EnvironmentValues/isSearching`` to `false`.
/// * Clears any text from the search field.
/// * Removes focus from the search field.
///
/// > Note: Calling this instance has no effect if the user isn't
/// interacting with a 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 ``EnvironmentValues/dismiss`` property to dismiss
/// the sheet, and the ``EnvironmentValues/dismissSearch`` property to
/// reset the search field.
///
/// > Important: Access the action from inside the searched view, as the
/// example above demonstrates, rather than from the searched view’s
/// parent, or another hierarchy, like that of a sheet. SwiftUI sets the
/// value in the environment of the view that you apply the searchable
/// modifier to, and doesn’t propagate the value up the view hierarchy.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct DismissSearchAction {
/// Dismisses the current search operation, if any.
///
/// Don't call this method directly. SwiftUI calls it for you when you
/// call the ``DismissSearchAction`` structure that you get from the
/// ``Environment``:
///
/// struct SearchedView: View {
/// @Environment(\.dismissSearch) private var dismissSearch
///
/// var body: some View {
/// Button("Cancel") {
/// dismissSearch() // Implicitly calls dismissSearch.callAsFunction()
/// }
/// }
/// }
///
/// For information about how Swift uses the `callAsFunction()` method to
/// simplify call site syntax, see
/// [Methods with Special Names](https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID622)
/// in *The Swift Programming Language*.
public func callAsFunction()
}
/// An action that dismisses a window associated to a particular scene.
///
/// Use the ``EnvironmentValues/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 ``DismissWindowAction/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")
/// }
/// }
/// }
@available(iOS 17.0, macOS 14.0, visionOS 1.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DismissWindowAction {
/// Dismisses the current window.
///
/// Don't call this method directly. SwiftUI calls it when you
/// call the ``EnvironmentValues/dismissWindow`` action:
///
/// dismissWindow()
///
/// For information about how Swift uses the `callAsFunction()` method to
/// simplify call site syntax, see
/// [Methods with Special Names](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/declarations#Methods-with-Special-Names)
/// in *The Swift Programming Language*.
public func callAsFunction()
/// Dismisses the window that's associated with the specified identifier.
///
/// When the specified identifier represents a ``WindowGroup``, all of the
/// open windows in that group will be dismissed. For dismissing a single
/// window associated to a `WindowGroup` scene, use
/// ``dismissWindow(value:)`` or ``dismissWindow(id:value:)``.
///
/// Don't call this method directly. SwiftUI calls it when you
/// call the ``EnvironmentValues/dismissWindow`` action with an identifier:
///
/// dismissWindow(id: "message")
///
/// For information about how Swift uses the `callAsFunction()` method to
/// simplify call site syntax, see
/// [Methods with Special Names](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/declarations#Methods-with-Special-Names)
/// in *The Swift Programming Language*.
///
/// - Parameter id: The identifier of the scene to dismiss.
public func callAsFunction(id: String)
/// Dismisses the window defined by the window group that is presenting the
/// specified value type.
///
/// If multiple windows match the provided value, then they all will be
/// dismissed. For dismissing a specific window in a specific group, use
/// ``dismissWindow(id:value:)``.
///
/// Don't call this method directly. SwiftUI calls it when you
/// call the ``EnvironmentValues/dismissWindow`` action with an identifier
/// and a value:
///
/// dismissWindow(value: message.id)
///
/// For information about how Swift uses the `callAsFunction()` method to
/// simplify call site syntax, see
/// [Methods with Special Names](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/declarations#Methods-with-Special-Names)
/// in *The Swift Programming Language*.
///
/// - Parameters:
/// - value: The value which is currently presented.
public func callAsFunction<D>(value: D) where D : Decodable, D : Encodable, D : Hashable
/// Dismisses the window defined by the window group that is presenting the
/// specified value type and that's associated with the specified identifier.
///
/// Don't call this method directly. SwiftUI calls it when you
/// call the ``EnvironmentValues/dismissWindow`` action with an identifier
/// and a value:
///
/// dismissWindow(id: "message", value: message.id)
///
/// For information about how Swift uses the `callAsFunction()` method to
/// simplify call site syntax, see
/// [Methods with Special Names](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/declarations#Methods-with-Special-Names)
/// in *The Swift Programming Language*.
///
/// - Parameters:
/// - id: The identifier of the scene to dismiss.
/// - value: The value which is currently presented.
public func callAsFunction<D>(id: String, value: D) where D : Decodable, D : Encodable, D : Hashable
}
/// A visual element that can be used to separate other content.
///
/// When contained in a stack, the divider extends across the minor axis of the
/// stack, or horizontally when not in a stack.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct Divider : View {
public init()
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
@available(iOS 17.0, macOS 14.0, visionOS 1.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DocumentConfiguration {
/// A Boolean value that indicates whether you can edit the document.
///
/// On macOS, the document could be non-editable if the user lacks write permissions,
/// the parent directory or volume is read-only,
/// or the document couldn't be autosaved.
///
/// On iOS, the document is not editable if there was
/// an error reading or saving it, there's an unresolved conflict,
/// the document is being uploaded or downloaded,
/// or otherwise, it is currently busy and unsafe for user edits.
public var isEditable: Bool { get }
/// A URL of an open document.
///
/// If the document has never been saved, returns `nil`.
public var fileURL: URL? { get }
}
@available(iOS 17.0, macOS 14.0, visionOS 1.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DocumentConfiguration : Sendable {
}
/// A scene that enables support for opening, creating, and saving documents.
///
/// 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.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DocumentGroup<Document, Content> : Scene where Content : View {
/// The content and behavior of the scene.
///
/// For any scene that you create, provide a computed `body` property that
/// defines the scene as a composition of other scenes. You can assemble a
/// scene from built-in scenes that SwiftUI provides, as well as other
/// scenes that you've defined.
///
/// Swift infers the scene's ``SwiftUI/Scene/Body-swift.associatedtype``
/// associated type based on the contents of the `body` property.
@MainActor public var body: some Scene { get }
/// The type of scene that represents the body of this scene.
///
/// When you create a custom scene, Swift infers this type from your
/// implementation of the required ``SwiftUI/Scene/body-swift.property``
/// property.
public typealias Body = some Scene
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DocumentGroup where Document : ReferenceFileDocument {
/// Creates a document group that is able to create and edit reference file
/// documents.
///
/// - Parameters:
/// - newDocument: The initial document used when the user creates
/// a new document. The argument should create a new instance, such that
/// a new document is created on each invocation of the closure.
/// - editor: The editing UI for the provided document.
///
/// The current document for a given editor instance is also provided as an
/// environment object for its subhierarchy.
///
/// Undo support is not automatically provided for this construction of
/// a `DocumentGroup`, and any updates to the document by the editor view
/// hierarchy are expected to register undo operations when appropriate.
public init(newDocument: @escaping () -> Document, @ViewBuilder editor: @escaping (ReferenceFileDocumentConfiguration<Document>) -> Content)
/// Creates a document group that is able to view reference file documents.
///
/// - Parameters:
/// - documentType: The type of document being viewed.
/// - viewer: The viewing UI for the provided document.
///
/// The current document for a given editor instance is also provided as an
/// environment object for its subhierarchy.
///
/// - See Also: `CFBundleTypeRole` with a value of "Viewer"
public init(viewing documentType: Document.Type, @ViewBuilder viewer: @escaping (ReferenceFileDocumentConfiguration<Document>) -> Content)
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DocumentGroup where Document : FileDocument {
/// Creates a document group for creating and editing file documents.
///
/// Use a ``DocumentGroup`` scene to tell SwiftUI what kinds of documents
/// your app can open when you declare your app using the ``App`` protocol.
/// You initialize a document group scene by passing in the document model
/// and a view capable of displaying the document's contents. 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()) { file in
/// ContentView(document: file.$document)
/// }
/// }
/// }
///
/// The document types you supply to ``DocumentGroup`` must conform to
/// ``FileDocument`` or ``ReferenceFileDocument``. Your app can support
/// multiple document types by adding additional ``DocumentGroup`` scenes.
///
/// - Parameters:
/// - newDocument: The initial document to use when a user creates
/// a new document.
/// - editor: The editing UI for the provided document.
public init(newDocument: @autoclosure @escaping () -> Document, @ViewBuilder editor: @escaping (FileDocumentConfiguration<Document>) -> Content)
/// Creates a document group capable of viewing file documents.
///
/// Use this method to create a document group that can view files of a
/// specific type. The example below creates a new document viewer for
/// `MyImageFormatDocument` and displays them with `MyImageFormatViewer`:
///
/// @main
/// struct MyApp: App {
/// var body: some Scene {
/// DocumentGroup(viewing: MyImageFormatDocument.self) { file in
/// MyImageFormatViewer(image: file.document)
/// }
/// }
/// }
///
/// - Parameters:
/// - documentType: The type of document your app can view.
/// - viewer: The viewing UI for the provided document.
///
/// You tell the system about the app's role with respect to the document
/// type by setting the
/// <doc://com.apple.documentation/documentation/BundleResources/Information_Property_List/CFBundleDocumentTypes/CFBundleTypeRole>
/// `Info.plist` key with a value of `Viewer`.
///
public init(viewing documentType: Document.Type, @ViewBuilder viewer: @escaping (FileDocumentConfiguration<Document>) -> Content)
}
/// A navigation view style represented by a primary view stack that
/// navigates to a detail view.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationStack or NavigationSplitView instead")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "replace styled NavigationView with NavigationSplitView instead")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationStack or NavigationSplitView instead")
@available(watchOS, unavailable)
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "replace styled NavigationView with NavigationStack or NavigationSplitView instead")
public struct DoubleColumnNavigationViewStyle : NavigationViewStyle {
public init()
}
/// A dragging motion that invokes an action as the drag-event sequence changes.
///
/// To recognize a drag gesture on a view, create and configure the gesture, and
/// then add it to the view using the ``View/gesture(_:including:)`` modifier.
///
/// Add a drag gesture to a ``Circle`` and change its color while the user
/// performs the drag gesture:
///
/// struct DragGestureView: View {
/// @State private var isDragging = false
///
/// var drag: some Gesture {
/// DragGesture()
/// .onChanged { _ in self.isDragging = true }
/// .onEnded { _ in self.isDragging = false }
/// }
///
/// var body: some View {
/// Circle()
/// .fill(self.isDragging ? Color.red : Color.blue)
/// .frame(width: 100, height: 100, alignment: .center)
/// .gesture(drag)
/// }
/// }
@available(iOS 13.0, macOS 10.15, watchOS 6.0, *)
@available(tvOS, unavailable)
public struct DragGesture : Gesture {
/// The attributes of a drag gesture.
public struct Value : Equatable, Sendable {
/// The time associated with the drag gesture's current event.
public var time: Date
/// The location of the drag gesture's current event.
public var location: CGPoint
/// The location of the drag gesture's first event.
public var startLocation: CGPoint
/// The total translation from the start of the drag gesture to the
/// current event of the drag gesture.
///
/// This is equivalent to `location.{x,y} - startLocation.{x,y}`.
public var translation: CGSize { get }
/// The current drag velocity.
public var velocity: CGSize { get }
/// A prediction, based on the current drag velocity, of where the final
/// location will be if dragging stopped now.
public var predictedEndLocation: CGPoint { get }
/// A prediction, based on the current drag velocity, of what the final
/// translation will be if dragging stopped now.
public var predictedEndTranslation: CGSize { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: DragGesture.Value, b: DragGesture.Value) -> Bool
}
/// The minimum dragging distance before the gesture succeeds.
public var minimumDistance: CGFloat
/// The coordinate space in which to receive location values.
public var coordinateSpace: CoordinateSpace
/// Creates a dragging gesture with the minimum dragging distance before the
/// gesture succeeds and the coordinate space of the gesture's location.
///
/// - Parameters:
/// - minimumDistance: The minimum dragging distance for the gesture to
/// succeed.
/// - coordinateSpace: The coordinate space of the dragging gesture's
/// location.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(tvOS, unavailable)
public init(minimumDistance: CGFloat = 10, coordinateSpace: CoordinateSpace = .local)
/// Creates a dragging gesture with the minimum dragging distance before the
/// gesture succeeds and the coordinate space of the gesture's location.
///
/// - Parameters:
/// - minimumDistance: The minimum dragging distance for the gesture to
/// succeed.
/// - coordinateSpace: The coordinate space of the dragging gesture's
/// location.
@available(iOS 17.0, macOS 14.0, watchOS 10.0, *)
@available(tvOS, unavailable)
public init(minimumDistance: CGFloat = 10, coordinateSpace: some CoordinateSpaceProtocol = .local)
/// The type of gesture representing the body of `Self`.
public typealias Body = Never
}
/// An interface that you implement to interact with a drop operation in a view
/// modified to accept drops.
///
/// The ``DropDelegate`` protocol provides a comprehensive and flexible way to
/// interact with a drop operation. Specify a drop delegate when you modify a
/// view to accept drops with the ``View/onDrop(of:delegate:)-6lin8`` method.
///
/// Alternatively, for simple drop cases that don't require the full
/// functionality of a drop delegate, you can modify a view to accept drops
/// using the ``View/onDrop(of:isTargeted:perform:)-f15m`` or the
/// ``View/onDrop(of:isTargeted:perform:)-982eu`` method. These methods handle the
/// drop using a closure you provide as part of the modifier.
@available(iOS 13.4, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@MainActor public protocol DropDelegate {
/// Tells the delegate that a drop containing items conforming to one of the
/// expected types entered a view that accepts drops.
///
/// Specify the expected types when you apply the drop modifier to the view.
/// The default implementation returns `true`.
@MainActor func validateDrop(info: DropInfo) -> Bool
/// Tells the delegate it can request the item provider data from the given
/// information.
///
/// Incorporate the received data into your app's data model as appropriate.
/// - Returns: A Boolean that is `true` if the drop was successful, `false`
/// otherwise.
@MainActor func performDrop(info: DropInfo) -> Bool
/// Tells the delegate a validated drop has entered the modified view.
///
/// The default implementation does nothing.
@MainActor func dropEntered(info: DropInfo)
/// Tells the delegate that a validated drop moved inside the modified view.
///
/// Use this method to return a drop proposal containing the operation the
/// delegate intends to perform at the drop ``DropInfo/location``. The
/// default implementation of this method returns `nil`, which tells the
/// drop to use the last valid returned value or else
/// ``DropOperation/copy``.
@MainActor func dropUpdated(info: DropInfo) -> DropProposal?
/// Tells the delegate a validated drop operation has exited the modified
/// view.
///
/// The default implementation does nothing.
@MainActor func dropExited(info: DropInfo)
}
@available(iOS 13.4, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DropDelegate {
/// Tells the delegate that a drop containing items conforming to one of the
/// expected types entered a view that accepts drops.
///
/// Specify the expected types when you apply the drop modifier to the view.
/// The default implementation returns `true`.
@MainActor public func validateDrop(info: DropInfo) -> Bool
/// Tells the delegate a validated drop has entered the modified view.
///
/// The default implementation does nothing.
@MainActor public func dropEntered(info: DropInfo)
/// Tells the delegate that a validated drop moved inside the modified view.
///
/// Use this method to return a drop proposal containing the operation the
/// delegate intends to perform at the drop ``DropInfo/location``. The
/// default implementation of this method returns `nil`, which tells the
/// drop to use the last valid returned value or else
/// ``DropOperation/copy``.
@MainActor public func dropUpdated(info: DropInfo) -> DropProposal?
/// Tells the delegate a validated drop operation has exited the modified
/// view.
///
/// The default implementation does nothing.
@MainActor public func dropExited(info: DropInfo)
}
/// The current state of a drop.
@available(iOS 13.4, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DropInfo {
/// The location of the drag in the coordinate space of the drop view.
public var location: CGPoint { get }
/// Indicates whether at least one item conforms to at least one of the
/// specified uniform type identifiers.
///
/// - Parameter contentTypes: The uniform type identifiers to query for.
/// - Returns: Whether at least one item conforms to one of `contentTypes`.
@available(iOS 14.0, macOS 11.0, *)
public func hasItemsConforming(to contentTypes: [UTType]) -> Bool
/// Finds item providers that conform to at least one of the specified
/// uniform type identifiers.
///
/// This function is only valid during the `performDrop()` action.
///
/// - Parameter contentTypes: The uniform type identifiers to query for.
/// - Returns: The item providers that conforms to `contentTypes`.
@available(iOS 14.0, macOS 11.0, *)
public func itemProviders(for contentTypes: [UTType]) -> [NSItemProvider]
}
@available(iOS, introduced: 13.4, deprecated: 100000.0, message: "Provide `UTType`s as the `types` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Provide `UTType`s as the `types` instead.")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Provide `UTType`s as the `types` instead.")
extension DropInfo {
/// Returns whether at least one item conforms to at least one of the
/// specified uniform type identifiers.
public func hasItemsConforming(to types: [String]) -> Bool
/// Returns an Array of items that each conform to at least one of the
/// specified uniform type identifiers.
///
/// This function is only valid during the performDrop() action.
public func itemProviders(for types: [String]) -> [NSItemProvider]
}
/// Operation types that determine how a drag and drop session resolves when the
/// user drops a drag item.
@available(iOS 13.4, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public enum DropOperation : Sendable {
/// Cancel the drag operation and transfer no data.
case cancel
/// The drop activity is not allowed at this time or location.
case forbidden
/// Copy the data to the modified view.
case copy
/// Move the data represented by the drag items instead of copying it.
case move
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: DropOperation, b: DropOperation) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.4, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DropOperation : Equatable {
}
@available(iOS 13.4, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DropOperation : Hashable {
}
/// The behavior of a drop.
@available(iOS 13.4, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DropProposal : Sendable {
/// The drop operation that the drop proposes to perform.
public let operation: DropOperation
public init(operation: DropOperation)
}
/// An interface for a stored variable that updates an external property of a
/// view.
///
/// The view gives values to these properties prior to recomputing the view's
/// ``View/body-swift.property``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol DynamicProperty {
/// Updates the underlying value of the stored value.
///
/// SwiftUI calls this function before rendering a view's
/// ``View/body-swift.property`` to ensure the view has the most recent
/// value.
mutating func update()
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension DynamicProperty {
/// Updates the underlying value of the stored value.
///
/// SwiftUI calls this function before rendering a view's
/// ``View/body-swift.property`` to ensure the view has the most recent
/// value.
public mutating func update()
}
/// A type of table row content that generates table rows from an underlying
/// collection of data.
///
/// This table row content type provides drag-and-drop support for tables. Use
/// the ``DynamicTableRowContent/onInsert(of:perform:)`` modifier to add an
/// action to call when the table inserts new contents into its underlying
/// collection.
@available(iOS 16.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public protocol DynamicTableRowContent : TableRowContent {
/// The type of the underlying collection of data.
associatedtype Data : Collection
/// The collection of underlying data.
var data: Self.Data { get }
}
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DynamicTableRowContent {
/// Sets the insert action for the dynamic table rows.
///
/// struct Profile: Identifiable {
/// let givenName: String
/// let familyName: String
/// let id = UUID()
/// }
///
/// @State private var profiles: [Profile] = [
/// Person(givenName: "Juan", familyName: "Chavez"),
/// Person(givenName: "Mei", familyName: "Chen"),
/// Person(givenName: "Tom", familyName: "Clark"),
/// Person(givenName: "Gita", familyName: "Kumar")
/// ]
///
/// var body: some View {
/// Table {
/// TableColumn("Given Name", value: \.givenName)
/// TableColumn("Family Name", value: \.familyName)
/// } rows: {
/// ForEach(profiles) {
/// TableRow($0)
/// }
/// .dropDestination(
/// for: Profile.self
/// ) { offset, receivedProfiles in
/// people.insert(contentsOf: receivedProfiles, at: offset)
/// }
/// }
/// }
///
/// - Parameters:
/// - payloadType: Type of the models that are dropped.
/// - action: A closure that SwiftUI invokes when elements are added to
/// the collection of rows.
/// The closure takes two arguments: The first argument is the
/// offset relative to the dynamic view's underlying collection of data.
/// The second argument is an array of `Transferable` items that
/// represents the data that you want to insert.
///
/// - Returns: A view that calls `action` when elements are inserted into
/// the original view.
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public func dropDestination<T>(for payloadType: T.Type = T.self, action: @escaping (Int, [T]) -> Void) -> ModifiedContent<Self, OnInsertTableRowModifier> where T : Transferable
}
@available(iOS 16.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DynamicTableRowContent {
/// Sets the insert action for the dynamic table rows.
///
/// - Parameters:
/// - supportedContentTypes: An array of universal type identifiers types that the rows supports.
/// - action: A closure that SwiftUI invokes when adding elements to
/// the collection of rows.
/// The closure takes two arguments. The first argument is the
/// offset relative to the dynamic view's underlying collection of data.
/// The second argument is an array of
/// <doc://com.apple.documentation/documentation/Foundation/NSItemProvider>
/// items that represents the data that you want to insert.
///
/// - Returns: A view that calls `action` when inserting elements into
/// the original view.
public func onInsert(of supportedContentTypes: [UTType], perform action: @escaping (Int, [NSItemProvider]) -> Void) -> ModifiedContent<Self, OnInsertTableRowModifier>
}
/// A Dynamic Type size, which specifies how large scalable content should be.
///
/// For more information about Dynamic Type sizes in iOS, see iOS Human Interface Guidelines >
/// [Dynamic Type Sizes](https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/typography/#dynamic-type-sizes).
/// For more information about Dynamic Type sizes in watchOS, see watchOS Human Interface Guidelines >
/// [Dynamic Type Sizes](https://developer.apple.com/design/human-interface-guidelines/watchos/visual/typography/#dynamic-type-sizes).
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public enum DynamicTypeSize : Hashable, Comparable, CaseIterable, Sendable {
/// An extra small size.
case xSmall
/// A small size.
case small
/// A medium size.
case medium
/// A large size.
case large
/// An extra large size.
case xLarge
/// An extra extra large size.
case xxLarge
/// An extra extra extra large size.
case xxxLarge
/// The first accessibility size.
case accessibility1
/// The second accessibility size.
case accessibility2
/// The third accessibility size.
case accessibility3
/// The fourth accessibility size.
case accessibility4
/// The fifth accessibility size.
case accessibility5
/// A Boolean value indicating whether the size is one that is associated
/// with accessibility.
public var isAccessibilitySize: Bool { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: DynamicTypeSize, b: DynamicTypeSize) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (a: DynamicTypeSize, b: DynamicTypeSize) -> Bool
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [DynamicTypeSize]
/// A collection of all values of this type.
public static var allCases: [DynamicTypeSize] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A type of view that generates views from an underlying collection of data.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol DynamicViewContent : View {
/// The type of the underlying collection of data.
associatedtype Data : Collection
/// The collection of underlying data.
var data: Self.Data { get }
}
extension DynamicViewContent {
/// Sets the insert action for the dynamic view.
///
/// struct Profile: Identifiable {
/// let givenName: String
/// let familyName: String
/// let id = UUID()
/// }
///
/// @State private var profiles: [Profile] = [
/// Person(givenName: "Juan", familyName: "Chavez"),
/// Person(givenName: "Mei", familyName: "Chen"),
/// Person(givenName: "Tom", familyName: "Clark"),
/// Person(givenName: "Gita", familyName: "Kumar")
/// ]
///
/// var body: some View {
/// List {
/// ForEach(profiles) { profile in
/// Text(profile.givenName)
/// }
/// .dropDestination(for: Profile.self) { receivedProfiles, offset in
/// profiles.insert(contentsOf: receivedProfiles, at: offset)
/// }
/// }
/// }
///
/// - Parameters:
/// - payloadType: Type of the models that are dropped.
/// - action: A closure that SwiftUI invokes when elements are added to
/// the view. The closure takes two arguments: The first argument is the
/// offset relative to the dynamic view's underlying collection of data.
/// The second argument is an array of `Transferable` items that
/// represents the data that you want to insert.
///
/// - Returns: A view that calls `action` when elements are inserted into
/// the original view.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public func dropDestination<T>(for payloadType: T.Type = T.self, action: @escaping ([T], Int) -> Void) -> some DynamicViewContent where T : Transferable
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension DynamicViewContent {
/// Sets the insert action for the dynamic view.
///
/// - Parameters:
/// - supportedContentTypes: An array of UTI types that the dynamic
/// view supports.
/// - action: A closure that SwiftUI invokes when elements are added to
/// the view. The closure takes two arguments: The first argument is the
/// offset relative to the dynamic view's underlying collection of data.
/// The second argument is an array of
/// <doc://com.apple.documentation/documentation/Foundation/NSItemProvider> items that
/// represents the data that you want to insert.
///
/// - Returns: A view that calls `action` when elements are inserted into
/// the original view.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public func onInsert(of supportedContentTypes: [UTType], perform action: @escaping (Int, [NSItemProvider]) -> Void) -> some DynamicViewContent
/// Sets the insert action for the dynamic view.
///
/// - Parameters:
/// - acceptedTypeIdentifiers: An array of UTI types that the dynamic
/// view supports.
/// - action: A closure that SwiftUI invokes when elements are added to
/// the view. The closure takes two arguments: The first argument is the
/// offset relative to the dynamic view's underlying collection of data.
/// The second argument is an array of `NSItemProvider` that represents
/// the data that you want to insert.
///
/// - Returns: A view that calls `action` when elements are inserted into
/// the original view.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Provide `UTType`s as the `supportedContentTypes` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Provide `UTType`s as the `supportedContentTypes` instead.")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Provide `UTType`s as the `supportedContentTypes` instead.")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Provide `UTType`s as the `supportedContentTypes` instead.")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Provide `UTType`s as the `supportedContentTypes` instead.")
public func onInsert(of acceptedTypeIdentifiers: [String], perform action: @escaping (Int, [NSItemProvider]) -> Void) -> some DynamicViewContent
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension DynamicViewContent {
/// Sets the move action for the dynamic view.
///
/// - Parameters:
/// - action: A closure that SwiftUI invokes when elements in the dynamic
/// view are moved. The closure takes two arguments that represent the
/// offset relative to the dynamic view's underlying collection of data.
/// Pass `nil` to disable the ability to move items.
///
/// - Returns: A view that calls `action` when elements are moved within the
/// original view.
@inlinable public func onMove(perform action: ((IndexSet, Int) -> Void)?) -> some DynamicViewContent
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension DynamicViewContent {
/// Sets the deletion action for the dynamic view.
///
/// - Parameter action: The action that you want SwiftUI to perform when
/// elements in the view are deleted. SwiftUI passes a set of indices to the
/// closure that's relative to the dynamic view's underlying collection of
/// data.
///
/// - Returns: A view that calls `action` when elements are deleted from the
/// original view.
@inlinable public func onDelete(perform action: ((IndexSet) -> Void)?) -> some DynamicViewContent
}
/// An enumeration to indicate one edge of a rectangle.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public enum Edge : Int8, CaseIterable {
case top
case leading
case bottom
case trailing
/// An efficient set of `Edge`s.
@frozen public struct Set : OptionSet {
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = Edge.Set
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public let rawValue: Int8
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
public init(rawValue: Int8)
public static let top: Edge.Set
public static let leading: Edge.Set
public static let bottom: Edge.Set
public static let trailing: Edge.Set
public static let all: Edge.Set
public static let horizontal: Edge.Set
public static let vertical: Edge.Set
/// Creates an instance containing just `e`
public init(_ e: Edge)
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = Edge.Set.Element
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = Int8
}
/// Creates a new instance with the specified raw value.
///
/// If there is no value of the type that corresponds with the specified raw
/// value, this initializer returns `nil`. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// print(PaperSize(rawValue: "Legal"))
/// // Prints "Optional("PaperSize.Legal")"
///
/// print(PaperSize(rawValue: "Tabloid"))
/// // Prints "nil"
///
/// - Parameter rawValue: The raw value to use for the new instance.
public init?(rawValue: Int8)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [Edge]
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = Int8
/// A collection of all values of this type.
public static var allCases: [Edge] { get }
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public var rawValue: Int8 { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Edge : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Edge : Hashable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Edge : RawRepresentable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Edge : Sendable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Edge.Set : Sendable {
}
/// The inset distances for the sides of a rectangle.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct EdgeInsets : Equatable {
public var top: CGFloat
public var leading: CGFloat
public var bottom: CGFloat
public var trailing: CGFloat
@inlinable public init(top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat)
@inlinable public init()
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: EdgeInsets, b: EdgeInsets) -> Bool
}
extension EdgeInsets {
/// Create edge insets from the equivalent NSDirectionalEdgeInsets.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, *)
@available(watchOS, unavailable)
public init(_ nsEdgeInsets: NSDirectionalEdgeInsets)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EdgeInsets : Animatable {
/// The type defining the data to animate.
public typealias AnimatableData = AnimatablePair<CGFloat, AnimatablePair<CGFloat, AnimatablePair<CGFloat, CGFloat>>>
/// The data to animate.
public var animatableData: EdgeInsets.AnimatableData
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EdgeInsets : Sendable {
}
/// A set of edit actions on a collection of data that a view can offer
/// to a user.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct EditActions<Data> : OptionSet, Sendable {
/// The raw value.
public let rawValue: Int
/// Creates a new set from a raw value.
///
/// - Parameter rawValue: The raw value with which to create the
/// collection edits.
public init(rawValue: Int)
/// All the edit actions available on this collection.
public static var all: EditActions<Data> { get }
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = EditActions<Data>
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = EditActions<Data>
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = Int
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EditActions where Data : RangeReplaceableCollection {
/// An edit action that allows the user to delete one or more elements
/// of a collection.
public static var delete: EditActions<Data> { get }
/// All the edit actions available on this collection.
public static var all: EditActions<Data> { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EditActions where Data : MutableCollection {
/// An edit action that allows the user to move elements of a
/// collection.
public static var move: EditActions<Data> { get }
/// All the edit actions available on this collection.
public static var all: EditActions<Data> { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EditActions where Data : MutableCollection, Data : RangeReplaceableCollection {
/// All the edit actions available on this collection.
public static var all: EditActions<Data> { get }
}
/// An opaque wrapper view that adds editing capabilities to a row in a list.
///
/// You don't use this type directly. Instead SwiftUI creates this type on
/// your behalf.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct EditableCollectionContent<Content, Data> {
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EditableCollectionContent : View where Content : View {
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
/// An ellipse aligned inside the frame of the view containing it.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Ellipse : Shape {
/// Describes this shape as a path within a rectangular frame of reference.
///
/// - Parameter rect: The frame of reference for describing this shape.
///
/// - Returns: A path that describes this shape.
public func path(in rect: CGRect) -> Path
/// Creates a new ellipse shape.
@inlinable public init()
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public var layoutDirectionBehavior: LayoutDirectionBehavior { get }
/// The type defining the data to animate.
public typealias AnimatableData = EmptyAnimatableData
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Ellipse : InsettableShape {
/// Returns `self` inset by `amount`.
@inlinable public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
public typealias InsetShape = some InsettableShape
}
/// A radial gradient that draws an ellipse.
///
/// 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
/// ``ShapeStyle/ellipticalGradient(_:center:startRadiusFraction:endRadiusFraction:)-fmox``.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public struct EllipticalGradient : ShapeStyle, View, Sendable {
/// Creates an elliptical gradient.
///
/// For example, an elliptical gradient centered on the top-leading
/// corner of the view:
///
/// EllipticalGradient(
/// gradient: .init(colors: [.blue, .green]),
/// center: .topLeading,
/// startRadiusFraction: 0,
/// endRadiusFraction: 1)
///
/// - Parameters:
/// - gradient: The colors and their parametric locations.
/// - center: The center of the circle, in [0, 1] coordinates.
/// - startRadiusFraction: The start radius value, as a fraction
/// between zero and one. Zero maps to the center point, one
/// maps to the diameter of the unit circle.
/// - endRadiusFraction: The end radius value, as a fraction
/// between zero and one. Zero maps to the center point, one
/// maps to the diameter of the unit circle.
public init(gradient: Gradient, center: UnitPoint = .center, startRadiusFraction: CGFloat = 0, endRadiusFraction: CGFloat = 0.5)
/// Creates an elliptical gradient from a collection of colors.
///
/// For example, an elliptical gradient centered on the top-leading
/// corner of the view:
///
/// EllipticalGradient(
/// colors: [.blue, .green],
/// center: .topLeading,
/// startRadiusFraction: 0,
/// endRadiusFraction: 1)
///
/// - Parameters:
/// - colors: The colors, evenly distributed throughout the gradient.
/// - center: The center of the circle, in [0, 1] coordinates.
/// - startRadiusFraction: The start radius value, as a fraction
/// between zero and one. Zero maps to the center point, one
/// maps to the diameter of the unit circle.
/// - endRadiusFraction: The end radius value, as a fraction
/// between zero and one. Zero maps to the center point, one
/// maps to the diameter of the unit circle.
public init(colors: [Color], center: UnitPoint = .center, startRadiusFraction: CGFloat = 0, endRadiusFraction: CGFloat = 0.5)
/// Creates an elliptical gradient from a collection of color stops.
///
/// For example, an elliptical gradient centered on the top-leading
/// corner of the view, with some extra green area:
///
/// EllipticalGradient(
/// stops: [
/// .init(color: .blue, location: 0.0),
/// .init(color: .green, location: 0.9),
/// .init(color: .green, location: 1.0),
/// ],
/// center: .topLeading,
/// startRadiusFraction: 0,
/// endRadiusFraction: 1)
///
/// - Parameters:
/// - stops: The colors and their parametric locations.
/// - center: The center of the circle, in [0, 1] coordinates.
/// - startRadiusFraction: The start radius value, as a fraction
/// between zero and one. Zero maps to the center point, one
/// maps to the diameter of the unit circle.
/// - endRadiusFraction: The end radius value, as a fraction
/// between zero and one. Zero maps to the center point, one
/// maps to the diameter of the unit circle.
public init(stops: [Gradient.Stop], center: UnitPoint = .center, startRadiusFraction: CGFloat = 0, endRadiusFraction: CGFloat = 0.5)
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
public typealias Resolved = Never
}
/// An empty type for animatable data.
///
/// This type is suitable for use as the `animatableData` property of
/// types that do not have any animatable properties.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct EmptyAnimatableData : VectorArithmetic {
@inlinable public init()
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
@inlinable public static var zero: EmptyAnimatableData { get }
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@inlinable public static func += (lhs: inout EmptyAnimatableData, rhs: EmptyAnimatableData)
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@inlinable public static func -= (lhs: inout EmptyAnimatableData, rhs: EmptyAnimatableData)
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@inlinable public static func + (lhs: EmptyAnimatableData, rhs: EmptyAnimatableData) -> EmptyAnimatableData
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@inlinable public static func - (lhs: EmptyAnimatableData, rhs: EmptyAnimatableData) -> EmptyAnimatableData
/// Multiplies each component of this value by the given value.
@inlinable public mutating func scale(by rhs: Double)
/// The dot-product of this animatable data instance with itself.
@inlinable public var magnitudeSquared: Double { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: EmptyAnimatableData, b: EmptyAnimatableData) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EmptyAnimatableData : Sendable {
}
/// An empty group of commands.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct EmptyCommands : Commands {
/// Creates an empty command hierarchy.
public init()
/// The type of commands that represents the body of this command hierarchy.
///
/// When you create custom commands, Swift infers this type from your
/// implementation of the required ``SwiftUI/Commands/body-swift.property``
/// property.
public typealias Body = Never
}
/// An empty, or identity, modifier, used during development to switch
/// modifiers at compile time.
///
/// 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 {
/// func body(content: Content) -> some View {
/// 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
/// }
/// }
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct EmptyModifier : ViewModifier {
public static let identity: EmptyModifier
/// The type of view representing the body.
public typealias Body = Never
@inlinable public init()
/// Gets the current body of the caller.
///
/// `content` is a proxy for the view that will have the modifier
/// represented by `Self` applied to it.
@MainActor public func body(content: EmptyModifier.Content) -> EmptyModifier.Body
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EmptyModifier : Sendable {
}
/// A table row content that doesn't produce any rows.
///
/// You will rarely, if ever, need to create an `EmptyTableRowContent` directly.
/// Instead, `EmptyTableRowContent` represents the absence of a row.
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct EmptyTableRowContent<Value> where Value : Identifiable {
/// The type of value represented by this table row content.
public typealias TableRowValue = Value
/// The type of content representing the body of this table row content.
public typealias TableRowBody = Never
}
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension EmptyTableRowContent : TableRowContent {
}
/// A view that doesn't contain any content.
///
/// You will rarely, if ever, need to create an `EmptyView` directly. Instead,
/// `EmptyView` represents the absence of a view.
///
/// SwiftUI uses `EmptyView` in situations where a SwiftUI view type defines one
/// or more child views with generic parameters, and allows the child views to
/// be absent. When absent, the child view's type in the generic type parameter
/// is `EmptyView`.
///
/// The following example creates an indeterminate ``ProgressView`` without
/// a label. The ``ProgressView`` type declares two generic parameters,
/// `Label` and `CurrentValueLabel`, for the types used by its subviews.
/// When both subviews are absent, like they are here, the resulting type is
/// `ProgressView<EmptyView, EmptyView>`, as indicated by the example's output:
///
/// let progressView = ProgressView()
/// print("\(type(of:progressView))")
/// // Prints: ProgressView<EmptyView, EmptyView>
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct EmptyView : View {
/// Creates an empty view.
@inlinable public init()
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EmptyView : Sendable {
}
/// The base visual effect that you apply additional effect to.
///
/// `EmptyVisualEffect` does not change the appearance of the view
/// that it is applied to.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct EmptyVisualEffect : VisualEffect {
/// Creates a new empty visual effect.
public init()
/// The type defining the data to animate.
public typealias AnimatableData = EmptyAnimatableData
}
/// An empty widget configuration.
@available(iOS 14.0, macOS 11.0, watchOS 9.0, *)
@available(tvOS, unavailable)
@frozen public struct EmptyWidgetConfiguration : WidgetConfiguration {
@inlinable public init()
/// The type of widget configuration representing the body of
/// this configuration.
///
/// When you create a custom widget, Swift infers this type from your
/// implementation of the required `body` property.
public typealias Body = Never
}
@available(iOS 14.0, macOS 11.0, watchOS 9.0, *)
@available(tvOS, unavailable)
extension EmptyWidgetConfiguration : Sendable {
}
/// A selectability type that enables text selection by the person using your app.
///
/// Don't use this type directly. Instead, use ``TextSelectability/enabled``.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct EnabledTextSelectability : TextSelectability {
/// A Boolean value that indicates whether the selectability type allows
/// selection.
///
/// Conforming types, such as ``EnabledTextSelectability`` and
/// ``DisabledTextSelectability``, return `true` or `false` for this
/// property as appropriate. SwiftUI expects this value for a given
/// selectability type to be constant, unaffected by global state.
public static let allowsSelection: Bool
}
/// A property wrapper that reads a value from a view's environment.
///
/// 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 ``EnvironmentValues/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 ``View/environment(_:_:)`` view modifier.
///
/// For the complete list of environment values provided by SwiftUI, see the
/// properties of the ``EnvironmentValues`` structure. For information about
/// creating custom environment values, see the ``EnvironmentKey`` protocol.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen @propertyWrapper public struct Environment<Value> : DynamicProperty {
/// Creates an environment property to read the specified key path.
///
/// Don’t call this initializer directly. Instead, declare a property
/// with the ``Environment`` property wrapper, and provide the key path of
/// the environment value that the property should reflect:
///
/// struct MyView: View {
/// @Environment(\.colorScheme) var colorScheme: ColorScheme
///
/// // ...
/// }
///
/// SwiftUI automatically updates any parts of `MyView` that depend on
/// the property when the associated environment value changes.
/// You can't modify the environment value using a property like this.
/// Instead, use the ``View/environment(_:_:)`` view modifier on a view to
/// set a value for a view hierarchy.
///
/// - Parameter keyPath: A key path to a specific resulting value.
@inlinable public init(_ keyPath: KeyPath<EnvironmentValues, Value>)
/// The current value of the environment property.
///
/// The wrapped value property provides primary access to the value's data.
/// However, you don't access `wrappedValue` directly. Instead, you read the
/// property variable created with the ``Environment`` property wrapper:
///
/// @Environment(\.colorScheme) var colorScheme: ColorScheme
///
/// var body: some View {
/// if colorScheme == .dark {
/// DarkContent()
/// } else {
/// LightContent()
/// }
/// }
///
@inlinable public var wrappedValue: Value { get }
}
extension Environment {
/// Creates an environment property to read an observable object from the
/// environment.
///
/// - Important: This initializer only accepts objects conforming to the
/// `Observable` protocol. For reading environment objects that conform to
/// `ObservableObject`, use ``EnvironmentObject`` instead.
///
/// Don’t call this initializer directly. Instead, declare a property with
/// the ``Environment`` property wrapper, passing the object's type to the
/// wrapper (using this syntax, the object type can be omitted from the end
/// of property declaration):
///
/// @Observable final class Profile { ... }
///
/// struct MyView: View {
/// @Environment(Profile.self) private var currentProfile
///
/// // ...
/// }
///
/// - Warning: If no object has been set in the view's environment, this
/// property will issue a fatal error when accessed. To safely check for the
/// existence of an environment object, initialize the environment property
/// with an optional object type instead.
///
/// SwiftUI automatically updates any parts of `MyView` that depend on the
/// property when the associated environment object changes.
///
/// You can't modify the environment object using a property like this.
/// Instead, use the ``View/environment(_:)`` view modifier on a view
/// to set an object for a view hierarchy.
///
/// - Parameter objectType: The type of the `Observable` object to read
/// from the environment.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public init(_ objectType: Value.Type) where Value : AnyObject, Value : Observable
/// Creates an environment property to read an observable object from the
/// environment, returning `nil` if no corresponding object has been set in
/// the current view's environment.
///
/// - Important: This initializer only accepts objects conforming to the
/// `Observable` protocol. For reading environment objects that conform to
/// `ObservableObject`, use ``EnvironmentObject`` instead.
///
/// Don’t call this initializer directly. Instead, declare an optional
/// property with the ``Environment`` property wrapper, passing the object's
/// type to the wrapper:
///
/// @Observable final class Profile { ... }
///
/// struct MyView: View {
/// @Environment(Profile.self) private var currentProfile: Profile?
///
/// // ...
/// }
///
/// If no object has been set in the view's environment, this property will
/// return `nil` as its wrapped value.
///
/// SwiftUI automatically updates any parts of `MyView` that depend on the
/// property when the associated environment object changes.
///
/// You can't modify the environment object using a property like this.
/// Instead, use the ``View/environment(_:)`` view modifier on a view
/// to set an object for a view hierarchy.
///
/// - Parameter objectType: The type of the `Observable` object to read
/// from the environment.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public init<T>(_ objectType: T.Type) where Value == T?, T : AnyObject, T : Observable
}
/// A key for accessing values in the environment.
///
/// 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
/// ``View/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 {
/// func myCustomValue(_ myCustomValue: String) -> some 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".
/// }
/// }
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol EnvironmentKey {
/// The associated type representing the type of the environment key's
/// value.
associatedtype Value
/// The default value for the environment key.
static var defaultValue: Self.Value { get }
}
/// A property wrapper type for an observable object that a parent or ancestor
/// view supplies.
///
/// An environment object invalidates the current view whenever the observable
/// object that conforms to
/// <doc://com.apple.documentation/documentation/Combine/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
/// ``View/environmentObject(_:)`` modifier.
///
/// > Note: If your observable object conforms to the
/// <doc://com.apple.documentation/documentation/Observation/Observable>
/// protocol, use ``Environment`` instead of `EnvironmentObject` and set the
/// model object in an ancestor view by calling its ``View/environment(_:)-4516h``
/// or ``View/environment(_:_:)`` modifiers.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen @propertyWrapper public struct EnvironmentObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject {
/// A wrapper of the underlying environment object that can create bindings
/// to its properties using dynamic member lookup.
@dynamicMemberLookup @frozen public struct Wrapper {
/// Returns a binding to the resulting value of a given key path.
///
/// - Parameter keyPath: A key path to a specific resulting value.
///
/// - Returns: A new binding.
public subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<ObjectType, Subject>) -> Binding<Subject> { get }
}
/// The underlying value referenced by the environment object.
///
/// This property provides primary access to the value's data. However, you
/// don't access `wrappedValue` directly. Instead, you use the property
/// variable created with the ``EnvironmentObject`` attribute.
///
/// When a mutable value changes, the new value is immediately available.
/// However, a view displaying the value is updated asynchronously and may
/// not show the new value immediately.
@MainActor @inlinable public var wrappedValue: ObjectType { get }
/// A projection of the environment object that creates bindings to its
/// properties using dynamic member lookup.
///
/// Use the projected value to pass an environment object down a view
/// hierarchy.
@MainActor public var projectedValue: EnvironmentObject<ObjectType>.Wrapper { get }
/// Creates an environment object.
public init()
}
/// A collection of environment values propagated through a view hierarchy.
///
/// 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
/// ``EnvironmentValues/pixelLength``, ``EnvironmentValues/scenePhase``, or
/// ``EnvironmentValues/locale``, based on device characteristics, system state,
/// or user settings. For others, like ``EnvironmentValues/lineLimit``, SwiftUI
/// provides a reasonable default value.
///
/// You can set or override some values using the ``View/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 ``EnvironmentValues/lineLimit`` value directly, as in the previous
/// example, you should instead use the ``View/lineLimit(_:)-513mb`` modifier:
///
/// MyView()
/// .lineLimit(2)
///
/// In some cases, using a dedicated view modifier provides additional
/// functionality. For example, you must use the
/// ``View/preferredColorScheme(_:)`` modifier rather than setting
/// ``EnvironmentValues/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 custom environment values by defining a type that
/// conforms to the ``EnvironmentKey`` protocol, and then extending the
/// environment values structure with a new property. Use your key to get and
/// set the value, and provide a dedicated modifier for clients to use when
/// setting the value:
///
/// private struct MyEnvironmentKey: EnvironmentKey {
/// static let defaultValue: String = "Default value"
/// }
///
/// extension EnvironmentValues {
/// var myCustomValue: String {
/// get { self[MyEnvironmentKey.self] }
/// set { self[MyEnvironmentKey.self] = newValue }
/// }
/// }
///
/// extension View {
/// func myCustomValue(_ myCustomValue: String) -> some View {
/// environment(\.myCustomValue, myCustomValue)
/// }
/// }
///
/// Clients of your value then access the value in the usual way, reading it
/// with the ``Environment`` property wrapper, and setting it with the
/// `myCustomValue` view modifier.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct EnvironmentValues : CustomStringConvertible {
/// Creates an environment values instance.
///
/// You don't typically create an instance of ``EnvironmentValues``
/// directly. Doing so would provide access only to default values that
/// don't update based on system settings or device characteristics.
/// Instead, you rely on an environment values' instance
/// that SwiftUI manages for you when you use the ``Environment``
/// property wrapper and the ``View/environment(_:_:)`` view modifier.
public init()
/// Accesses the environment value associated with a custom key.
///
/// Create custom environment values by defining a key
/// that conforms to the ``EnvironmentKey`` protocol, and then using that
/// key with the subscript operator of the ``EnvironmentValues`` structure
/// to get and set a value for that key:
///
/// private struct MyEnvironmentKey: EnvironmentKey {
/// static let defaultValue: String = "Default value"
/// }
///
/// extension EnvironmentValues {
/// var myCustomValue: String {
/// get { self[MyEnvironmentKey.self] }
/// set { self[MyEnvironmentKey.self] = newValue }
/// }
/// }
///
/// You use custom environment values the same way you use system-provided
/// values, setting a value with the ``View/environment(_:_:)`` view
/// modifier, and reading values with the ``Environment`` property wrapper.
/// You can also provide a dedicated view modifier as a convenience for
/// setting the value:
///
/// extension View {
/// func myCustomValue(_ myCustomValue: String) -> some View {
/// environment(\.myCustomValue, myCustomValue)
/// }
/// }
///
public subscript<K>(key: K.Type) -> K.Value where K : EnvironmentKey
/// A string that represents the contents of the environment values
/// instance.
public var description: String { get }
}
extension EnvironmentValues {
/// Whether the Large Content Viewer is enabled.
///
/// The system can automatically provide a large content view
/// with ``View/accessibilityShowsLargeContentViewer()``
/// or you can provide your own with ``View/accessibilityShowsLargeContentViewer(_:)``.
///
/// While it is not necessary to check this value before adding
/// a large content view, it may be helpful if you need to
/// adjust the behavior of a gesture. For example, a button with
/// a long press handler might increase its long press duration
/// so the user can read the text in the large content viewer first.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public var accessibilityLargeContentViewerEnabled: Bool { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension EnvironmentValues {
/// The current redaction reasons applied to the view hierarchy.
public var redactionReasons: RedactionReasons
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// Whether the system preference for Differentiate without Color is enabled.
///
/// If this is true, UI should not convey information using color alone
/// and instead should use shapes or glyphs to convey information.
public var accessibilityDifferentiateWithoutColor: Bool { get }
/// Whether the system preference for Reduce Transparency is enabled.
///
/// If this property's value is true, UI (mainly window) backgrounds should
/// not be semi-transparent; they should be opaque.
public var accessibilityReduceTransparency: Bool { get }
/// Whether the system preference for Reduce Motion is enabled.
///
/// If this property's value is true, UI should avoid large animations,
/// especially those that simulate the third dimension.
public var accessibilityReduceMotion: Bool { get }
/// Whether the system preference for Invert Colors is enabled.
///
/// If this property's value is true then the display will be inverted.
/// In these cases it may be needed for UI drawing to be adjusted to in
/// order to display optimally when inverted.
public var accessibilityInvertColors: Bool { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension EnvironmentValues {
/// Whether the system preference for Show Button Shapes is enabled.
///
/// If this property's value is true, interactive custom controls
/// such as buttons should be drawn in such a way that their edges
/// and borders are clearly visible.
public var accessibilityShowButtonShapes: Bool { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension EnvironmentValues {
/// 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.
public var accessibilityDimFlashingLights: Bool { get }
/// 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.
public var accessibilityPlayAnimatedImages: Bool { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// A Boolean value that indicates whether the VoiceOver screen reader is in use.
///
/// The state changes as the user turns on or off the VoiceOver screen reader.
public var accessibilityVoiceOverEnabled: Bool { get }
/// A Boolean value that indicates whether the Switch Control motor accessibility feature is in use.
///
/// The state changes as the user turns on or off the Switch Control feature.
public var accessibilitySwitchControlEnabled: Bool { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension EnvironmentValues {
/// The prominence of the background underneath views associated with this
/// environment.
///
/// Foreground elements above an increased prominence background are
/// typically adjusted to have higher contrast against a potentially vivid
/// color, such as taking on a higher opacity monochrome appearance
/// according to the `colorScheme`. System styles like `primary`,
/// `secondary`, etc will automatically resolve to an appropriate style in
/// this context. The property can be read and used for custom styled
/// elements.
///
/// In the example below, a custom star rating element is in a list row
/// alongside some text. When the row is selected and has an increased
/// prominence appearance, the text and star rating will update their
/// appearance, the star rating replacing its use of yellow with the
/// standard `secondary` style.
///
/// struct RecipeList: View {
/// var recipes: [Recipe]
/// @Binding var selectedRecipe: Recipe.ID?
///
/// var body: some View {
/// List(recipes, selection: $selectedRecipe) {
/// RecipeListRow(recipe: $0)
/// }
/// }
/// }
///
/// struct RecipeListRow: View {
/// var recipe: Recipe
/// var body: some View {
/// VStack(alignment: .leading) {
/// HStack(alignment: .firstTextBaseline) {
/// Text(recipe.name)
/// Spacer()
/// StarRating(rating: recipe.rating)
/// }
/// Text(recipe.description)
/// .foregroundStyle(.secondary)
/// .lineLimit(2, reservesSpace: true)
/// }
/// }
/// }
///
/// private struct StarRating: View {
/// var rating: Int
///
/// @Environment(\.backgroundProminence)
/// private var backgroundProminence
///
/// var body: some View {
/// HStack(spacing: 1) {
/// ForEach(0..<rating, id: \.self) { _ in
/// Image(systemName: "star.fill")
/// }
/// }
/// .foregroundStyle(backgroundProminence == .increased ?
/// AnyShapeStyle(.secondary) : AnyShapeStyle(.yellow))
/// .imageScale(.small)
/// }
/// }
///
/// Note that the use of `backgroundProminence` was used by a view that
/// was nested in additional stack containers within the row. This ensured
/// that the value correctly reflected the environment within the list row
/// itself, as opposed to the environment of the list as a whole. One way
/// to ensure correct resolution would be to prefer using this in a custom
/// ShapeStyle instead, for example:
///
/// private struct StarRating: View {
/// var rating: Int
///
/// var body: some View {
/// HStack(spacing: 1) {
/// ForEach(0..<rating, id: \.self) { _ in
/// Image(systemName: "star.fill")
/// }
/// }
/// .foregroundStyle(FillStyle())
/// .imageScale(.small)
/// }
/// }
///
/// extension StarRating {
/// struct FillStyle: ShapeStyle {
/// func resolve(in env: EnvironmentValues) -> some ShapeStyle {
/// switch env.backgroundProminence {
/// case .increased: return AnyShapeStyle(.secondary)
/// default: return AnyShapeStyle(.yellow)
/// }
/// }
/// }
/// }
///
/// Views like `List` and `Table` as well as standard shape styles like
/// `ShapeStyle.selection` will automatically update the background
/// prominence of foreground views. For custom backgrounds, this environment
/// property can be explicitly set on views above custom backgrounds.
public var backgroundProminence: BackgroundProminence
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EnvironmentValues {
/// A Boolean value that indicates whether the current platform supports
/// opening multiple windows.
///
/// Read this property from the environment to determine if your app can
/// use the ``EnvironmentValues/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 `true` for any app that uses the
/// SwiftUI app lifecycle.
/// * In iPadOS, this property returns `true` for any app that uses the
/// SwiftUI app lifecycle and has the Information Property List key
/// <doc://com.apple.documentation/documentation/bundleresources/information_property_list/uiapplicationscenemanifest/uiapplicationsupportsmultiplescenes> set to `true`.
/// * 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.
public var supportsMultipleWindows: Bool { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// An action that dismisses the current presentation.
///
/// 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 ``DismissAction/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``.
/// * Close a window that you create with ``WindowGroup`` or ``Window``.
///
/// 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
/// ``View/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 ``EnvironmentValues/isPresented`` environment value.
public var dismiss: DismissAction { get }
/// A Boolean value that indicates whether the view associated with this
/// environment is currently presented.
///
/// 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 ``View/onChange(of:perform:)``
/// modifier:
///
/// .onChange(of: isPresented) { isPresented in
/// if isPresented {
/// // Do something when first presented.
/// }
/// }
///
/// This behaves differently than ``View/onAppear(perform:)``, which
/// SwiftUI can call more than once for a given presentation, like
/// when you navigate back to a view that's already in the
/// navigation hierarchy.
///
/// To dismiss the currently presented view, use
/// ``EnvironmentValues/dismiss``.
public var isPresented: Bool { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// An environment value that indicates how a text view aligns its lines
/// when the content wraps or contains newlines.
///
/// Set this value for a view hierarchy by applying the
/// ``View/multilineTextAlignment(_:)`` view modifier. Views in the
/// hierarchy that display text, like ``Text`` or ``TextEditor``, read the
/// value from the environment and adjust their text alignment accordingly.
///
/// This value has no effect on a ``Text`` view that contains only one
/// line of text, because a text view has a width that exactly matches the
/// width of its widest line. If you want to align an entire text view
/// rather than its contents, set the aligment of its container, like a
/// ``VStack`` or a frame that you create with the
/// ``View/frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)``
/// modifier.
///
/// > Note: You can use this value to control the alignment of a ``Text``
/// view that you create with the ``Text/init(_:style:)`` initializer
/// to display localized dates and times, including when the view uses
/// only a single line, but only when that view appears in a widget.
public var multilineTextAlignment: TextAlignment
/// A value that indicates how the layout truncates the last line of text to
/// fit into the available space.
///
/// The default value is ``Text/TruncationMode/tail``. Some controls,
/// however, might have a different default if appropriate.
public var truncationMode: Text.TruncationMode
/// The distance in points between the bottom of one line fragment and the
/// top of the next.
///
/// This value is always nonnegative.
public var lineSpacing: CGFloat
/// A Boolean value that indicates whether inter-character spacing should
/// tighten to fit the text into the available space.
///
/// The default value is `false`.
public var allowsTightening: Bool
/// The minimum permissible proportion to shrink the font size to fit
/// the text into the available space.
///
/// In the example below, a label with a `minimumScaleFactor` of `0.5`
/// draws its text in a font size as small as half of the actual font if
/// needed to fit into the space next to the text input field:
///
/// HStack {
/// Text("This is a very long label:")
/// .lineLimit(1)
/// .minimumScaleFactor(0.5)
/// TextField("My Long Text Field", text: $myTextField)
/// .frame(width: 250, height: 50, alignment: .center)
/// }
///
/// ![A screenshot showing the effects of setting the minimumScaleFactor on
/// the text in a view](SwiftUI-View-minimumScaleFactor.png)
///
/// You can set the minimum scale factor to any value greater than `0` and
/// less than or equal to `1`. The default value is `1`.
///
/// SwiftUI uses this value to shrink text that doesn't fit in a view when
/// it's okay to shrink the text. For example, a label with a
/// `minimumScaleFactor` of `0.5` draws its text in a font size as small as
/// half the actual font if needed.
public var minimumScaleFactor: CGFloat
/// A stylistic override to transform the case of `Text` when displayed,
/// using the environment's locale.
///
/// The default value is `nil`, displaying the `Text` without any case
/// changes.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public var textCase: Text.Case?
}
extension EnvironmentValues {
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "dynamicTypeSize")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "dynamicTypeSize")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "dynamicTypeSize")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "dynamicTypeSize")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, renamed: "dynamicTypeSize")
public var sizeCategory: ContentSizeCategory
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// The allowed dynamic range for the view, or nil.
public var allowedDynamicRange: Image.DynamicRange?
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EnvironmentValues {
/// An optional style that overrides the default system background
/// style when set.
public var backgroundStyle: AnyShapeStyle?
}
@available(iOS 16.0, macOS 13.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// An window presentation action stored in a view's environment.
///
/// 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
/// ``OpenWindowAction/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 `id` parameter,
/// as in the above example.
/// * A `value` parameter 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
/// <doc://com.apple.documentation/documentation/Foundation/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.
public var openWindow: OpenWindowAction { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// The color scheme of this environment.
///
/// 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
/// ``View/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 ``EnvironmentValues/colorSchemeContrast``
/// property, which reflects a system-wide contrast setting that the user
/// controls. For information about using color and contrast in your app,
/// see [Color and Contrast](https://developer.apple.com/design/human-interface-guidelines/accessibility/overview/color-and-contrast/).
///
/// > Note: If you only need to provide different colors or
/// images for different color scheme and contrast settings, do that in
/// your app's Asset Catalog. See
/// <doc://com.apple.documentation/documentation/Xcode/Asset-Management>.
public var colorScheme: ColorScheme
/// The contrast associated with the color scheme of this environment.
///
/// 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 ``EnvironmentValues/colorScheme`` property
/// to find out if SwiftUI is displaying the view with a light or dark
/// appearance. For information about using color and contrast in your app,
/// see [Color and Contrast](https://developer.apple.com/design/human-interface-guidelines/accessibility/overview/color-and-contrast/).
///
/// > Note: If you only need to provide different colors or
/// images for different color scheme and contrast settings, do that in
/// your app's Asset Catalog. See
/// <doc://com.apple.documentation/documentation/Xcode/Asset-Management>.
public var colorSchemeContrast: ColorSchemeContrast { get }
}
@available(macOS 13.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
extension EnvironmentValues {
/// An action in the environment that presents a new document.
///
/// 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 ``NewDocumentAction/callAsFunction(_:)-3h5h6``
/// 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.
public var newDocument: NewDocumentAction { get }
/// An action in the environment that presents an existing document.
///
/// 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 ``OpenDocumentAction/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.
public var openDocument: OpenDocumentAction { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The prominence to apply to section headers within a view.
///
/// The default is ``Prominence/standard``.
public var headerProminence: Prominence
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EnvironmentValues {
/// The preferred order of items for menus presented from this view.
///
/// Set this value for a view hierarchy by calling the
/// ``View/menuOrder(_:)`` view modifier.
public var menuOrder: MenuOrder
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension EnvironmentValues {
/// The behavior of spring loaded interactions for the views associated
/// with this environment.
///
/// Spring loading refers to a view being activated during a drag and drop
/// interaction. On iOS this can occur when pausing briefly on top of a
/// view with dragged content. On macOS this can occur with similar brief
/// pauses or on pressure-sensitive systems by "force clicking" during the
/// drag. This has no effect on tvOS or watchOS.
///
/// This is commonly used with views that have a navigation or presentation
/// effect, allowing the destination to be revealed without pausing the
/// drag interaction. For example, a button that reveals a list of folders
/// that a dragged item can be dropped onto.
///
/// A value of `enabled` means that a view should support spring loaded
/// interactions if it is able, and `disabled` means it should not.
/// A value of `automatic` means that a view should follow its default
/// behavior, such as a `TabView` automatically allowing spring loading,
/// but a `Picker` with `segmented` style would not.
public var springLoadingBehavior: SpringLoadingBehavior { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension EnvironmentValues {
/// The current phase of the scene.
///
/// 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``.
public var scenePhase: ScenePhase
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// The default minimum height of a row in a list.
public var defaultMinListRowHeight: CGFloat
/// The default minimum height of a header in a list.
///
/// When this value is `nil`, the system chooses the appropriate height. The
/// default is `nil`.
public var defaultMinListHeaderHeight: CGFloat?
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension EnvironmentValues {
/// An action that opens a URL.
///
/// Read this environment value to get an ``OpenURLAction``
/// instance for a given ``Environment``. Call the
/// instance to open a URL. You call the instance directly because it
/// defines a ``OpenURLAction/callAsFunction(_:)`` method that Swift
/// calls when you call the instance.
///
/// For example, you can open a web site when the user taps a button:
///
/// struct OpenURLExample: View {
/// @Environment(\.openURL) private var openURL
///
/// var body: some View {
/// Button {
/// if let url = URL(string: "https://www.example.com") {
/// openURL(url)
/// }
/// } label: {
/// Label("Get Help", systemImage: "person.fill.questionmark")
/// }
/// }
/// }
///
/// If you want to know whether the action succeeds, add a completion
/// handler that takes a Boolean value. In this case, Swift implicitly
/// calls the ``OpenURLAction/callAsFunction(_:completion:)`` method
/// instead. That method calls your completion handler after it determines
/// whether it can open the URL, but possibly before it finishes opening
/// the URL. You can add a handler to the example above so that
/// it prints the outcome to the console:
///
/// openURL(url) { accepted in
/// print(accepted ? "Success" : "Failure")
/// }
///
/// The system provides a default open URL action with behavior
/// that depends on the contents of the URL. For example, the default
/// action opens a Universal Link in the associated app if possible,
/// or in the user’s default web browser if not.
///
/// You can also set a custom action using the ``View/environment(_:_:)``
/// view modifier. Any views that read the action from the environment,
/// including the built-in ``Link`` view and ``Text`` views with markdown
/// links, or links in attributed strings, use your action. Initialize an
/// action by calling the ``OpenURLAction/init(handler:)`` initializer with
/// a handler that takes a URL and returns an ``OpenURLAction/Result``:
///
/// Text("Visit [Example Company](https://www.example.com) for details.")
/// .environment(\.openURL, OpenURLAction { url in
/// handleURL(url) // Define this method to take appropriate action.
/// return .handled
/// })
///
/// SwiftUI translates the value that your custom action's handler
/// returns into an appropriate Boolean result for the action call.
/// For example, a view that uses the action declared above
/// receives `true` when calling the action, because the
/// handler always returns ``OpenURLAction/Result/handled``.
public var openURL: OpenURLAction
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The symbol variant to use in this environment.
///
/// You set this environment value indirectly by using the
/// ``View/symbolVariant(_:)`` view modifier. However, you access the
/// environment variable directly using the ``View/environment(_:_:)``
/// modifier. Do this when you want to use the ``SymbolVariants/none``
/// variant to ignore the value that's already in the environment:
///
/// HStack {
/// Image(systemName: "heart")
/// Image(systemName: "heart")
/// .environment(\.symbolVariants, .none)
/// }
/// .symbolVariant(.fill)
///
/// ![A screenshot of two heart symbols. The first is filled while the
/// second is outlined.](SymbolVariants-none-1)
public var symbolVariants: SymbolVariants
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// The layout direction associated with the current environment.
///
/// Use this value to determine or set whether the environment uses a
/// left-to-right or right-to-left direction.
public var layoutDirection: LayoutDirection
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// A binding to the current presentation mode of the view associated with
/// this environment.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Use isPresented or dismiss")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use isPresented or dismiss")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Use isPresented or dismiss")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Use isPresented or dismiss")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use isPresented or dismiss")
public var presentationMode: Binding<PresentationMode> { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// A refresh action stored in a view's environment.
///
/// When this environment value contains an instance of the
/// ``RefreshAction`` structure, certain built-in views in the corresponding
/// ``Environment`` begin offering a refresh capability. They apply the
/// instance's handler to any refresh operation that the user initiates.
/// By default, the environment value is `nil`, but you can use the
/// ``View/refreshable(action:)`` modifier to create and store a new
/// refresh action that uses the handler that you specify:
///
/// List(mailbox.conversations) { conversation in
/// ConversationCell(conversation)
/// }
/// .refreshable {
/// await mailbox.fetch()
/// }
///
/// On iOS and iPadOS, the ``List`` in the example above offers a
/// pull to refresh gesture because it detects the refresh action. When
/// the user drags the list down and releases, the list calls the action's
/// handler. Because SwiftUI declares the handler as asynchronous, it can
/// safely make long-running asynchronous calls, like fetching network data.
///
/// ### Refreshing custom views
///
/// You can also offer refresh capability in your custom views.
/// Read the `refresh` environment value to get the ``RefreshAction``
/// instance for a given ``Environment``. If you find
/// a non-`nil` value, change your view's appearance or behavior to offer
/// the refresh to the user, and call the instance to conduct the
/// refresh. You can call the refresh instance directly because it defines
/// a ``RefreshAction/callAsFunction()`` method that Swift calls
/// when you call the instance:
///
/// struct RefreshableView: View {
/// @Environment(\.refresh) private var refresh
///
/// var body: some View {
/// Button("Refresh") {
/// Task {
/// await refresh?()
/// }
/// }
/// .disabled(refresh == nil)
/// }
/// }
///
/// Be sure to call the handler asynchronously by preceding it
/// with `await`. Because the call is asynchronous, you can use
/// its lifetime to indicate progress to the user. For example,
/// you can reveal an indeterminate ``ProgressView`` before
/// calling the handler, and hide it when the handler completes.
///
/// If your code isn't already in an asynchronous context, create a
/// <doc://com.apple.documentation/documentation/Swift/Task> for the
/// method to run in. If you do this, consider adding a way for the
/// user to cancel the task. For more information, see
/// [Concurrency](https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html)
/// in *The Swift Programming Language*.
public var refresh: RefreshAction? { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EnvironmentValues {
/// The current size of sidebar rows.
///
/// On macOS, reflects the value of the "Sidebar icon size" in
/// System Settings' Appearance settings.
///
/// This can be used to update the content shown in the sidebar in
/// response to this size. And it can be overridden to force a sidebar to a
/// particularly size, regardless of the user preference.
///
/// On other platforms, the value is always `.medium` and setting a
/// different value has no effect.
///
/// SwiftUI views like `Label` automatically adapt to the sidebar row size.
public var sidebarRowSize: SidebarRowSize
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// The default font of this environment.
public var font: Font?
/// The display scale of this environment.
public var displayScale: CGFloat
/// The image scale for this environment.
@available(macOS 11.0, *)
public var imageScale: Image.Scale
/// The size of a pixel on the screen.
///
/// This value is usually equal to `1` divided by
/// ``EnvironmentValues/displayScale``.
public var pixelLength: CGFloat { get }
/// The font weight to apply to text.
///
/// This value reflects the value of the Bold Text display setting found in
/// the Accessibility settings.
public var legibilityWeight: LegibilityWeight?
/// The current locale that views should use.
public var locale: Locale
/// The current calendar that views should use when handling dates.
public var calendar: Calendar
/// The current time zone that views should use when handling dates.
public var timeZone: TimeZone
}
extension EnvironmentValues {
/// The horizontal size class of this environment.
///
/// You receive a ``UserInterfaceSizeClass`` value when you read this
/// environment value. The value tells you about the amount of horizontal
/// space available to the view that reads it. You can read this
/// size class like any other of the ``EnvironmentValues``, by creating a
/// property with the ``Environment`` property wrapper:
///
/// @Environment(\.horizontalSizeClass) private var horizontalSizeClass
///
/// SwiftUI sets this size class based on several factors, including:
///
/// * The current device type.
/// * The orientation of the device.
/// * The appearance of Slide Over and Split View on iPad.
///
/// Several built-in views change their behavior based on this size class.
/// For example, a ``NavigationView`` presents a multicolumn view when
/// the horizontal size class is ``UserInterfaceSizeClass/regular``,
/// but a single column otherwise. You can also adjust the appearance of
/// custom views by reading the size class and conditioning your views.
/// If you do, be prepared to handle size class changes while
/// your app runs, because factors like device orientation can change at
/// runtime.
///
/// In watchOS, the horizontal size class is always
/// ``UserInterfaceSizeClass/compact``. In macOS, and tvOS, it's always
/// ``UserInterfaceSizeClass/regular``.
///
/// Writing to the horizontal size class in the environment
/// before macOS 14.0, tvOS 17.0, and watchOS 10.0 is not supported.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@_backDeploy(before: macOS 14.0, tvOS 17.0, watchOS 10.0)
public var horizontalSizeClass: UserInterfaceSizeClass?
/// The vertical size class of this environment.
///
/// You receive a ``UserInterfaceSizeClass`` value when you read this
/// environment value. The value tells you about the amount of vertical
/// space available to the view that reads it. You can read this
/// size class like any other of the ``EnvironmentValues``, by creating a
/// property with the ``Environment`` property wrapper:
///
/// @Environment(\.verticalSizeClass) private var verticalSizeClass
///
/// SwiftUI sets this size class based on several factors, including:
///
/// * The current device type.
/// * The orientation of the device.
///
/// You can adjust the appearance of custom views by reading this size
/// class and conditioning your views. If you do, be prepared to
/// handle size class changes while your app runs, because factors like
/// device orientation can change at runtime.
///
/// In watchOS, the vertical size class is always
/// ``UserInterfaceSizeClass/compact``. In macOS, and tvOS, it's always
/// ``UserInterfaceSizeClass/regular``.
///
/// Writing to the vertical size class in the environment
/// before macOS 14.0, tvOS 17.0, and watchOS 10.0 is not supported.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@_backDeploy(before: macOS 14.0, tvOS 17.0, watchOS 10.0)
public var verticalSizeClass: UserInterfaceSizeClass?
}
extension EnvironmentValues {
/// The active state of controls in the view.
///
/// The default is ``ControlActiveState/key``.
@available(macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public var controlActiveState: ControlActiveState
}
extension EnvironmentValues {
/// Reads an observable object of the specified type from the environment.
///
/// - Important: This subscript only supports reading objects that conform
/// to the `Observable` protocol.
///
/// Use this subscript to read the environment object of a specific type
/// from an instance of ``EnvironmentValues``, such as when accessing the
/// ``GraphicsContext/environment`` property of a graphics context:
///
/// @Observable final class Profile { ... }
///
/// Canvas { context, size in
/// let currentProfile = context.environment[Profile.self]
/// ...
/// }
///
/// - Parameter objectType: The type of the `Observable` object to read
/// from the environment.
///
/// - Returns: The environment object of the specified type, or `nil` if no
/// object of that type has been set in this environment.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public subscript<T>(objectType: T.Type) -> T? where T : AnyObject, T : Observable
}
extension EnvironmentValues {
/// The maximum number of lines that text can occupy in a view.
///
/// The maximum number of lines is `1` if the value is less than `1`. If the
/// value is `nil`, the text uses as many lines as required. The default is
/// `nil`.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public var lineLimit: Int?
}
extension EnvironmentValues {
/// The visiblity to apply to scroll indicators of any
/// vertically scrollable content.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public var verticalScrollIndicatorVisibility: ScrollIndicatorVisibility
/// The visibility to apply to scroll indicators of any
/// horizontally scrollable content.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public var horizontalScrollIndicatorVisibility: ScrollIndicatorVisibility
}
extension EnvironmentValues {
/// A Boolean value that indicates whether any scroll views associated
/// with this environment allow scrolling to occur.
///
/// The default value is `true`. Use the ``View/scrollDisabled(_:)``
/// modifier to configure this property.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public var isScrollEnabled: Bool
}
extension EnvironmentValues {
/// The way that scrollable content interacts with the software keyboard.
///
/// The default value is ``ScrollDismissesKeyboardMode/automatic``. Use the
/// ``View/scrollDismissesKeyboard(_:)`` modifier to configure this
/// property.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@available(visionOS, unavailable)
public var scrollDismissesKeyboardMode: ScrollDismissesKeyboardMode
}
extension EnvironmentValues {
/// The scroll bounce mode for the vertical axis of scrollable views.
///
/// Use the ``View/scrollBounceBehavior(_:axes:)`` view modifier to set this
/// value in the ``Environment``.
@available(iOS 16.4, macOS 13.3, tvOS 16.4, watchOS 9.4, *)
public var verticalScrollBounceBehavior: ScrollBounceBehavior
/// The scroll bounce mode for the horizontal axis of scrollable views.
///
/// Use the ``View/scrollBounceBehavior(_:axes:)`` view modifier to set this
/// value in the ``Environment``.
@available(iOS 16.4, macOS 13.3, tvOS 16.4, watchOS 9.4, *)
public var horizontalScrollBounceBehavior: ScrollBounceBehavior
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// A Boolean value that indicates when the user is searching.
///
/// 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
/// ``View/searchable(text:placement:prompt:)-18a8f``:
///
/// 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
/// ``EnvironmentValues/dismissSearch``.
///
/// > Important: Access the value from inside the searched view, as the
/// example above demonstrates, rather than from the searched view’s
/// parent. SwiftUI sets the value in the environment of the view that
/// you apply the searchable modifier to, and doesn’t propagate the
/// value up the view hierarchy.
public var isSearching: Bool { get }
/// An action that ends the current search interaction.
///
/// 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 ``DismissSearchAction/callAsFunction()`` method that Swift
/// calls when you call the instance.
///
/// When you dismiss search, SwiftUI:
///
/// * Sets ``EnvironmentValues/isSearching`` to `false`.
/// * Clears any text from the search field.
/// * Removes focus from the search field.
///
/// > Note: Calling this instance has no effect if the user isn't
/// interacting with a 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 ``EnvironmentValues/dismiss`` property to dismiss
/// the sheet, and the ``EnvironmentValues/dismissSearch`` property to
/// reset the search field.
///
/// > Important: Access the action from inside the searched view, as the
/// example above demonstrates, rather than from the searched view’s
/// parent, or another hierarchy, like that of a sheet. SwiftUI sets the
/// value in the environment of the view that you apply the searchable
/// modifier to, and doesn’t propagate the value up the view hierarchy.
public var dismissSearch: DismissSearchAction { get }
/// The current placement of search suggestions.
///
/// Search suggestions render based on the platform and surrounding context
/// in which you place the searchable modifier containing suggestions.
/// You can render search suggestions in two ways:
///
/// * In a menu attached to the search field.
/// * Inline with the main content of the app.
///
/// You find the current search suggestion placement by querying the
/// ``EnvironmentValues/searchSuggestionsPlacement`` in your
/// search suggestions.
///
/// enum FruitSuggestion: String, Identifiable {
/// case apple, banana, orange
/// var id: Self { self }
/// }
///
/// @State private var text: String = ""
/// @State private var suggestions: [FruitSuggestion] = []
///
/// var body: some View {
/// MainContent()
/// .searchable(text: $text) {
/// FruitSuggestions(suggestions: suggestions)
/// }
/// }
///
/// struct FruitSuggestions: View {
/// var suggestions: [FruitSuggestion]
///
/// @Environment(\.searchSuggestionsPlacement)
/// private var placement
///
/// var body: some View {
/// if shouldRender {
/// ForEach(suggestions) { suggestion in
/// Text(suggestion.rawValue.capitalized)
/// .searchCompletion(suggestion.rawValue)
/// }
/// }
/// }
///
/// var shouldRender: Bool {
/// #if os(iOS)
/// placement == .menu
/// #else
/// true
/// #endif
/// }
/// }
///
/// In the above example, search suggestions only render in iOS
/// if the searchable modifier displays them in a menu. You might want
/// to do this to render suggestions in your own list alongside
/// your own search results when they would render in a list.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public var searchSuggestionsPlacement: SearchSuggestionsPlacement { get }
}
extension EnvironmentValues {
/// The configuration of a document in a ``DocumentGroup``.
///
/// 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"
/// )
/// }
/// }
///
@available(iOS 17.0, macOS 14.0, visionOS 1.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public var documentConfiguration: DocumentConfiguration? { get }
}
extension EnvironmentValues {
/// The undo manager used to register a view's undo operations.
///
/// 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`.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public var undoManager: UndoManager? { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The current Dynamic Type size.
///
/// This value changes as the user's chosen Dynamic Type size changes. The
/// default value is device-dependent.
///
/// When limiting the Dynamic Type size, consider if adding a
/// large content view with ``View/accessibilityShowsLargeContentViewer()``
/// would be appropriate.
///
/// On macOS, this value cannot be changed by users and does not affect the
/// text size.
public var dynamicTypeSize: DynamicTypeSize
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// A Boolean value that indicates whether the user has enabled an assistive
/// technology.
public var accessibilityEnabled: Bool
}
@available(macOS 12.0, tvOS 14.0, watchOS 7.0, *)
@available(iOS, unavailable)
@available(visionOS, unavailable)
extension EnvironmentValues {
/// An action that requests the focus system to reevaluate default focus.
///
/// Get this environment value and call and call it as a function to force
/// a default focus reevaluation at runtime.
///
/// @Namespace var mainNamespace
/// @Environment(\.resetFocus) var resetFocus
///
/// var body: some View {
/// // ...
/// resetFocus(in: mainNamespace)
/// // ...
/// }
///
public var resetFocus: ResetFocusAction { get }
}
extension EnvironmentValues {
/// A Boolean that indicates whether the quick actions feature is enabled.
///
/// The system uses quick actions to provide users with a
/// fast alternative interaction method. Quick actions can be
/// presented to users with a textual banner at the top of their
/// screen and/or an outline around a view that is already on screen.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public var accessibilityQuickActionsEnabled: Bool { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 8.0, *)
extension EnvironmentValues {
/// A Boolean value that indicates whether the display or environment currently requires
/// reduced luminance.
///
/// When you detect this condition, lower the overall brightness of your view.
/// For example, you can change large, filled shapes to be stroked, and choose
/// less bright colors:
///
/// @Environment(\.isLuminanceReduced) var isLuminanceReduced
///
/// var body: some View {
/// if isLuminanceReduced {
/// Circle()
/// .stroke(Color.gray, lineWidth: 10)
/// } else {
/// Circle()
/// .fill(Color.white)
/// }
/// }
///
/// In addition to the changes that you make, the system could also
/// dim the display to achieve a suitable brightness. By reacting to
/// `isLuminanceReduced`, you can preserve contrast and readability
/// while helping to satisfy the reduced brightness requirement.
///
/// > Note: On watchOS, the system typically sets this value to `true` when the user
/// lowers their wrist, but the display remains on. Starting in watchOS 8, the system keeps your
/// view visible on wrist down by default. If you want the system to blur the screen
/// instead, as it did in earlier versions of watchOS, set the value for the
/// <doc://com.apple.documentation/documentation/BundleResources/Information_Property_List/WKSupportsAlwaysOnDisplay>
/// key in your app's
/// <doc://com.apple.documentation/documentation/BundleResources/Information_Property_List>
/// file to `false`.
public var isLuminanceReduced: Bool
}
@available(iOS 15.0, macOS 12.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// The menu indicator visibility to apply to controls within a view.
///
/// - Note: On tvOS, the standard button styles do not include a menu
/// indicator, so this modifier will have no effect when using a
/// built-in button style. You can implement an indicator in your
/// own ``ButtonStyle`` implementation by checking the value of this
/// environment value.
public var menuIndicatorVisibility: Visibility
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EnvironmentValues {
/// The current method of animating the contents of views.
public var contentTransition: ContentTransition
/// A Boolean value that controls whether views that render content
/// transitions use GPU-accelerated rendering.
///
/// Setting this value to `true` causes SwiftUI to wrap content transitions
/// with a ``View/drawingGroup(opaque:colorMode:)`` modifier.
public var contentTransitionAddsDrawingGroup: Bool
}
@available(iOS 15.0, macOS 10.15, watchOS 9.0, *)
@available(tvOS, unavailable)
extension EnvironmentValues {
/// The size to apply to controls within a view.
///
/// The default is ``ControlSize/regular``.
@available(tvOS, unavailable)
public var controlSize: ControlSize
}
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// The keyboard shortcut that buttons in this environment will be triggered
/// with.
///
/// This is particularly useful in button styles when a button's appearance
/// depends on the shortcut associated with it. On macOS, for example, when
/// a button is bound to the Return key, it is typically drawn with a
/// special emphasis. This happens automatically when using the built-in
/// button styles, and can be implemented manually in custom styles using
/// this environment key:
///
/// private struct MyButtonStyle: ButtonStyle {
/// @Environment(\.keyboardShortcut)
/// private var shortcut: KeyboardShortcut?
///
/// func makeBody(configuration: Configuration) -> some View {
/// let labelFont = Font.body
/// .weight(shortcut == .defaultAction ? .bold : .regular)
/// configuration.label
/// .font(labelFont)
/// }
/// }
///
/// If no keyboard shortcut has been applied to the view or its ancestor,
/// then the environment value will be `nil`.
public var keyboardShortcut: KeyboardShortcut? { get }
}
extension EnvironmentValues {
/// A Boolean value that determines whether the view hierarchy has
/// auto-correction enabled.
///
/// The default value is `false`.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 8.0, *)
public var autocorrectionDisabled: Bool
}
extension EnvironmentValues {
/// A Boolean value that determines whether the view hierarchy has
/// auto-correction enabled.
///
/// When the value is `nil`, SwiftUI uses the system default. The default
/// value is `nil`.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "autocorrectionDisabled")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "autocorrectionDisabled")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "autocorrectionDisabled")
@available(watchOS, introduced: 8.0, deprecated: 100000.0, renamed: "autocorrectionDisabled")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, renamed: "autocorrectionDisabled")
public var disableAutocorrection: Bool?
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
public var managedObjectContext: NSManagedObjectContext
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension EnvironmentValues {
/// Whether buttons with this associated environment should repeatedly
/// trigger their actions on prolonged interactions.
///
/// A value of `enabled` means that buttons will be able to repeatedly
/// trigger their action, and `disabled` means they should not. A value of
/// `automatic` means that buttons will defer to default behavior.
public var buttonRepeatBehavior: ButtonRepeatBehavior { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension EnvironmentValues {
/// A Boolean value that indicates whether the view associated with this
/// environment allows focus effects to be displayed.
///
/// The default value is `true`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public var isFocusEffectEnabled: Bool
}
extension EnvironmentValues {
/// Returns whether the nearest focusable ancestor has focus.
///
/// If there is no focusable ancestor, the value is `false`.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public var isFocused: Bool { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The current symbol rendering mode, or `nil` denoting that the
/// mode is picked automatically using the current image and
/// foreground style as parameters.
public var symbolRenderingMode: SymbolRenderingMode?
}
@available(iOS 17.0, macOS 14.0, visionOS 1.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// A window dismissal action stored in a view's environment.
///
/// 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 ``DismissWindowAction/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")
/// }
/// }
/// }
public var dismissWindow: DismissWindowAction { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The material underneath the current view.
///
/// This value is `nil` if the current background isn't one of the standard
/// materials. If you set a material, the standard content styles enable
/// their vibrant rendering modes.
///
/// You set this value by calling one of the background modifiers that takes
/// a ``ShapeStyle``, like ``View/background(_:ignoresSafeAreaEdges:)``
/// or ``View/background(_:in:fillStyle:)-89n7j``, and passing in a
/// ``Material``. You can also set the value manually, using
/// `nil` to disable vibrant rendering, or a ``Material`` instance to
/// enable the vibrancy style associated with the specified material.
public var backgroundMaterial: Material?
}
extension EnvironmentValues {
/// An action that activates the standard rename interaction.
///
/// Use the ``View/renameAction(_:)-6lghl`` modifier to configure the rename
/// action in the environment.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public var rename: RenameAction? { get }
}
@available(iOS 17.0, macOS 14.0, *)
@available(watchOS, unavailable)
@available(tvOS, unavailable)
extension EnvironmentValues {
/// The prominence to apply to badges associated with this environment.
///
/// The default is ``BadgeProminence/standard``.
public var badgeProminence: BadgeProminence
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// A Boolean value that indicates whether the view associated with this
/// environment allows user interaction.
///
/// The default value is `true`.
public var isEnabled: Bool
}
/// A modifier that must resolve to a concrete modifier in an environment before
/// use.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol EnvironmentalModifier : ViewModifier where Self.Body == Never {
/// The type of modifier to use after being resolved.
associatedtype ResolvedModifier : ViewModifier
/// Resolve to a concrete modifier in the given `environment`.
func resolve(in environment: EnvironmentValues) -> Self.ResolvedModifier
}
/// 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.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct EquatableView<Content> : View where Content : Equatable, Content : View {
public var content: Content
@inlinable public init(content: Content)
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A set of key modifiers that you can add to a gesture.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct EventModifiers : OptionSet {
/// The raw value.
public let rawValue: Int
/// Creates a new set from a raw value.
///
/// - Parameter rawValue: The raw value with which to create the key
/// modifier.
public init(rawValue: Int)
/// The Caps Lock key.
public static let capsLock: EventModifiers
/// The Shift key.
public static let shift: EventModifiers
/// The Control key.
public static let control: EventModifiers
/// The Option key.
public static let option: EventModifiers
/// The Command key.
public static let command: EventModifiers
/// Any key on the numeric keypad.
public static let numericPad: EventModifiers
/// The Function key.
@available(iOS, deprecated: 15.0, message: "Function modifier is reserved for system applications")
@available(macOS, deprecated: 12.0, message: "Function modifier is reserved for system applications")
@available(tvOS, deprecated: 15.0, message: "Function modifier is reserved for system applications")
@available(watchOS, deprecated: 8.0, message: "Function modifier is reserved for system applications")
@available(visionOS, deprecated: 1.0, message: "Function modifier is reserved for system applications")
public static let function: EventModifiers
/// All possible modifier keys.
public static let all: EventModifiers
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = EventModifiers
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = EventModifiers
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = Int
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EventModifiers : Sendable {
}
/// A schedule for updating a timeline view at the start of every minute.
///
/// You can also use ``TimelineSchedule/everyMinute`` to construct this
/// schedule.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct EveryMinuteTimelineSchedule : TimelineSchedule, Sendable {
/// The sequence of dates in an every minute schedule.
///
/// The ``EveryMinuteTimelineSchedule/entries(from:mode:)`` method returns
/// a value of this type, which is a
/// <doc://com.apple.documentation/documentation/Swift/Sequence>
/// of dates, one per minute, in ascending order. A ``TimelineView`` that
/// you create updates its content at the moments in time corresponding to
/// the dates included in the sequence.
public struct Entries : Sequence, IteratorProtocol, Sendable {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying sequence. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// You must not call this method if any other copy of this iterator has been
/// advanced with a call to its `next()` method.
///
/// The following example shows how an iterator can be used explicitly to
/// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and
/// then call the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence, if a next element
/// exists; otherwise, `nil`.
public mutating func next() -> Date?
/// A type representing the sequence's elements.
public typealias Element = Date
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
public typealias Iterator = EveryMinuteTimelineSchedule.Entries
}
/// Creates a per-minute update schedule.
///
/// Use the ``EveryMinuteTimelineSchedule/entries(from:mode:)`` method
/// to get the sequence of dates.
public init()
/// Provides a sequence of per-minute dates starting from a given date.
///
/// A ``TimelineView`` that you create with an every minute schedule
/// calls this method to ask the schedule when to update its content.
/// The method returns a sequence of per-minute dates in increasing
/// order, from earliest to latest, that represents
/// when the timeline view updates.
///
/// For a `startDate` that's exactly minute-aligned, the
/// schedule's sequence of dates starts at that time. Otherwise, it
/// starts at the beginning of the specified minute. For
/// example, for start dates of both `10:09:32` and `10:09:00`, the first
/// entry in the sequence is `10:09:00`.
///
/// - Parameters:
/// - startDate: The date from which the sequence begins.
/// - mode: The mode for the update schedule.
/// - Returns: A sequence of per-minute dates in ascending order.
public func entries(from startDate: Date, mode: TimelineScheduleMode) -> EveryMinuteTimelineSchedule.Entries
}
/// A gesture that consists of two gestures where only one of them can succeed.
///
/// The `ExclusiveGesture` gives precedence to its first gesture.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct ExclusiveGesture<First, Second> : Gesture where First : Gesture, Second : Gesture {
/// The value of an exclusive gesture that indicates which of two gestures
/// succeeded.
@frozen public enum Value {
/// The first of two gestures succeeded.
case first(First.Value)
/// The second of two gestures succeeded.
case second(Second.Value)
}
/// The first of two gestures.
public var first: First
/// The second of two gestures.
public var second: Second
/// Creates a gesture from two gestures where only one of them succeeds.
///
/// - Parameters:
/// - first: The first of two gestures. This gesture has precedence over
/// the other gesture.
/// - second: The second of two gestures.
@inlinable public init(_ first: First, _ second: Second)
/// The type of gesture representing the body of `Self`.
public typealias Body = Never
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ExclusiveGesture.Value : Sendable where First.Value : Sendable, Second.Value : Sendable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ExclusiveGesture.Value : Equatable where First.Value : Equatable, Second.Value : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ExclusiveGesture<First, Second>.Value, b: ExclusiveGesture<First, Second>.Value) -> Bool
}
/// A window toolbar style which displays its title bar area above the toolbar.
///
/// You can also use ``WindowToolbarStyle/expanded`` to construct this style.
@available(macOS 11.0, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct ExpandedWindowToolbarStyle : WindowToolbarStyle {
/// Creates an expanded window toolbar style.
public init()
}
/// A schedule for updating a timeline view at explicit points in time.
///
/// You can also use ``TimelineSchedule/explicit(_:)`` to construct this
/// schedule.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct ExplicitTimelineSchedule<Entries> : TimelineSchedule where Entries : Sequence, Entries.Element == Date {
/// Creates a schedule composed of an explicit sequence of dates.
///
/// Use the ``ExplicitTimelineSchedule/entries(from:mode:)`` method
/// to get the sequence of dates.
///
/// - Parameter dates: The sequence of dates at which a timeline view
/// updates. Use a monotonically increasing sequence of dates,
/// and ensure that at least one is in the future.
public init(_ dates: Entries)
/// Provides the sequence of dates with which you initialized the schedule.
///
/// A ``TimelineView`` that you create with a schedule calls this
/// ``TimelineSchedule`` method to ask the schedule when to update its
/// content. The explicit timeline schedule implementation
/// of this method returns the unmodified sequence of dates that you
/// provided when you created the schedule with
/// ``TimelineSchedule/explicit(_:)``. As a result, this particular
/// implementation ignores the `startDate` and `mode` parameters.
///
/// - Parameters:
/// - startDate: The date from which the sequence begins. This
/// particular implementation of the protocol method ignores the start
/// date.
/// - mode: The mode for the update schedule. This particular
/// implementation of the protocol method ignores the mode.
/// - Returns: The sequence of dates that you provided at initialization.
public func entries(from startDate: Date, mode: TimelineScheduleMode) -> Entries
}
/// A property wrapper type that retrieves entities from a Core Data persistent
/// store.
///
/// 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
/// <doc://com.apple.documentation/documentation/CoreData/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)])
/// private var quakes: FetchedResults<Quake> // Define Quake in your model.
///
/// Alternatively, when you need more flexibility, you can initialize the
/// request with a configured
/// <doc://com.apple.documentation/documentation/CoreData/NSFetchRequest>
/// instance:
///
/// @FetchRequest(fetchRequest: request)
/// private var quakes: FetchedResults<Quake>
///
/// 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
/// ``EnvironmentValues/managedObjectContext`` environment value. To
/// support user interface activity, you typically rely on the
/// <doc://com.apple.documentation/documentation/CoreData/NSPersistentContainer/1640622-viewContext>
/// property of a shared
/// <doc://com.apple.documentation/documentation/CoreData/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.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@MainActor @propertyWrapper public struct FetchRequest<Result> where Result : NSFetchRequestResult {
/// The fetched results of the fetch request.
///
/// SwiftUI returns the value associated with this property
/// when you use ``FetchRequest`` as a property wrapper, and then access
/// the wrapped property by name. For example, consider the following
/// `quakes` property declaration that fetches a `Quake` type that the
/// <doc://com.apple.documentation/documentation/CoreData/loading_and_displaying_a_large_data_feed>
/// sample code project defines:
///
/// @FetchRequest(fetchRequest: request)
/// private var quakes: FetchedResults<Quake>
///
/// You access the request's `wrappedValue`, which contains a
/// ``FetchedResults`` instance, by referring to the `quakes` property
/// by name:
///
/// Text("Found \(quakes.count) earthquakes")
///
/// If you need to separate the request and the result
/// entities, you can declare `quakes` in two steps by
/// using the request's `wrappedValue` to obtain the results:
///
/// var fetchRequest = FetchRequest<Quake>(fetchRequest: request)
/// var quakes: FetchedResults<Quake> { fetchRequest.wrappedValue }
///
/// The `wrappedValue` property returns an empty array when there are no
/// fetched results --- for example, because no entities satisfy the
/// predicate, or because the data store is empty.
@MainActor public var wrappedValue: FetchedResults<Result> { get }
/// The request's configurable properties.
///
/// You initialize a ``FetchRequest`` with an optional predicate and
/// sort descriptors, either explicitly or using a configured
/// <doc://com.apple.documentation/documentation/CoreData/NSFetchRequest>.
/// Later, you can dynamically update the predicate and sort
/// parameters using the request's configuration structure.
///
/// You access or bind to a request's configuration components through
/// properties on the associated ``FetchedResults`` instance.
///
/// ### Configure using a binding
///
/// Get a ``Binding`` to a fetch request's configuration structure
/// by accessing the request's ``FetchRequest/projectedValue``, which you
/// do by using the dollar sign (`$`) prefix on the associated
/// results property. For example, you can create a request for `Quake`
/// entities --- a managed object type that the
/// <doc://com.apple.documentation/documentation/CoreData/loading_and_displaying_a_large_data_feed>
/// sample code project defines --- that initially sorts the results by time:
///
/// @FetchRequest(sortDescriptors: [SortDescriptor(\.time, order: .reverse)])
/// private var quakes: FetchedResults<Quake>
///
/// Then you can bind the request's sort descriptors,
/// which you access through the `quakes` result, to those
/// of a ``Table`` instance:
///
/// Table(quakes, sortOrder: $quakes.sortDescriptors) {
/// TableColumn("Place", value: \.place)
/// TableColumn("Time", value: \.time) { quake in
/// Text(quake.time, style: .time)
/// }
/// }
///
/// A user who clicks on a table column header initiates the following
/// sequence of events:
/// 1. The table updates the sort descriptors through the binding.
/// 2. The modified sort descriptors reconfigure the request.
/// 3. The reconfigured request fetches new results.
/// 4. SwiftUI redraws the table in response to new results.
///
/// ### Set configuration directly
///
/// If you need to access the fetch request's configuration elements
/// directly, use the ``FetchedResults/nsPredicate`` and
/// ``FetchedResults/sortDescriptors`` or
/// ``FetchedResults/nsSortDescriptors`` properties of the
/// ``FetchedResults`` instance. Continuing the example above, to
/// enable the user to dynamically update the predicate, declare a
/// ``State`` property to hold a query string:
///
/// @State private var query = ""
///
/// Then add an ``View/onChange(of:perform:)`` modifier to the ``Table``
/// that sets a new predicate any time the query changes:
///
/// .onChange(of: query) { value in
/// quakes.nsPredicate = query.isEmpty
/// ? nil
/// : NSPredicate(format: "place CONTAINS %@", value)
/// }
///
/// To give the user control over the string, add a ``TextField`` in your
/// user interface that's bound to the `query` state:
///
/// TextField("Filter", text: $query)
///
/// When the user types into the text field, the predicate updates,
/// the request fetches new results, and SwiftUI redraws the table.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct Configuration {
/// The request's sort descriptors, accessed as reference types.
///
/// Set this configuration value to cause a ``FetchRequest`` to execute
/// a fetch with a new collection of
/// <doc://com.apple.documentation/documentation/Foundation/NSSortDescriptor>
/// instances. If you want to use
/// <doc://com.apple.documentation/documentation/Foundation/SortDescriptor>
/// instances, set ``FetchRequest/Configuration/sortDescriptors``
/// instead.
///
/// Access this value of a ``FetchRequest/Configuration`` structure for
/// a given request by using the ``FetchedResults/nsSortDescriptors``
/// property on the associated ``FetchedResults`` instance, either
/// directly or through a ``Binding``.
public var nsSortDescriptors: [NSSortDescriptor]
/// The request's predicate.
///
/// Set this configuration value to cause a ``FetchRequest`` to execute
/// a fetch with a new predicate.
///
/// Access this value of a ``FetchRequest/Configuration`` structure for
/// a given request by using the ``FetchedResults/nsPredicate``
/// property on the associated ``FetchedResults`` instance, either
/// directly or through a ``Binding``.
public var nsPredicate: NSPredicate?
}
/// A binding to the request's mutable configuration properties.
///
/// SwiftUI returns the value associated with this property when you use
/// ``FetchRequest`` as a property wrapper on a ``FetchedResults`` instance,
/// and then access the results with a dollar sign (`$`) prefix. The value
/// that SwiftUI returns is a ``Binding`` to the request's
/// ``FetchRequest/Configuration`` structure, which dynamically
/// configures the request.
///
/// For example, consider the following fetch request for a type that the
/// <doc://com.apple.documentation/documentation/CoreData/loading_and_displaying_a_large_data_feed>
/// sample code project defines to store earthquake data, sorted based on
/// the `time` property:
///
/// @FetchRequest(sortDescriptors: [SortDescriptor(\.time, order: .reverse)])
/// private var quakes: FetchedResults<Quake>
///
/// You can use the projected value to enable a ``Table`` instance to make
/// updates:
///
/// Table(quakes, sortOrder: $quakes.sortDescriptors) {
/// TableColumn("Place", value: \.place)
/// TableColumn("Time", value: \.time) { quake in
/// Text(quake.time, style: .time)
/// }
/// }
///
/// Because you initialize the table using a binding to the descriptors,
/// the table can modify the sort in response to actions that the user
/// takes, like clicking a column header.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@MainActor public var projectedValue: Binding<FetchRequest<Result>.Configuration> { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension FetchRequest : DynamicProperty {
/// Updates the fetched results.
///
/// SwiftUI calls this function before rendering a view's
/// ``View/body-swift.property`` to ensure the view has the most recent
/// fetched results.
@MainActor public mutating func update()
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension FetchRequest {
/// Creates a fetch request for a specified entity description, based on a
/// predicate and sort parameters.
///
/// Use this initializer if you need to explicitly specify the entity type
/// for the request. If you specify a placeholder `Result` type in the
/// request declaration, use the
/// ``init(sortDescriptors:predicate:animation:)-4obxy`` initializer to
/// let the request infer the entity type. If you need more control over
/// the fetch request configuration, use ``init(fetchRequest:animation:)``.
///
/// - Parameters:
/// - entity: The description of the Core Data entity to fetch.
/// - sortDescriptors: An array of sort descriptors that define the sort
/// order of the fetched results.
/// - predicate: An
/// <doc://com.apple.documentation/documentation/Foundation/NSPredicate>
/// instance that defines logical conditions used to filter the fetched
/// results.
/// - animation: The animation to use for user interface changes that
/// result from changes to the fetched results.
@MainActor public init(entity: NSEntityDescription, sortDescriptors: [NSSortDescriptor], predicate: NSPredicate? = nil, animation: Animation? = nil)
/// Creates a fully configured fetch request that uses the specified
/// animation when updating results.
///
/// Use this initializer when you want to configure a fetch
/// request with more than a predicate and sort descriptors.
/// For example, you can vend a request from a `Quake` managed object
/// that the
/// <doc://com.apple.documentation/documentation/CoreData/loading_and_displaying_a_large_data_feed>
/// sample code project defines to store earthquake data.
/// Limit the number of results to `1000` by setting a
/// <doc://com.apple.documentation/documentation/CoreData/NSFetchRequest/1506622-fetchLimit>
/// for the request:
///
/// extension Quake {
/// var request: NSFetchRequest<Quake> {
/// let request = NSFetchRequest<Quake>(entityName: "Quake")
/// request.sortDescriptors = [
/// NSSortDescriptor(
/// keyPath: \Quake.time,
/// ascending: true)]
/// request.fetchLimit = 1000
/// return request
/// }
/// }
///
/// Use the request to define a ``FetchedResults`` property:
///
/// @FetchRequest(fetchRequest: Quake.request)
/// private var quakes: FetchedResults<Quake>
///
/// If you only need to configure the request's predicate and sort
/// descriptors, use ``init(sortDescriptors:predicate:animation:)-462jp``
/// instead. If you need to specify a ``Transaction`` rather than an
/// optional ``Animation``, use ``init(fetchRequest:transaction:)``.
///
/// - Parameters:
/// - fetchRequest: An
/// <doc://com.apple.documentation/documentation/CoreData/NSFetchRequest>
/// instance that describes the search criteria for retrieving data
/// from the persistent store.
/// - animation: The animation to use for user interface changes that
/// result from changes to the fetched results.
@MainActor public init(fetchRequest: NSFetchRequest<Result>, animation: Animation? = nil)
/// Creates a fully configured fetch request that uses the specified
/// transaction when updating results.
///
/// Use this initializer if you need a fetch request with updates that
/// affect the user interface based on a ``Transaction``. Otherwise, use
/// ``init(fetchRequest:animation:)``.
///
/// - Parameters:
/// - fetchRequest: An
/// <doc://com.apple.documentation/documentation/CoreData/NSFetchRequest>
/// instance that describes the search criteria for retrieving data
/// from the persistent store.
/// - transaction: A transaction to use for user interface changes that
/// result from changes to the fetched results.
@MainActor public init(fetchRequest: NSFetchRequest<Result>, transaction: Transaction)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension FetchRequest where Result : NSManagedObject {
/// Creates a fetch request based on a predicate and reference type sort
/// parameters.
///
/// The request gets the entity type from the `Result` instance by calling
/// that managed object's
/// <doc://com.apple.documentation/documentation/CoreData/NSManagedObject/1640588-entity>
/// type method. If you need to specify the entity type explicitly, use the
/// ``init(entity:sortDescriptors:predicate:animation:)`` initializer
/// instead. If you need more control over the fetch request configuration,
/// use ``init(fetchRequest:animation:)``. For value type sort
/// descriptors, use ``init(sortDescriptors:predicate:animation:)-462jp``.
///
/// - Parameters:
/// - sortDescriptors: An array of sort descriptors that define the sort
/// order of the fetched results.
/// - predicate: An
/// <doc://com.apple.documentation/documentation/Foundation/NSPredicate>
/// instance that defines logical conditions used to filter the fetched
/// results.
/// - animation: The animation to use for user interface changes that
/// result from changes to the fetched results.
@MainActor public init(sortDescriptors: [NSSortDescriptor], predicate: NSPredicate? = nil, animation: Animation? = nil)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension FetchRequest where Result : NSManagedObject {
/// Creates a fetch request based on a predicate and value type sort
/// parameters.
///
/// The request gets the entity type from the `Result` instance by calling
/// that managed object's
/// <doc://com.apple.documentation/documentation/CoreData/NSManagedObject/1640588-entity>
/// type method. If you need to specify the entity type explicitly, use the
/// ``init(entity:sortDescriptors:predicate:animation:)`` initializer
/// instead. If you need more control over the fetch request configuration,
/// use ``init(fetchRequest:animation:)``. For reference type sort
/// descriptors, use ``init(sortDescriptors:predicate:animation:)-4obxy``.
///
/// - Parameters:
/// - sortDescriptors: An array of sort descriptors that define the sort
/// order of the fetched results.
/// - predicate: An
/// <doc://com.apple.documentation/documentation/Foundation/NSPredicate>
/// instance that defines logical conditions used to filter the fetched
/// results.
/// - animation: The animation to use for user interface changes that
/// result from changes to the fetched results.
@MainActor public init(sortDescriptors: [SortDescriptor<Result>], predicate: NSPredicate? = nil, animation: Animation? = nil)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension FetchRequest.Configuration where Result : NSManagedObject {
/// The request's sort descriptors, accessed as value types.
///
/// Set this configuration value to cause a ``FetchRequest`` to execute a
/// fetch with a new collection of
/// <doc://com.apple.documentation/documentation/Foundation/SortDescriptor>
/// instances. If you want to use
/// <doc://com.apple.documentation/documentation/Foundation/NSSortDescriptor>
/// instances, set ``FetchRequest/Configuration/nsSortDescriptors`` instead.
///
/// Access this value of a ``FetchRequest/Configuration`` structure for
/// a given request by using the ``FetchedResults/sortDescriptors``
/// property on the associated ``FetchedResults`` instance, either
/// directly or through a ``Binding``.
public var sortDescriptors: [SortDescriptor<Result>]
}
/// A collection of results retrieved from a Core Data store.
///
/// 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
/// <doc://com.apple.documentation/documentation/CoreData/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)])
/// private var quakes: FetchedResults<Quake>
///
/// The results instance conforms to
/// <doc://com.apple.documentation/documentation/Swift/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
/// ``EnvironmentValues/managedObjectContext`` environment value. To
/// support user interface activity, you typically rely on the
/// <doc://com.apple.documentation/documentation/CoreData/NSPersistentContainer/1640622-viewContext>
/// property of a shared
/// <doc://com.apple.documentation/documentation/CoreData/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)
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct FetchedResults<Result> : RandomAccessCollection where Result : NSFetchRequestResult {
/// The request's sort descriptors, accessed as reference types.
///
/// Set this value to cause the associated ``FetchRequest`` to execute
/// a fetch with a new collection of
/// <doc://com.apple.documentation/documentation/Foundation/NSSortDescriptor>
/// instances.
/// The order of managed objects stored in the results collection may change
/// as a result.
///
/// If you want to use
/// <doc://com.apple.documentation/documentation/Foundation/SortDescriptor>
/// instances, set ``FetchedResults/sortDescriptors`` instead.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public var nsSortDescriptors: [NSSortDescriptor] { get nonmutating set }
/// The request's predicate.
///
/// Set this value to cause the associated ``FetchRequest`` to execute a
/// fetch with a new predicate, producing an updated collection of results.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public var nsPredicate: NSPredicate? { get nonmutating set }
/// The index of the first entity in the results collection.
public var startIndex: Int { get }
/// The index that's one greater than the last valid subscript argument.
public var endIndex: Int { get }
/// Gets the entity at the specified index.
public subscript(position: Int) -> Result { get }
/// A type representing the sequence's elements.
public typealias Element = Result
/// A type that represents a position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript
/// argument.
public typealias Index = Int
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
public typealias Indices = Range<Int>
/// A type that provides the collection's iteration interface and
/// encapsulates its iteration state.
///
/// By default, a collection conforms to the `Sequence` protocol by
/// supplying `IndexingIterator` as its associated `Iterator`
/// type.
public typealias Iterator = IndexingIterator<FetchedResults<Result>>
/// A collection representing a contiguous subrange of this collection's
/// elements. The subsequence shares indices with the original collection.
///
/// The default subsequence type for collections that don't define their own
/// is `Slice`.
public typealias SubSequence = Slice<FetchedResults<Result>>
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension FetchedResults where Result : NSManagedObject {
/// The request's sort descriptors, accessed as value types.
///
/// Set this value to cause the associated ``FetchRequest`` to execute a
/// fetch with a new collection of
/// <doc://com.apple.documentation/documentation/Foundation/SortDescriptor>
/// instances.
/// The order of entities stored in the results collection may change
/// as a result.
///
/// If you want to use
/// <doc://com.apple.documentation/documentation/Foundation/NSSortDescriptor>
/// instances, set ``FetchedResults/nsSortDescriptors`` instead.
public var sortDescriptors: [SortDescriptor<Result>] { get nonmutating set }
}
/// A date picker style that displays the components in an editable field.
///
/// You can also use ``DatePickerStyle/field`` to construct this style.
@available(macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct FieldDatePickerStyle : DatePickerStyle {
/// Creates an instance of the field date picker style.
public init()
/// Returns the appearance and interaction content for a `DatePicker`.
///
/// The system calls this method for each ``DatePicker`` instance in a view
/// hierarchy where this style is the current date picker style.
///
/// - Parameter configuration : The properties of the date picker.
@available(macOS 13.0, *)
public func makeBody(configuration: FieldDatePickerStyle.Configuration) -> some View
/// A view representing the appearance and interaction of a `DatePicker`.
public typealias Body = some View
}
/// The way that file dialogs present the file system.
///
/// Apply the options using the ``View/fileDialogBrowserOptions(_:)`` modifier.
@available(iOS 17.0, macOS 14.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct FileDialogBrowserOptions : OptionSet {
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public let rawValue: Int
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
public init(rawValue: Int)
/// Allows enumerating packages contents in contrast to the default behavior
/// when packages are represented flatly, similar to files.
public static let enumeratePackages: FileDialogBrowserOptions
/// Displays the files that are hidden by default.
public static let includeHiddenFiles: 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.
public static let displayFileExtensions: FileDialogBrowserOptions
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = FileDialogBrowserOptions
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = FileDialogBrowserOptions
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = Int
}
@available(iOS 17.0, macOS 14.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension FileDialogBrowserOptions : Sendable {
}
/// A type that you use to serialize documents to and from file.
///
/// 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 define ``writableContentTypes-2opfc``.
/// * Loads documents from file in the ``init(configuration:)`` initializer.
/// * Stores documents to file by serializing their content in the
/// ``fileWrapper(configuration:)`` method.
///
/// > Important: If you store your document as a reference type --- like a
/// class --- use ``ReferenceFileDocument`` instead.
///
/// Ensure that types that conform to this protocol are thread-safe.
/// In particular, SwiftUI calls the protocol's methods on a background
/// thread. Don't use that thread to perform user interface updates.
/// Use it only to serialize and deserialize the document data.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public protocol FileDocument {
/// The file and data types that the document reads from.
///
/// Define this list to indicate the content types that your document can
/// read. By default, SwiftUI assumes that your document can also write
/// the same set of content types. If you need to indicate a different set
/// of types for writing files, define the ``writableContentTypes-2opfc``
/// property in addition to this property.
static var readableContentTypes: [UTType] { get }
/// The file types that the document supports saving or exporting to.
///
/// By default, SwiftUI assumes that your document reads and writes the
/// same set of content types. Only define this property if you need to
/// indicate a different set of types for writing files. Otherwise, the
/// default implementation of this property returns the list that you
/// specify in your implementation of ``readableContentTypes``.
static var writableContentTypes: [UTType] { get }
/// Creates a document and initializes it with the contents of a file.
///
/// SwiftUI calls this initializer when someone opens a file type
/// that matches one of those that your document type supports.
/// Use the ``FileDocumentReadConfiguration/file`` property of the
/// `configuration` input to get document's data. Deserialize the data,
/// and store it in your document's data structure:
///
/// init(configuration: ReadConfiguration) throws {
/// guard let data = configuration.file.regularFileContents
/// else { /* Throw an error. */ }
/// model = try JSONDecoder().decode(Model.self, from: data)
/// }
///
/// The above example assumes that you define `Model` to contain
/// the document's data, that `Model` conforms to the
/// <doc://com.apple.documentation/documentation/Swift/Codable> protocol,
/// and that you store a `model` property of that type inside your document.
///
/// > Note: SwiftUI calls this method on a background thread. Don't
/// make user interface changes from that thread.
///
/// - Parameter configuration: Information about the file that you read
/// document data from.
init(configuration: Self.ReadConfiguration) throws
/// The configuration for reading document contents.
///
/// This type is an alias for ``FileDocumentReadConfiguration``, which
/// contains a content type and a file wrapper that you use to access the
/// contents of a document file. You get a value of this type as an input
/// to the ``init(configuration:)`` initializer. Use it to load a
/// document from a file.
typealias ReadConfiguration = FileDocumentReadConfiguration
/// Serializes a document snapshot to a file wrapper.
///
/// To store a document --- for example, in response to a Save command ---
/// SwiftUI calls this method. Use it to serialize the document's data and
/// create or modify a file wrapper with the serialized data:
///
/// func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
/// let data = try JSONEncoder().encode(model)
/// return FileWrapper(regularFileWithContents: data)
/// }
///
/// > Note: SwiftUI calls this method on a background thread. Don't
/// make user interface changes from that thread.
///
/// - Parameters:
/// - configuration: Information about a file that already exists for the
/// document, if any.
///
/// - Returns: The destination to serialize the document contents to. The
/// value can be a newly created
/// <doc://com.apple.documentation/documentation/Foundation/FileWrapper>
/// or an update of the one provided in the `configuration` input.
func fileWrapper(configuration: Self.WriteConfiguration) throws -> FileWrapper
/// The configuration for writing document contents.
///
/// This type is an alias for ``FileDocumentWriteConfiguration``, which
/// contains a content type and a file wrapper that you use to access the
/// contents of a document file, if one already exists. You get a value
/// of this type as an input to the ``fileWrapper(configuration:)``
/// method.
typealias WriteConfiguration = FileDocumentWriteConfiguration
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension FileDocument {
/// The file types that the document supports saving or exporting to.
///
/// By default, SwiftUI assumes that your document reads and writes the
/// same set of content types. Only define this property if you need to
/// indicate a different set of types for writing files. Otherwise, the
/// default implementation of this property returns the list that you
/// specify in your implementation of ``readableContentTypes``.
public static var writableContentTypes: [UTType] { get }
}
/// The properties of an open file document.
///
/// 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.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct FileDocumentConfiguration<Document> where Document : FileDocument {
/// The current document model.
///
/// Setting a new value marks the document as having changes for later
/// saving and registers an undo action to restore the model to its
/// previous value.
///
/// If ``isEditable`` is `false`, setting a new value has no effect
/// because the document is in viewing mode.
@Binding public var document: Document { get nonmutating set }
public var $document: Binding<Document> { get }
/// The URL of the open file document.
public var fileURL: URL?
/// A Boolean that indicates whether you can edit the document.
///
/// This value is `false` if the document is in viewing mode, or if the
/// file is not writable.
public var isEditable: Bool
}
/// The configuration for reading file contents.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct FileDocumentReadConfiguration {
/// The expected uniform type of the file contents.
public let contentType: UTType
/// The file wrapper containing the document content.
public let file: FileWrapper
}
/// The configuration for serializing file contents.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct FileDocumentWriteConfiguration {
/// The expected uniform type of the file contents.
public let contentType: UTType
/// The file wrapper containing the current document content.
/// `nil` if the document is unsaved.
public let existingFile: FileWrapper?
}
/// A shape style that displays one of the overlay fills.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@frozen public struct FillShapeStyle : ShapeStyle {
/// An overlay fill style for filling shapes.
///
/// This shape style is appropriate for items situated on top of an existing
/// background color. It incorporates transparency to allow the background
/// color to show through.
///
/// Use the primary version of this style to fill thin or small shapes, such
/// as the track of a slider.
/// Use the secondary version of this style to fill medium-size shapes, such
/// as the background of a switch.
/// Use the tertiary version of this style to fill large shapes, such as
/// input fields, search bars, or buttons.
/// Use the quaternary version of this style to fill large areas that
/// contain complex content, such as an expanded table cell.
public init()
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
public typealias Resolved = Never
}
/// A shape provider that fills its shape.
///
/// You do not create this type directly, it is the return type of `Shape.fill`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@frozen public struct FillShapeView<Content, Style, Background> : ShapeView where Content : Shape, Style : ShapeStyle, Background : View {
/// The shape that this type draws and provides for other drawing
/// operations.
public var shape: Content
/// The style that fills this view's shape.
public var style: Style
/// The fill style used when filling this view's shape.
public var fillStyle: FillStyle
/// The background shown beneath this view.
public var background: Background
/// Create a FillShapeView.
public init(shape: Content, style: Style, fillStyle: FillStyle, background: Background)
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A style for rasterizing vector shapes.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct FillStyle : Equatable {
/// A Boolean value that indicates whether to use the even-odd rule when
/// rendering a shape.
///
/// When `isOEFilled` is `false`, the style uses the non-zero winding number
/// rule.
public var isEOFilled: Bool
/// A Boolean value that indicates whether to apply antialiasing to the
/// edges of a shape.
public var isAntialiased: Bool
/// Creates a new fill style with the specified settings.
///
/// - Parameters:
/// - eoFill: A Boolean value that indicates whether to use the even-odd
/// rule for rendering a shape. Pass `false` to use the non-zero winding
/// number rule instead.
/// - antialiased: A Boolean value that indicates whether to use
/// antialiasing when rendering the edges of a shape.
@inlinable public init(eoFill: Bool = false, antialiased: Bool = true)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: FillStyle, b: FillStyle) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension FillStyle : Sendable {
}
/// Values describe different focus interactions that a view can support.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct FocusInteractions : OptionSet, Sendable {
/// The view has a primary action that can be activated via focus gestures.
///
/// On macOS and iOS, focus-driven activation interactions are only possible
/// when all-controls keyboard navigation is enabled. On tvOS and watchOS,
/// focus-driven activation interactions are always possible.
public static let activate: FocusInteractions
/// The view captures input from non-spatial sources like a keyboard or
/// Digital Crown.
///
/// Views that support focus-driven editing interactions become focused when
/// the user taps or clicks on them, or when the user issues a focus
/// movement command.
public static let edit: FocusInteractions
/// The view supports whatever focus-driven interactions are commonly
/// expected for interactive content on the current platform.
public static var automatic: FocusInteractions { get }
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public var rawValue: Int
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
public init(rawValue: Int)
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = FocusInteractions
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = FocusInteractions
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = Int
}
/// A property wrapper type that can read and write a value that SwiftUI updates
/// as the placement of focus within the scene changes.
///
/// Use this property wrapper in conjunction with ``View/focused(_:equals:)``
/// and ``View/focused(_:)`` to
/// describe views whose appearance and contents relate to the location of
/// focus in the scene. When focus enters the modified view, the wrapped value
/// of this property updates to match a given prototype value. Similarly, when
/// focus leaves, the wrapped value of this property resets to `nil`
/// or `false`. Setting the property's value programmatically has the reverse
/// effect, causing focus to move to the view associated with the
/// updated value.
///
/// In the following example of a simple login screen, when the user presses the
/// Sign In button and one of the fields is still empty, focus moves to that
/// field. Otherwise, the sign-in process proceeds.
///
/// struct LoginForm {
/// enum Field: Hashable {
/// case username
/// case password
/// }
///
/// @State private var username = ""
/// @State private var password = ""
/// @FocusState private var focusedField: Field?
///
/// var body: some View {
/// Form {
/// TextField("Username", text: $username)
/// .focused($focusedField, equals: .username)
///
/// SecureField("Password", text: $password)
/// .focused($focusedField, equals: .password)
///
/// Button("Sign In") {
/// if username.isEmpty {
/// focusedField = .username
/// } else if password.isEmpty {
/// focusedField = .password
/// } else {
/// handleLogin(username, password)
/// }
/// }
/// }
/// }
/// }
///
/// To allow for cases where focus is completely absent from a view tree, the
/// wrapped value must be either an optional or a Boolean. Set the focus binding
/// to `false` or `nil` as appropriate to remove focus from all bound fields.
/// You can also use this to remove focus from a ``TextField`` and thereby
/// dismiss the keyboard.
///
/// ### Avoid ambiguous focus bindings
///
/// The same view can have multiple focus bindings. In the following example,
/// setting `focusedField` to either `name` or `fullName` causes the field
/// to receive focus:
///
/// struct ContentView: View {
/// enum Field: Hashable {
/// case name
/// case fullName
/// }
/// @FocusState private var focusedField: Field?
///
/// var body: some View {
/// TextField("Full Name", ...)
/// .focused($focusedField, equals: .name)
/// .focused($focusedField, equals: .fullName)
/// }
/// }
///
/// On the other hand, binding the same value to two views is ambiguous. In
/// the following example, two separate fields bind focus to the `name` value:
///
/// struct ContentView: View {
/// enum Field: Hashable {
/// case name
/// case fullName
/// }
/// @FocusState private var focusedField: Field?
///
/// var body: some View {
/// TextField("Name", ...)
/// .focused($focusedField, equals: .name)
/// TextField("Full Name", ...)
/// .focused($focusedField, equals: .name) // incorrect re-use of .name
/// }
/// }
///
/// If the user moves focus to either field, the `focusedField` binding updates
/// to `name`. However, if the app programmatically sets the value to `name`,
/// SwiftUI chooses the first candidate, which in this case is the "Name"
/// field. SwiftUI also emits a runtime warning in this case, since the repeated
/// binding is likely a programmer error.
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen @propertyWrapper public struct FocusState<Value> : DynamicProperty where Value : Hashable {
/// A property wrapper type that can read and write a value that indicates
/// the current focus location.
@frozen @propertyWrapper public struct Binding {
/// The underlying value referenced by the bound property.
public var wrappedValue: Value { get nonmutating set }
/// A projection of the binding value that returns a binding.
///
/// Use the projected value to pass a binding value down a view
/// hierarchy.
public var projectedValue: FocusState<Value>.Binding { get }
}
/// The current state value, taking into account whatever bindings might be
/// in effect due to the current location of focus.
///
/// When focus is not in any view that is bound to this state, the wrapped
/// value will be `nil` (for optional-typed state) or `false` (for `Bool`-
/// typed state).
public var wrappedValue: Value { get nonmutating set }
/// A projection of the focus state value that returns a binding.
///
/// When focus is outside any view that is bound to this state, the wrapped
/// value is `nil` for optional-typed state or `false` for Boolean state.
///
/// In the following example of a simple navigation sidebar, when the user
/// presses the Filter Sidebar Contents button, focus moves to the sidebar's
/// filter text field. Conversely, if the user moves focus to the sidebar's
/// filter manually, then the value of `isFiltering` automatically
/// becomes `true`, and the sidebar view updates.
///
/// struct Sidebar: View {
/// @State private var filterText = ""
/// @FocusState private var isFiltering: Bool
///
/// var body: some View {
/// VStack {
/// Button("Filter Sidebar Contents") {
/// isFiltering = true
/// }
///
/// TextField("Filter", text: $filterText)
/// .focused($isFiltering)
/// }
/// }
/// }
public var projectedValue: FocusState<Value>.Binding { get }
/// Creates a focus state that binds to a Boolean.
public init() where Value == Bool
/// Creates a focus state that binds to an optional type.
public init<T>() where Value == T?, T : Hashable
}
/// A convenience property wrapper for observing and automatically unwrapping
/// state bindings from the focused view or one of its ancestors.
///
/// If multiple views publish bindings using the same key, the wrapped property
/// will reflect the value of the binding from the view closest to focus.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@propertyWrapper public struct FocusedBinding<Value> : DynamicProperty {
/// A new property wrapper for the given key path.
///
/// The value of the property wrapper is updated dynamically as focus
/// changes and different published bindings go in and out of scope.
///
/// - Parameter keyPath: The key path for the focus value to read.
public init(_ keyPath: KeyPath<FocusedValues, Binding<Value>?>)
/// The unwrapped value for the focus key given the current scope and state
/// of the focused view hierarchy.
@inlinable public var wrappedValue: Value? { get nonmutating set }
/// A binding to the optional value.
///
/// The unwrapped value is `nil` when no focused view hierarchy has
/// published a corresponding binding.
public var projectedValue: Binding<Value?> { get }
}
/// A property wrapper type for an observable object supplied by the focused
/// view or one of its ancestors.
///
/// Focused objects invalidate the current view whenever the observable object
/// changes. If multiple views publish a focused object using the same key, the
/// wrapped property will reflect the object that's closest to the focused view.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@frozen @propertyWrapper public struct FocusedObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject {
/// A wrapper around the underlying focused object that can create bindings
/// to its properties using dynamic member lookup.
@dynamicMemberLookup @frozen public struct Wrapper {
/// Returns a binding to the value of a given key path.
///
/// - Parameter keyPath: A key path to a specific value on the
/// wrapped object.
/// - Returns: A new binding.
public subscript<T>(dynamicMember keyPath: ReferenceWritableKeyPath<ObjectType, T>) -> Binding<T> { get }
}
/// The underlying value referenced by the focused object.
///
/// This property provides primary access to the value's data. However, you
/// don't access `wrappedValue` directly. Instead, you use the property
/// variable created with the ``FocusedObject`` attribute.
///
/// When a mutable value changes, the new value is immediately available.
/// However, a view displaying the value is updated asynchronously and may
/// not show the new value immediately.
@MainActor @inlinable public var wrappedValue: ObjectType? { get }
/// A projection of the focused object that creates bindings to its
/// properties using dynamic member lookup.
///
/// Use the projected value to pass a focused object down a view hierarchy.
@MainActor public var projectedValue: FocusedObject<ObjectType>.Wrapper? { get }
/// Creates a focused object.
public init()
}
/// A property wrapper for observing values from the focused view or one of its
/// ancestors.
///
/// If multiple views publish values using the same key, the wrapped property
/// will reflect the value from the view closest to focus.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@propertyWrapper public struct FocusedValue<Value> : DynamicProperty {
/// A new property wrapper for the given key path.
///
/// The value of the property wrapper is updated dynamically as focus
/// changes and different published values go in and out of scope.
///
/// - Parameter keyPath: The key path for the focus value to read.
public init(_ keyPath: KeyPath<FocusedValues, Value?>)
/// The value for the focus key given the current scope and state of the
/// focused view hierarchy.
///
/// Returns `nil` when nothing in the focused view hierarchy exports a
/// value.
@inlinable public var wrappedValue: Value? { get }
}
extension FocusedValue {
/// A new property wrapper for the given object type.
///
/// Reads the focused value of the given object type.
///
/// - Important: This initializer only accepts objects conforming to the
/// `Observable` protocol. For reading environment objects that conform to
/// `ObservableObject`, use `FocusedObject`, instead.
///
/// To set the focused value that is read by this, use the `focusedValue(_:)` view modifier.
///
/// - Parameter objectType: The type of object to read the focus value for.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public init(_ objectType: Value.Type) where Value : AnyObject, Value : Observable
}
/// A protocol for identifier types used when publishing and observing focused
/// values.
///
/// Unlike ``EnvironmentKey``, `FocusedValueKey` has no default value
/// requirement, because the default value for a key is always `nil`.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public protocol FocusedValueKey {
associatedtype Value
}
/// A collection of state exported by the focused view and its ancestors.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct FocusedValues {
/// Reads and writes values associated with a given focused value key.
public subscript<Key>(key: Key.Type) -> Key.Value? where Key : FocusedValueKey
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension FocusedValues : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: FocusedValues, rhs: FocusedValues) -> Bool
}
/// An environment-dependent font.
///
/// The system resolves a font's value at the time it uses the font in a given
/// environment because ``Font`` is a late-binding token.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Font : Hashable, Sendable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Font, rhs: Font) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font {
/// Specifies a system font to use, along with the style, weight, and any
/// design parameters you want applied to the text.
///
/// Use this function to create a system font by specifying the size and
/// weight, and a type design together. The following styles the system font
/// as 17 point, ``Font/Weight/semibold`` text:
///
/// Text("Hello").font(.system(size: 17, weight: .semibold))
///
/// While the following styles the text as 17 point ``Font/Weight/bold``,
/// and applies a `serif` ``Font/Design`` to the system font:
///
/// Text("Hello").font(.system(size: 17, weight: .bold, design: .serif))
///
/// Both `weight` and `design` can be optional. When you do not provide a
/// `weight` or `design`, the system can pick one based on the current
/// context, which may not be ``Font/Weight/regular`` or
/// ``Font/Design/default`` in certain context. The following example styles
/// the text as 17 point system font using ``Font/Design/rounded`` design,
/// while its weight can depend on the current context:
///
/// Text("Hello").font(.system(size: 17, design: .rounded))
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public static func system(size: CGFloat, weight: Font.Weight? = nil, design: Font.Design? = nil) -> Font
/// Specifies a system font to use, along with the style, weight, and any
/// design parameters you want applied to the text.
///
/// Use this function to create a system font by specifying the size and
/// weight, and a type design together. The following styles the system font
/// as 17 point, ``Font/Weight/semibold`` text:
///
/// Text("Hello").font(.system(size: 17, weight: .semibold))
///
/// While the following styles the text as 17 point ``Font/Weight/bold``,
/// and applies a `serif` ``Font/Design`` to the system font:
///
/// Text("Hello").font(.system(size: 17, weight: .bold, design: .serif))
///
/// If you want to use the default ``Font/Weight``
/// (``Font/Weight/regular``), you don't need to specify the `weight` in the
/// method. The following example styles the text as 17 point
/// ``Font/Weight/regular``, and uses a ``Font/Design/rounded`` system font:
///
/// Text("Hello").font(.system(size: 17, design: .rounded))
///
/// This function has been deprecated, use the one with nullable `weight`
/// and `design` instead.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
public static func system(size: CGFloat, weight: Font.Weight = .regular, design: Font.Design = .default) -> Font
/// A design to use for fonts.
public enum Design : Hashable, Sendable {
case `default`
@available(watchOS 7.0, *)
case serif
case rounded
@available(watchOS 7.0, *)
case monospaced
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.Design, b: Font.Design) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font {
/// A font with the large title text style.
public static let largeTitle: Font
/// A font with the title text style.
public static let title: Font
/// Create a font for second level hierarchical headings.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static let title2: Font
/// Create a font for third level hierarchical headings.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static let title3: Font
/// A font with the headline text style.
public static let headline: Font
/// A font with the subheadline text style.
public static let subheadline: Font
/// A font with the body text style.
public static let body: Font
/// A font with the callout text style.
public static let callout: Font
/// A font with the footnote text style.
public static let footnote: Font
/// A font with the caption text style.
public static let caption: Font
/// Create a font with the alternate caption text style.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static let caption2: Font
/// Gets a system font that uses the specified style, design, and weight.
///
/// Use this method to create a system font that has the specified
/// properties. The following example creates a system font with the
/// ``TextStyle/body`` text style, a ``Design/serif`` design, and
/// a ``Weight/bold`` weight, and applies the font to a ``Text`` view
/// using the ``View/font(_:)`` view modifier:
///
/// Text("Hello").font(.system(.body, design: .serif, weight: .bold))
///
/// The `design` and `weight` parameters are both optional. If you omit
/// either, the system uses a default value for that parameter. The
/// default values are typically ``Design/default`` and ``Weight/regular``,
/// respectively, but might vary depending on the context.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public static func system(_ style: Font.TextStyle, design: Font.Design? = nil, weight: Font.Weight? = nil) -> Font
/// Gets a system font with the given text style and design.
///
/// This function has been deprecated, use the one with nullable `design`
/// and `weight` instead.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
public static func system(_ style: Font.TextStyle, design: Font.Design = .default) -> Font
/// A dynamic text style to use for fonts.
public enum TextStyle : CaseIterable, Sendable {
/// The font style for large titles.
case largeTitle
/// The font used for first level hierarchical headings.
case title
/// The font used for second level hierarchical headings.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
case title2
/// The font used for third level hierarchical headings.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
case title3
/// The font used for headings.
case headline
/// The font used for subheadings.
case subheadline
/// The font used for body text.
case body
/// The font used for callouts.
case callout
/// The font used in footnotes.
case footnote
/// The font used for standard captions.
case caption
/// The font used for alternate captions.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
case caption2
/// A collection of all values of this type.
public static var allCases: [Font.TextStyle]
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.TextStyle, b: Font.TextStyle) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [Font.TextStyle]
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font {
/// Adds italics to the font.
public func italic() -> Font
/// Adjusts the font to enable all small capitals.
///
/// See ``Font/lowercaseSmallCaps()`` and ``Font/uppercaseSmallCaps()`` for
/// more details.
public func smallCaps() -> Font
/// Adjusts the font to enable lowercase small capitals.
///
/// This function turns lowercase characters into small capitals for the
/// font. It is generally used for display lines set in large and small
/// caps, such as titles. It may include forms related to small capitals,
/// such as old-style figures.
public func lowercaseSmallCaps() -> Font
/// Adjusts the font to enable uppercase small capitals.
///
/// This feature turns capital characters into small capitals. It is
/// generally used for words which would otherwise be set in all caps, such
/// as acronyms, but which are desired in small-cap form to avoid disrupting
/// the flow of text.
public func uppercaseSmallCaps() -> Font
/// Returns a modified font that uses fixed-width digits, while leaving
/// other characters proportionally spaced.
///
/// This modifier only affects numeric characters, and leaves all other
/// characters unchanged. If the base font doesn't support fixed-width,
/// or _monospace_ digits, the font remains unchanged.
///
/// The following example shows two text fields arranged in a ``VStack``.
/// Both text fields specify the 12-point system font, with the second
/// adding the `monospacedDigit()` modifier to the font. Because the text
/// includes the digit 1, normally a narrow character in proportional
/// fonts, the second text field becomes wider than the first.
///
/// @State private var userText = "Effect of monospacing digits: 111,111."
///
/// var body: some View {
/// VStack {
/// TextField("Proportional", text: $userText)
/// .font(.system(size: 12))
/// TextField("Monospaced", text: $userText)
/// .font(.system(size: 12).monospacedDigit())
/// }
/// .padding()
/// .navigationTitle(Text("Font + monospacedDigit()"))
/// }
///
/// ![A macOS window showing two text fields arranged vertically. Each
/// shows the text Effect of monospacing digits: 111,111. The even spacing
/// of the digit 1 in the second text field causes it to be noticably wider
/// than the first.](Environment-Font-monospacedDigit-1)
///
/// - Returns: A font that uses fixed-width numeric characters.
public func monospacedDigit() -> Font
/// Sets the weight of the font.
public func weight(_ weight: Font.Weight) -> Font
/// Sets the width of the font.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public func width(_ width: Font.Width) -> Font
/// Adds bold styling to the font.
public func bold() -> Font
/// Returns a fixed-width font from the same family as the base font.
///
/// If there's no suitable font face in the same family, SwiftUI
/// returns a default fixed-width font.
///
/// The following example adds the `monospaced()` modifier to the default
/// system font, then applies this font to a ``Text`` view:
///
/// struct ContentView: View {
/// let myFont = Font
/// .system(size: 24)
/// .monospaced()
///
/// var body: some View {
/// Text("Hello, world!")
/// .font(myFont)
/// .padding()
/// .navigationTitle("Monospaced")
/// }
/// }
///
///
/// ![A macOS window showing the text Hello, world in a 24-point
/// fixed-width font.](Environment-Font-monospaced-1)
///
/// SwiftUI may provide different fixed-width replacements for standard
/// user interface fonts (such as ``Font/title``, or a system font created
/// with ``Font/system(_:design:)``) than for those same fonts when created
/// by name with ``Font/custom(_:size:)``.
///
/// The ``View/font(_:)`` modifier applies the font to all text within
/// the view. To mix fixed-width text with other styles in the same
/// `Text` view, use the ``Text/init(_:)-1a4oh`` initializer to use an
/// appropropriately-styled
/// <doc://com.apple.documentation/documentation/Foundation/AttributedString>
/// for the text view's content. You can use the
/// <doc://com.apple.documentation/documentation/Foundation/AttributedString/3796160-init>
/// initializer to provide a Markdown-formatted string containing the
/// backtick-syntax (\`…\`) to apply code voice to specific ranges
/// of the attributed string.
///
/// - Returns: A fixed-width font from the same family as the base font,
/// if one is available, and a default fixed-width font otherwise.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public func monospaced() -> Font
/// Adjusts the line spacing of a font.
///
/// You can change a font's line spacing while maintaining other
/// characteristics of the font by applying this modifier.
/// For example, you can decrease spacing of the ``body`` font by
/// applying the ``Leading/tight`` value to it:
///
/// let myFont = Font.body.leading(.tight)
///
/// The availability of leading adjustments depends on the font. For some
/// fonts, the modifier has no effect and returns the original font.
///
/// - Parameter leading: The line spacing adjustment to apply.
///
/// - Returns: A modified font that uses the specified line spacing, or
/// the original font if it doesn't support line spacing adjustments.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public func leading(_ leading: Font.Leading) -> Font
/// A weight to use for fonts.
@frozen public struct Weight : Hashable {
public static let ultraLight: Font.Weight
public static let thin: Font.Weight
public static let light: Font.Weight
public static let regular: Font.Weight
public static let medium: Font.Weight
public static let semibold: Font.Weight
public static let bold: Font.Weight
public static let heavy: Font.Weight
public static let black: Font.Weight
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.Weight, b: Font.Weight) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A width to use for fonts that have multiple widths.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct Width : Hashable, Sendable {
public var value: CGFloat
public static let compressed: Font.Width
public static let condensed: Font.Width
public static let standard: Font.Width
public static let expanded: Font.Width
public init(_ value: CGFloat)
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.Width, b: Font.Width) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A line spacing adjustment that you can apply to a font.
///
/// Apply one of the `Leading` values to a font using the
/// ``Font/leading(_:)`` method to increase or decrease the line spacing.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public enum Leading : Sendable {
/// The font's default line spacing.
///
/// If you modify a font to use a nonstandard line spacing like
/// ``tight`` or ``loose``, you can use this value to return to
/// the font's default line spacing.
case standard
/// Reduced line spacing.
///
/// This value typically reduces line spacing by 1 point for watchOS
/// and 2 points on other platforms.
case tight
/// Increased line spacing.
///
/// This value typically increases line spacing by 1 point for watchOS
/// and 2 points on other platforms.
case loose
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.Leading, b: Font.Leading) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font {
/// Create a custom font with the given `name` and `size` that scales with
/// the body text style.
public static func custom(_ name: String, size: CGFloat) -> Font
/// Create a custom font with the given `name` and `size` that scales
/// relative to the given `textStyle`.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static func custom(_ name: String, size: CGFloat, relativeTo textStyle: Font.TextStyle) -> Font
/// Create a custom font with the given `name` and a fixed `size` that does
/// not scale with Dynamic Type.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static func custom(_ name: String, fixedSize: CGFloat) -> Font
/// Creates a custom font from a platform font instance.
///
/// Initializing ``Font`` with platform font instance
/// (<doc://com.apple.documentation/documentation/CoreText/CTFont-q6r>) can bridge SwiftUI
/// ``Font`` with <doc://com.apple.documentation/documentation/AppKit/NSFont> or
/// <doc://com.apple.documentation/documentation/UIKit/UIFont>, both of which are
/// toll-free bridged to
/// <doc://com.apple.documentation/documentation/CoreText/CTFont-q6r>. For example:
///
/// // Use native Core Text API to create desired ctFont.
/// let ctFont = CTFontCreateUIFontForLanguage(.system, 12, nil)!
///
/// // Create SwiftUI Text with the CTFont instance.
/// let text = Text("Hello").font(Font(ctFont))
public init(_ font: CTFont)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font.TextStyle : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font.TextStyle : Hashable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font.Weight : Sendable {
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Font.Leading : Equatable {
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Font.Leading : Hashable {
}
/// A structure that computes views on demand from an underlying collection of
/// identified data.
///
/// Use `ForEach` to provide views based on a
/// <doc://com.apple.documentation/documentation/Swift/RandomAccessCollection>
/// of some data type. Either the collection's elements must conform to
/// <doc://com.apple.documentation/documentation/Swift/Identifiable> or you
/// need to provide an `id` parameter to the `ForEach` initializer.
///
/// The following example creates a `NamedFont` type that conforms to
/// <doc://com.apple.documentation/documentation/Swift/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)
/// }
/// }
///
/// ![A vertically arranged stack of labels showing various standard fonts,
/// such as Large Title and Headline.](SwiftUI-ForEach-fonts.png)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct ForEach<Data, ID, Content> where Data : RandomAccessCollection, ID : Hashable {
/// The collection of underlying identified data that SwiftUI uses to create
/// views dynamically.
public var data: Data
/// A function to create content on demand using the underlying data.
public var content: (Data.Element) -> Content
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ForEach {
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the identity of the underlying data.
///
/// It's important that the `id` of a data element doesn't change unless you
/// replace the data element with a new data element that has a new
/// identity. If the `id` of a data element changes, the content view
/// generated from that data element loses any current state and animations.
///
/// When placed inside a `List` the edit actions (like delete or move)
/// can be automatically synthesized by specifying an appropriate
/// `EditActions`.
///
/// The following example shows a list of recipes whose elements can be
/// deleted and reordered:
///
/// List {
/// ForEach($recipes, editActions: [.delete, .move]) { $recipe in
/// RecipeCell($recipe)
/// }
/// }
///
/// Use ``View/deleteDisabled(_:)`` and ``View/moveDisabled(_:)``
/// to disable respectively delete or move actions on a per-row basis.
///
/// The following example shows a list of recipes whose elements can be
/// deleted only if they satisfy a condition:
///
/// List {
/// ForEach($recipes, editActions: .delete) { $recipe in
/// RecipeCell($recipe)
/// .deleteDisabled(recipe.isFromMom)
/// }
/// }
///
/// Explicit ``DynamicViewContent.onDelete(perform:)``,
/// ``DynamicViewContent.onMove(perform:)``, or
/// ``View.swipeActions(edge:allowsFullSwipe:content:)``
/// modifiers will override any synthesized actions.
/// Use this modifier if you need fine-grain control on how mutations are
/// applied to the data driving the `ForEach`. For example, if you need to
/// execute side effects or call into your existing model code.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create views dynamically and can be edited by the user.
/// - editActions: The edit actions that are synthesized on `data`.
/// - content: The view builder that creates views dynamically.
public init<C, R>(_ data: Binding<C>, editActions: EditActions<C>, @ViewBuilder content: @escaping (Binding<C.Element>) -> R) where Data == IndexedIdentifierCollection<C, ID>, ID == C.Element.ID, Content == EditableCollectionContent<R, C>, C : MutableCollection, C : RandomAccessCollection, R : View, C.Element : Identifiable, C.Index : Hashable
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the identity of the underlying data.
///
/// It's important that the `id` of a data element doesn't change unless you
/// replace the data element with a new data element that has a new
/// identity. If the `id` of a data element changes, the content view
/// generated from that data element loses any current state and animations.
///
/// When placed inside a `List` the edit actions (like delete or move)
/// can be automatically synthesized by specifying an appropriate
/// `EditActions`.
///
/// The following example shows a list of recipes whose elements can be
/// deleted and reordered:
///
/// List {
/// ForEach($recipes, editActions: [.delete, .move]) { $recipe in
/// RecipeCell($recipe)
/// }
/// }
///
/// Use ``View/deleteDisabled(_:)`` and ``View/moveDisabled(_:)``
/// to disable respectively delete or move actions on a per-row basis.
///
/// The following example shows a list of recipes whose elements can be
/// deleted only if they satisfy a condition:
///
/// List {
/// ForEach($recipes, editActions: .delete) { $recipe in
/// RecipeCell($recipe)
/// .deleteDisabled(recipe.isFromMom)
/// }
/// }
///
/// Explicit ``DynamicViewContent.onDelete(perform:)``,
/// ``DynamicViewContent.onMove(perform:)``, or
/// ``View.swipeActions(edge:allowsFullSwipe:content:)``
/// modifiers will override any synthesized actions.
/// Use this modifier if you need fine-grain control on how mutations are
/// applied to the data driving the `ForEach`. For example, if you need to
/// execute side effects or call into your existing model code.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create views dynamically and can be edited by the user.
/// - id: The key path to the provided data's identifier.
/// - editActions: The edit actions that are synthesized on `data`.
/// - content: The view builder that creates views dynamically.
public init<C, R>(_ data: Binding<C>, id: KeyPath<C.Element, ID>, editActions: EditActions<C>, @ViewBuilder content: @escaping (Binding<C.Element>) -> R) where Data == IndexedIdentifierCollection<C, ID>, Content == EditableCollectionContent<R, C>, C : MutableCollection, C : RandomAccessCollection, R : View, C.Index : Hashable
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach : DynamicViewContent where Content : View {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ForEach : AccessibilityRotorContent where Content : AccessibilityRotorContent {
/// The internal content of this `AccessibilityRotorContent`.
public var body: Never { get }
/// The type for the internal content of this `AccessibilityRotorContent`.
public typealias Body = Never
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ForEach where ID == Data.Element.ID, Content : AccessibilityRotorContent, Data.Element : Identifiable {
/// Creates an instance that generates Rotor content by combining, in order,
/// individual Rotor content for each element in the data given to this
/// `ForEach`.
///
/// It's important that the `id` of a data element doesn't change unless you
/// replace the data element with a new data element that has a new
/// identity.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create views dynamically.
/// - content: The result builder that generates Rotor content for each
/// data element.
public init(_ data: Data, @AccessibilityRotorContentBuilder content: @escaping (Data.Element) -> Content)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ForEach where Content : AccessibilityRotorContent {
/// Creates an instance that generates Rotor content by combining, in order,
/// individual Rotor content for each element in the data given to this
/// `ForEach`.
///
/// It's important that the `id` of a data element doesn't change, unless
/// SwiftUI considers the data element to have been replaced with a new data
/// element that has a new identity.
///
/// - Parameters:
/// - data: The data that the ``ForEach`` instance uses to create views
/// dynamically.
/// - id: The key path to the provided data's identifier.
/// - content: The result builder that generates Rotor content for each
/// data element.
public init(_ data: Data, id: KeyPath<Data.Element, ID>, @AccessibilityRotorContentBuilder content: @escaping (Data.Element) -> Content)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach : View where Content : View {
public typealias Body = Never
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where ID == Data.Element.ID, Content : View, Data.Element : Identifiable {
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the identity of the underlying data.
///
/// It's important that the `id` of a data element doesn't change unless you
/// replace the data element with a new data element that has a new
/// identity. If the `id` of a data element changes, the content view
/// generated from that data element loses any current state and animations.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create views dynamically.
/// - content: The view builder that creates views dynamically.
public init(_ data: Data, @ViewBuilder content: @escaping (Data.Element) -> Content)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where Content : View {
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the provided key path to the underlying data's
/// identifier.
///
/// It's important that the `id` of a data element doesn't change, unless
/// SwiftUI considers the data element to have been replaced with a new data
/// element that has a new identity. If the `id` of a data element changes,
/// then the content view generated from that data element will lose any
/// current state and animations.
///
/// - Parameters:
/// - data: The data that the ``ForEach`` instance uses to create views
/// dynamically.
/// - id: The key path to the provided data's identifier.
/// - content: The view builder that creates views dynamically.
public init(_ data: Data, id: KeyPath<Data.Element, ID>, @ViewBuilder content: @escaping (Data.Element) -> Content)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where Content : View {
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the identity of the underlying data.
///
/// It's important that the `id` of a data element doesn't change unless you
/// replace the data element with a new data element that has a new
/// identity. If the `id` of a data element changes, the content view
/// generated from that data element loses any current state and animations.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create views dynamically.
/// - content: The view builder that creates views dynamically.
public init<C>(_ data: Binding<C>, @ViewBuilder content: @escaping (Binding<C.Element>) -> Content) where Data == LazyMapSequence<C.Indices, (C.Index, ID)>, ID == C.Element.ID, C : MutableCollection, C : RandomAccessCollection, C.Element : Identifiable, C.Index : Hashable
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the identity of the underlying data.
///
/// It's important that the `id` of a data element doesn't change unless you
/// replace the data element with a new data element that has a new
/// identity. If the `id` of a data element changes, the content view
/// generated from that data element loses any current state and animations.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create views dynamically.
/// - id: The key path to the provided data's identifier.
/// - content: The view builder that creates views dynamically.
public init<C>(_ data: Binding<C>, id: KeyPath<C.Element, ID>, @ViewBuilder content: @escaping (Binding<C.Element>) -> Content) where Data == LazyMapSequence<C.Indices, (C.Index, ID)>, C : MutableCollection, C : RandomAccessCollection, C.Index : Hashable
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where Data == Range<Int>, ID == Int, Content : View {
/// Creates an instance that computes views on demand over a given constant
/// range.
///
/// The instance only reads the initial value of the provided `data` and
/// doesn't need to identify views across updates. To compute views on
/// demand over a dynamic range, use ``ForEach/init(_:id:content:)``.
///
/// - Parameters:
/// - data: A constant range.
/// - content: The view builder that creates views dynamically.
public init(_ data: Range<Int>, @ViewBuilder content: @escaping (Int) -> Content)
}
@available(iOS 16.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ForEach : TableRowContent where Content : TableRowContent {
/// The type of value represented by this table row content.
public typealias TableRowValue = Content.TableRowValue
/// The type of content representing the body of this table row content.
public typealias TableRowBody = Never
/// Creates an instance that uniquely identifies and creates table rows
/// across updates based on the identity of the underlying data.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create table rows dynamically.
/// - content: The table row builder that creates rows dynamically.
public init<V>(_ data: Data, @TableRowBuilder<V> content: @escaping (Data.Element) -> Content) where ID == Data.Element.ID, V == Content.TableRowValue, Data.Element : Identifiable
/// Creates an instance that uniquely identifies and creates table rows
/// across updates based on the provided key path to the underlying data's
/// identifier.
///
/// - Parameters:
/// - data: The data that the ``ForEach`` instance uses to create table
/// rows dynamically.
/// - id: The key path to the provided data's identifier.
/// - content: The table row builder that creates rows dynamically.
public init<V>(_ data: Data, id: KeyPath<Data.Element, ID>, @TableRowBuilder<V> content: @escaping (Data.Element) -> Content) where V == Content.TableRowValue
/// Creates an instance that uniquely identifies and creates table rows
/// across updates based on the identity of the underlying data.
///
/// The following example creates a `Person` type that conforms to
/// <doc://com.apple.documentation/documentation/Swift/Identifiable>, and an
/// array of this type called `people`. A `ForEach` instance iterates over
/// the array, producing new ``TableRow`` instances implicitly.
///
/// private struct Person: Identifiable {
/// var id = UUID()
/// var name: String
/// }
///
/// @State private var people: [Person] = /* ... */
///
/// Table(of: Person.self) {
/// TableColumn("ID", value: \.id.uuidString)
/// TableColumn("Name", value: \.name)
/// } rows: {
/// Section("Team") {
/// /* This is equivalent to the line below:
/// ForEach(people) { TableRow($0) }
/// */
/// ForEach(people)
/// }
/// }
///
/// - Parameter data: The identified data that the ``ForEach`` instance uses
/// to create table rows dynamically.
public init(_ data: Data) where ID == Data.Element.ID, Content == TableRow<Data.Element>, Data.Element : Identifiable
/// Creates an instance that computes table rows on demand over a given
/// constant range.
///
/// The instance only reads the initial value of the provided `data` and
/// doesn't need to identify rows across updates. To compute rows on
/// demand over a dynamic range, use ``ForEach/init(_:id:content:)``.
///
/// - Parameters:
/// - data: A constant range.
/// - content: The table row builder that creates rows dynamically.
public init<V>(_ data: Range<Int>, @TableRowBuilder<V> content: @escaping (Int) -> Content) where Data == Range<Int>, ID == Int, V == Content.TableRowValue
}
@available(iOS 16.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ForEach : DynamicTableRowContent where Content : TableRowContent {
}
/// The foreground style in the current context.
///
/// You can also use ``ShapeStyle/foreground`` to construct this style.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct ForegroundStyle : ShapeStyle {
/// Creates a foreground style instance.
@inlinable public init()
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
public typealias Resolved = Never
}
/// A container for grouping controls used for data entry, such as in settings
/// or inspectors.
///
/// 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") {}
/// }
/// }
/// }
/// }
///
///
/// ![A form on iOS, presented as a grouped list with two sections. The
/// first section is labeled Notifications and contains a navigation link with
/// the label Notify Me About and the current value Direct Messages. The section
/// also contains two toggles, Play Notification Sounds and Send Read Receipts,
/// the first of which is set to the on position. A second section named User
/// Profiles has a navigation link labeled Profile Image Size and the value
/// Medium, followed by a button labeled Clear Image
/// Cache.](SwiftUI-Form-iOS.png)
///
/// 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 ``PickerStyle/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()
/// }
///
/// ![A form on iOS, presented as a vertical stack of views. At top, it shows
/// a pop-up menu with the label label Notify Me about and the current value
/// Direct Messages. Below this are two checkboxes, labeled Play Notification
/// Sounds and Send Read Receipts, the first of which is set on. Below this
/// is the label Profile Image Size with three radio buttons -- Large, Medium,
/// and Small -- with Medium currently selected. At the bottom of the form,
/// there is a button titled Clear Image Cache.](SwiftUI-Form-macOS.png)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct Form<Content> : View where Content : View {
/// Creates a form with the provided content.
/// - Parameter content: A ``SwiftUI/ViewBuilder`` that provides the content for the
/// form.
public init(@ViewBuilder content: () -> Content)
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Form where Content == FormStyleConfiguration.Content {
/// Creates a form based on a form style configuration.
///
/// - Parameter configuration: The properties of the form.
public init(_ configuration: FormStyleConfiguration)
}
/// The appearance and behavior of a form.
///
/// To configure the style for a single ``Form`` or for all form instances
/// in a view hierarchy, use the ``View/formStyle(_:)`` modifier.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public protocol FormStyle {
/// A view that represents the appearance and interaction of a form.
associatedtype Body : View
/// Creates a view that represents the body of a form.
///
/// - Parameter configuration: The properties of the form.
/// - Returns: A view that has behavior and appearance that enables it
/// to function as a ``Form``.
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a form instance.
///
/// You receive a `configuration` parameter of this type --- which is an
/// alias for the ``FormStyleConfiguration`` type --- when you implement
/// the required ``makeBody(configuration:)`` method in a custom form
/// style implementation.
typealias Configuration = FormStyleConfiguration
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension FormStyle where Self == ColumnsFormStyle {
/// A non-scrolling form style with a trailing aligned column of labels
/// next to a leading aligned column of values.
public static var columns: ColumnsFormStyle { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension FormStyle where Self == GroupedFormStyle {
/// A form style with grouped rows.
///
/// Rows in a grouped rows form have leading aligned labels and trailing
/// aligned controls within visually grouped sections.
public static var grouped: GroupedFormStyle { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension FormStyle where Self == AutomaticFormStyle {
/// The default form style.
public static var automatic: AutomaticFormStyle { get }
}
/// The properties of a form instance.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct FormStyleConfiguration {
/// A type-erased content of a form.
public struct Content : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A view that is the content of the form.
public let content: FormStyleConfiguration.Content
}
/// A view that shows a value within a range.
///
/// 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")
/// }
/// }
/// }
///
/// ![A linear gauge displaying a current value set to 40 percent in a range of 0
/// to 1.](SwiftUI-Gauge-ValueLabelLinear.png)
///
/// 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))")
/// }
/// }
/// }
///
/// ![A linear gauge describing heart-rate in beats per minute with its
/// value set to 67 in a range of 0 to
/// 170.](SwiftUI-Gauge-Label-CurrentValueLinear.png)
///
/// 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.
///
/// > Note: Some visual presentations of `Gauge` don't display all the
/// labels required by the API. However, the accessibility system does use
/// the label content and you should use these labels to fully describe
/// the gauge for accessibility users.
///
/// To change the style of a gauge, use the ``View/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
/// ``GaugeStyle/circular`` style to the view:
///
/// 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))")
/// }
/// .gaugeStyle(.circular)
/// }
/// }
///
/// ![A circular gauge describing heart rate in beats per minute with its
/// value set to 67 in a range of 0 to 170.](SwiftUI-Gauge-LabeledCircular.png)
///
/// 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)
/// }
/// }
///
/// ![A circular gauge describing heart rate in beats per minute with its
/// value set to 67 on a range of 0 to 170. The style of each label is
/// individually set showing custom label
/// colors.](SwiftUI-Gauge-CircularStyled.png)
///
/// 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))
/// }
/// }
/// ![A screenshot showing a circular gauge with a gradient
/// tint.](SwiftUI-Gauge-Circular-Gradient.png)
///
@available(iOS 16.0, macOS 13.0, watchOS 7.0, *)
@available(tvOS, unavailable)
public struct Gauge<Label, CurrentValueLabel, BoundsLabel, MarkedValueLabels> : View where Label : View, CurrentValueLabel : View, BoundsLabel : View, MarkedValueLabels : View {
/// Creates a gauge showing a value within a range and describes the
/// gauge's purpose and current value.
///
/// Use this modifier to create a gauge that shows the value at its
/// relative position along the gauge and a label describing the gauge's
/// purpose. In the example below, the gauge has a range of `0...1`, the
/// indicator is set to `0.4`, or 40 percent of the distance along the
/// gauge:
///
/// struct SimpleGauge: View {
/// @State private var batteryLevel = 0.4
///
/// var body: some View {
/// Gauge(value: batteryLevel) {
/// Text("Battery Level")
/// }
/// }
/// }
///
/// ![A linear gauge that shows an indicator at 40 percent along the length
/// of the gauge.](SwiftUI-Gauge-ValueLabelLinear.png)
///
/// - Parameters:
/// - value: The value to show in the gauge.
/// - bounds: The range of the valid values. Defaults to `0...1`.
/// - label: A view that describes the purpose of the gauge.
public init<V>(value: V, in bounds: ClosedRange<V> = 0...1, @ViewBuilder label: () -> Label) where CurrentValueLabel == EmptyView, BoundsLabel == EmptyView, MarkedValueLabels == EmptyView, V : BinaryFloatingPoint
/// Creates a gauge showing a value within a range and that describes the
/// gauge's purpose and current value.
///
/// Use this method to create a gauge that displays a value within a range
/// you supply with labels that describe the purpose of the gauge and its
/// current value. In the example below, a gauge using the
/// ``GaugeStyle/circular`` style shows its current value of `67` along with a
/// label describing the (BPM) for the gauge:
///
/// struct SimpleGauge: View {
/// @State private var current = 67.0
///
/// var body: some View {
/// Gauge(value: currrent, in: 0...170) {
/// Text("BPM")
/// } currentValueLabel: {
/// Text("\(current)")
/// }
/// .gaugeStyle(.circular)
/// }
/// }
///
/// ![A screenshot showing a circular gauge describing heart rate in beats
/// per minute, with the indicator and the current value label indicating a
/// value of 67.](SwiftUI-Gauge-LabelCurrentValueCircular.png)
///
/// - Parameters:
/// - value: The value to show on the gauge.
/// - bounds: The range of the valid values. Defaults to `0...1`.
/// - label: A view that describes the purpose of the gauge.
/// - currentValueLabel: A view that describes the current value of
/// the gauge.
public init<V>(value: V, in bounds: ClosedRange<V> = 0...1, @ViewBuilder label: () -> Label, @ViewBuilder currentValueLabel: () -> CurrentValueLabel) where BoundsLabel == EmptyView, MarkedValueLabels == EmptyView, V : BinaryFloatingPoint
/// Creates a gauge showing a value within a range and describes the
/// gauge's current, minimum, and maximum values.
///
/// Use this method to create a gauge that shows a value within a
/// prescribed bounds. The gauge has labels that describe its purpose,
/// and for the gauge's current, minimum, and maximum values.
///
/// 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))")
/// }
/// }
/// }
///
/// ![A screenshot of a gauge, labeled BPM, that's represented by a
/// semicircle showing its current value of 67 along a range of 0
/// to 170.](SwiftUI-Gauge-LabeledCircular.png)
///
/// - Parameters:
/// - value: The value to show on the gauge.
/// - bounds: The range of the valid values. Defaults to `0...1`.
/// - label: A view that describes the purpose of the gauge.
/// - currentValueLabel: A view that describes the current value of
/// the gauge.
/// - minimumValueLabel: A view that describes the lower bounds of the
/// gauge.
/// - maximumValueLabel: A view that describes the upper bounds of the
/// gauge.
public init<V>(value: V, in bounds: ClosedRange<V> = 0...1, @ViewBuilder label: () -> Label, @ViewBuilder currentValueLabel: () -> CurrentValueLabel, @ViewBuilder minimumValueLabel: () -> BoundsLabel, @ViewBuilder maximumValueLabel: () -> BoundsLabel) where MarkedValueLabels == EmptyView, V : BinaryFloatingPoint
/// Creates a gauge representing a value within a range.
///
/// - Parameters:
/// - value: The value to show in the instance.
/// - bounds: The range of the valid values. Defaults to `0...1`.
/// - label: A view that describes the purpose of the gauge.
/// - currentValueLabel: A view that describes the current value of
/// the gauge.
/// - minimumValueLabel: A view that describes the lower bounds of the
/// gauge.
/// - maximumValueLabel: A view that describes the upper bounds of the
/// gauge.
/// - markedValueLabels: A view builder containing tagged views,
/// each of which describes a particular value of the gauge.
/// The method ignores this parameter.
public init<V>(value: V, in bounds: ClosedRange<V> = 0...1, @ViewBuilder label: () -> Label, @ViewBuilder currentValueLabel: () -> CurrentValueLabel, @ViewBuilder markedValueLabels: () -> MarkedValueLabels) where BoundsLabel == EmptyView, V : BinaryFloatingPoint
/// Creates a gauge representing a value within a range.
///
/// - Parameters:
/// - value: The value to show in the gauge.
/// - bounds: The range of the valid values. Defaults to `0...1`.
/// - label: A view that describes the purpose of the gauge.
/// - currentValueLabel: A view that describes the current value of
/// the gauge.
/// - minimumValueLabel: A view that describes the lower bounds of the
/// gauge.
/// - maximumValueLabel: A view that describes the upper bounds of the
/// gauge.
/// - markedValueLabels: A view builder containing tagged views.
/// each of which describes a particular value of the gauge.
/// The method ignores this parameter.
public init<V>(value: V, in bounds: ClosedRange<V> = 0...1, @ViewBuilder label: () -> Label, @ViewBuilder currentValueLabel: () -> CurrentValueLabel, @ViewBuilder minimumValueLabel: () -> BoundsLabel, @ViewBuilder maximumValueLabel: () -> BoundsLabel, @ViewBuilder markedValueLabels: () -> MarkedValueLabels) where V : BinaryFloatingPoint
/// The content and behavior of the view.
///
/// 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 <doc:Declaring-a-Custom-View>.
@MainActor public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = some View
}
/// Defines the implementation of all gauge instances within a view
/// hierarchy.
///
/// To configure the style for all the ``Gauge`` instances in a view hierarchy,
/// use the ``View/gaugeStyle(_:)`` modifier. For example, you can configure
/// a gauge to use the ``circular`` style:
///
/// Gauge(value: batteryLevel, in: 0...100) {
/// Text("Battery Level")
/// }
/// .gaugeStyle(.circular)
///
@available(iOS 16.0, macOS 13.0, watchOS 7.0, *)
@available(tvOS, unavailable)
public protocol GaugeStyle {
/// A view representing the body of a gauge.
associatedtype Body : View
/// Creates a view representing the body of a gauge.
///
/// The system calls this modifier on each instance of gauge within a view
/// hierarchy where this style is the current gauge style.
///
/// - Parameter configuration: The properties to apply to the gauge instance.
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a gauge instance.
typealias Configuration = GaugeStyleConfiguration
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
extension GaugeStyle where Self == AccessoryCircularCapacityGaugeStyle {
/// A gauge style that displays a closed ring that's partially filled in to
/// indicate the gauge's current value.
///
/// Apply this style to a ``Gauge`` or to a view hierarchy that contains
/// gauges using the ``View/gaugeStyle(_:)`` modifier:
///
/// Gauge(value: batteryLevel, in: 0...100) {
/// Text("Battery Level")
/// }
/// .gaugeStyle(.accessoryCircularCapacity)
///
/// This style displays the gauge's `currentValueLabel` value at the center
/// of the gauge.
public static var accessoryCircularCapacity: AccessoryCircularCapacityGaugeStyle { get }
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
extension GaugeStyle where Self == LinearCapacityGaugeStyle {
/// A gauge style that displays a bar that fills from leading to trailing
/// edges as the gauge's current value increases.
///
/// Apply this style to a ``Gauge`` or to a view hierarchy that contains
/// gauges using the ``View/gaugeStyle(_:)`` modifier:
///
/// Gauge(value: batteryLevel, in: 0...100) {
/// Text("Battery Level")
/// }
/// .gaugeStyle(.linearCapacity)
///
/// If you provide `minimumValueLabel` and `maximumValueLabel`
/// parameters when you create the gauge, they appear on leading and
/// trailing edges of the bar, respectively. The `label` appears above
/// the gauge, and the `currentValueLabel` appears below.
public static var linearCapacity: LinearCapacityGaugeStyle { get }
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
extension GaugeStyle where Self == AccessoryLinearGaugeStyle {
/// A gauge style that displays bar with a marker that appears at a
/// point along the bar to indicate the gauge's current value.
///
/// Apply this style to a ``Gauge`` or to a view hierarchy that contains
/// gauges using the ``View/gaugeStyle(_:)`` modifier:
///
/// Gauge(value: batteryLevel, in: 0...100) {
/// Text("Battery Level")
/// }
/// .gaugeStyle(.accessoryLinear)
///
/// If you provide `minimumValueLabel` and `maximumValueLabel`
/// parameters when you create the gauge, they appear on leading and
/// trailing edges of the bar, respectively. Otherwise, the gauge displays
/// the `currentValueLabel` value on the leading edge.
public static var accessoryLinear: AccessoryLinearGaugeStyle { get }
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
extension GaugeStyle where Self == AccessoryLinearCapacityGaugeStyle {
/// A gauge style that displays bar that fills from leading to trailing
/// edges as the gauge's current value increases.
///
/// Apply this style to a ``Gauge`` or to a view hierarchy that contains
/// gauges using the ``View/gaugeStyle(_:)`` modifier:
///
/// Gauge(value: batteryLevel, in: 0...100) {
/// Text("Battery Level")
/// }
/// .gaugeStyle(.accessoryLinearCapacity)
///
/// If you provide `minimumValueLabel` and `maximumValueLabel`
/// parameters when you create the gauge, they appear on leading and
/// trailing edges of the bar, respectively. The `label` appears above
/// the gauge, and the `currentValueLabel` appears below.
public static var accessoryLinearCapacity: AccessoryLinearCapacityGaugeStyle { get }
}
@available(iOS 16.0, macOS 13.0, watchOS 7.0, *)
@available(tvOS, unavailable)
extension GaugeStyle where Self == DefaultGaugeStyle {
/// The default gauge view style in the current context of the view being
/// styled.
public static var automatic: DefaultGaugeStyle { get }
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, *)
@available(tvOS, unavailable)
extension GaugeStyle where Self == AccessoryCircularGaugeStyle {
/// A gauge style that displays an open ring with a marker that appears at a
/// point along the ring to indicate the gauge's current value.
///
/// Apply this style to a ``Gauge`` or to a view hierarchy that contains
/// gauges using the ``View/gaugeStyle(_:)`` modifier:
///
/// Gauge(value: batteryLevel, in: 0...100) {
/// Text("Battery Level")
/// }
/// .gaugeStyle(.accessoryCircular)
///
/// This style displays the gauge's `currentValueLabel` value at the center
/// of the gauge. If you provide `minimumValueLabel` and `maximumValueLabel`
/// parameters when you create the gauge, they appear in the opening at the
/// bottom of the ring. Otherwise, the gauge places its label in that
/// location.
public static var accessoryCircular: AccessoryCircularGaugeStyle { get }
}
/// The properties of a gauge instance.
@available(iOS 16.0, macOS 13.0, watchOS 7.0, *)
@available(tvOS, unavailable)
public struct GaugeStyleConfiguration {
/// A type-erased label of a gauge, describing its purpose.
public struct Label : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A type-erased value label of a gauge that contains the current value.
public struct CurrentValueLabel : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A type-erased value label of a gauge describing the minimum value.
public struct MinimumValueLabel : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A type-erased value label of a gauge describing the maximum value.
public struct MaximumValueLabel : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// A type-erased label describing a specific value of a gauge.
public struct MarkedValueLabel : View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// The current value of the gauge.
///
/// The valid range is `0.0...1.0`.
public var value: Double
/// A view that describes the purpose of the gauge.
public var label: GaugeStyleConfiguration.Label
/// A view that describes the current value.
public var currentValueLabel: GaugeStyleConfiguration.CurrentValueLabel?
/// A view that describes the minimum of the range for the current value.
public var minimumValueLabel: GaugeStyleConfiguration.MinimumValueLabel?
/// A view that describes the maximum of the range for the current value.
public var maximumValueLabel: GaugeStyleConfiguration.MaximumValueLabel?
}
/// An effect that changes the visual appearance of a view, largely without
/// changing its ancestors or descendants.
///
/// The only change the effect makes to the view's ancestors and descendants is
/// to change the coordinate transform to and from them.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol GeometryEffect : Animatable, ViewModifier where Self.Body == Never {
/// Returns the current value of the effect.
func effectValue(size: CGSize) -> ProjectionTransform
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension GeometryEffect {
/// Returns an effect that produces the same geometry transform as this
/// effect, but only applies the transform while rendering its view.
///
/// Use this method to disable layout changes during transitions. The view
/// ignores the transform returned by this method while the view is
/// performing its layout calculations.
@inlinable public func ignoredByLayout() -> _IgnoredByLayoutEffect<Self>
}
/// A proxy for access to the size and coordinate space (for anchor resolution)
/// of the container view.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct GeometryProxy {
/// The size of the container view.
public var size: CGSize { get }
/// Resolves the value of `anchor` to the container view.
public subscript<T>(anchor: Anchor<T>) -> T { get }
/// The safe area inset of the container view.
public var safeAreaInsets: EdgeInsets { get }
/// Returns the container view's bounds rectangle, converted to a defined
/// coordinate space.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
public func frame(in coordinateSpace: CoordinateSpace) -> CGRect
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension GeometryProxy {
/// Returns the given coordinate space's bounds rectangle, converted to the
/// local coordinate space.
public func bounds(of coordinateSpace: NamedCoordinateSpace) -> CGRect?
/// Returns the container view's bounds rectangle, converted to a defined
/// coordinate space.
public func frame(in coordinateSpace: some CoordinateSpaceProtocol) -> CGRect
}
/// A container view that defines its content as a function of its own size and
/// coordinate space.
///
/// This view returns a flexible preferred size to its parent layout.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct GeometryReader<Content> : View where Content : View {
public var content: (GeometryProxy) -> Content
@inlinable public init(@ViewBuilder content: @escaping (GeometryProxy) -> Content)
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
public typealias Body = Never
}
/// An instance that matches a sequence of events to a gesture, and returns a
/// stream of values for each of its states.
///
/// Create custom gestures by declaring types that conform to the `Gesture`
/// protocol.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol Gesture<Value> {
/// The type representing the gesture's value.
associatedtype Value
/// The type of gesture representing the body of `Self`.
associatedtype Body : Gesture
/// The content and behavior of the gesture.
var body: Self.Body { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Gesture {
/// Sequences a gesture with another one to create a new gesture, which
/// results in the second gesture only receiving events after the first
/// gesture succeeds.
///
/// - Parameter other: A gesture you want to combine with another gesture to
/// create a new, sequenced gesture.
///
/// - Returns: A gesture that's a sequence of two gestures.
@inlinable public func sequenced<Other>(before other: Other) -> SequenceGesture<Self, Other> where Other : Gesture
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Gesture {
/// Updates the provided gesture state property as the gesture's value
/// changes.
///
/// Use this callback to update transient UI state as described in
/// <doc:Adding-Interactivity-with-Gestures>.
///
/// - Parameters:
/// - state: A binding to a view's ``GestureState`` property.
/// - body: The callback that SwiftUI invokes as the gesture's value
/// changes. Its `currentState` parameter is the updated state of the
/// gesture. The `gestureState` parameter is the previous state of the
/// gesture, and the `transaction` is the context of the gesture.
///
/// - Returns: A version of the gesture that updates the provided `state` as
/// the originating gesture's value changes and that resets the `state`
/// to its initial value when the user or the system ends or cancels the
/// gesture.
@inlinable public func updating<State>(_ state: GestureState<State>, body: @escaping (Self.Value, inout State, inout Transaction) -> Void) -> GestureStateGesture<Self, State>
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Gesture {
/// Combines a gesture with another gesture to create a new gesture that
/// recognizes both gestures at the same time.
///
/// - Parameter other: A gesture that you want to combine with your gesture
/// to create a new, combined gesture.
///
/// - Returns: A gesture with two simultaneous gestures.
@inlinable public func simultaneously<Other>(with other: Other) -> SimultaneousGesture<Self, Other> where Other : Gesture
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Gesture {
/// Adds an action to perform when the gesture ends.
///
/// - Parameter action: The action to perform when this gesture ends. The
/// `action` closure's parameter contains the final value of the gesture.
///
/// - Returns: A gesture that triggers `action` when the gesture ends.
public func onEnded(_ action: @escaping (Self.Value) -> Void) -> _EndedGesture<Self>
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Gesture where Self.Value : Equatable {
/// Adds an action to perform when the gesture's value changes.
///
/// - Parameter action: The action to perform when this gesture's value
/// changes. The `action` closure's parameter contains the gesture's new
/// value.
///
/// - Returns: A gesture that triggers `action` when this gesture's value
/// changes.
public func onChanged(_ action: @escaping (Self.Value) -> Void) -> _ChangedGesture<Self>
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Gesture {
/// Returns a gesture that's the result of mapping the given closure over
/// the gesture.
public func map<T>(_ body: @escaping (Self.Value) -> T) -> _MapGesture<Self, T>
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Gesture {
/// Combines two gestures exclusively to create a new gesture where only one
/// gesture succeeds, giving precedence to the first gesture.
///
/// - Parameter other: A gesture you combine with your gesture, to create a
/// new, combined gesture.
///
/// - Returns: A gesture that's the result of combining two gestures where
/// only one of them can succeed. SwiftUI gives precedence to the first
/// gesture.
@inlinable public func exclusively<Other>(before other: Other) -> ExclusiveGesture<Self, Other> where Other : Gesture
}
@available(macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
extension Gesture {
/// Combines a gesture with keyboard modifiers.
///
/// The gesture receives updates while the user presses the modifier keys
/// that correspond to the given modifiers option set.
///
/// - Parameter modifiers: A set of flags that correspond to the modifier
/// keys that the user needs to hold down.
///
/// - Returns: A new gesture that combines a gesture with keyboard
/// modifiers.
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public func modifiers(_ modifiers: EventModifiers) -> _ModifiersGesture<Self>
}
/// Options that control how adding a gesture to a view affects other gestures
/// recognized by the view and its subviews.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct GestureMask : OptionSet {
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public let rawValue: UInt32
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
public init(rawValue: UInt32)
/// Disable all gestures in the subview hierarchy, including the added
/// gesture.
public static let none: GestureMask
/// Enable the added gesture but disable all gestures in the subview
/// hierarchy.
public static let gesture: GestureMask
/// Enable all gestures in the subview hierarchy but disable the added
/// gesture.
public static let subviews: GestureMask
/// Enable both the added gesture as well as all other gestures on the view
/// and its subviews.
public static let all: GestureMask
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = GestureMask
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
public typealias Element = GestureMask
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
public typealias RawValue = UInt32
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension GestureMask : Sendable {
}
/// A property wrapper type that updates a property while the user performs a
/// gesture and resets the property back to its initial state when the gesture
/// ends.
///
/// Declare a property as `@GestureState`, pass as a binding to it as a
/// parameter to a gesture's ``Gesture/updating(_:body:)`` callback, and receive
/// updates to it. A property that's declared as `@GestureState` implicitly
/// resets when the gesture becomes inactive, making it suitable for tracking
/// transient state.
///
/// Add a long-press gesture to a ``Circle``, and update the interface during
/// the gesture by declaring a property as `@GestureState`:
///
/// struct SimpleLongPressGestureView: View {
/// @GestureState private var isDetectingLongPress = false
///
/// var longPress: some Gesture {
/// LongPressGesture(minimumDuration: 3)
/// .updating($isDetectingLongPress) { currentState, gestureState, transaction in
/// gestureState = currentState
/// }
/// }
///
/// var body: some View {
/// Circle()
/// .fill(self.isDetectingLongPress ? Color.red : Color.green)
/// .frame(width: 100, height: 100, alignment: .center)
/// .gesture(longPress)
/// }
/// }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper @frozen public struct GestureState<Value> : DynamicProperty {
/// Creates a view state that's derived from a gesture.
///
/// - Parameter wrappedValue: A wrapped value for the gesture state
/// property.
public init(wrappedValue: Value)
/// Creates a view state that's derived from a gesture with an initial
/// value.
///
/// - Parameter initialValue: An initial value for the gesture state
/// property.
public init(initialValue: Value)
/// Creates a view state that's derived from a gesture with a wrapped state
/// value and a transaction to reset it.
///
/// - Parameters:
/// - wrappedValue: A wrapped value for the gesture state property.
/// - resetTransaction: A transaction that provides metadata for view
/// updates.
public init(wrappedValue: Value, resetTransaction: Transaction)
/// Creates a view state that's derived from a gesture with an initial state
/// value and a transaction to reset it.
///
/// - Parameters:
/// - initialValue: An initial state value.
/// - resetTransaction: A transaction that provides metadata for view
/// updates.
public init(initialValue: Value, resetTransaction: Transaction)
/// Creates a view state that's derived from a gesture with a wrapped state
/// value and a closure that provides a transaction to reset it.
///
/// - Parameters:
/// - wrappedValue: A wrapped value for the gesture state property.
/// - reset: A closure that provides a ``Transaction``.
public init(wrappedValue: Value, reset: @escaping (Value, inout Transaction) -> Void)
/// Creates a view state that's derived from a gesture with an initial state
/// value and a closure that provides a transaction to reset it.
///
/// - Parameters:
/// - initialValue: An initial state value.
/// - reset: A closure that provides a ``Transaction``.
public init(initialValue: Value, reset: @escaping (Value, inout Transaction) -> Void)
/// The wrapped value referenced by the gesture state property.
public var wrappedValue: Value { get }
/// A binding to the gesture state property.
public var projectedValue: GestureState<Value> { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension GestureState where Value : ExpressibleByNilLiteral {
/// Creates a view state that's derived from a gesture with a transaction to
/// reset it.
///
/// - Parameter resetTransaction: A transaction that provides metadata for
/// view updates.
public init(resetTransaction: Transaction = Transaction())
/// Creates a view state that's derived from a gesture with a closure that
/// provides a transaction to reset it.
///
/// - Parameter reset: A closure that provides a ``Transaction``.
public init(reset: @escaping (Value, inout Transaction) -> Void)
}
/// A gesture that updates the state provided by a gesture's updating callback.
///
/// A gesture's ``Gesture/updating(_:body:)`` callback returns a
/// `GestureStateGesture` instance for updating a transient state property
/// that's annotated with the ``GestureState`` property wrapper.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct GestureStateGesture<Base, State> : Gesture where Base : Gesture {
/// The type representing the gesture's value.
public typealias Value = Base.Value
/// The originating gesture.
public var base: Base
/// A value that changes as the user performs the gesture.
public var state: GestureState<State>
/// The updating gesture containing the originating gesture's value, the
/// updated state of the gesture, and a transaction.
public var body: (GestureStateGesture<Base, State>.Value, inout State, inout Transaction) -> Void
/// Creates a new gesture that's the result of an ongoing gesture.
///
/// - Parameters:
/// - base: The originating gesture.
/// - state: The wrapped value of a ``GestureState`` property.
/// - body: The callback that SwiftUI invokes as the gesture's value
/// changes.
@inlinable public init(base: Base, state: GestureState<State>, body: @escaping (GestureStateGest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment