Skip to content

Instantly share code, notes, and snippets.

@duraidabdul
Last active July 27, 2021 18:27
Show Gist options
  • Save duraidabdul/b16c5704603ce4d154a6f1537c6a40e6 to your computer and use it in GitHub Desktop.
Save duraidabdul/b16c5704603ce4d154a6f1537c6a40e6 to your computer and use it in GitHub Desktop.
Xcode 13.0 beta 4 SwiftUI Interface
This file has been truncated, but you can view the full file.
import Accessibility
import Combine
import CoreData
import CoreFoundation
import CoreGraphics
import Darwin
import DeveloperToolsSupport
import Foundation
import UIKit
import UniformTypeIdentifiers
import _Concurrency
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)
}
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 {
/// 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(iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@available(macOS, unavailable)
public static let magicTap: 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 {
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: Never call `finalize()` on `hasher`. 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.
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
}
@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: Never call `finalize()` on `hasher`. 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.
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)
}
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
}
/// 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 public struct AccessibilityFocusState<Value> : DynamicProperty where Value : Hashable {
@propertyWrapper 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 {
}
@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
}
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: Never call `finalize()` on `hasher`. 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.
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 {
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 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension AccessibilityRotorContentBuilder {
public static func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> some AccessibilityRotorContent where C0 : AccessibilityRotorContent, C1 : AccessibilityRotorContent
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.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 14.0, macOS 11.0, tvOS 14.0, watchOS 7.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 14.0, macOS 11.0, tvOS 14.0, watchOS 7.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 14.0, macOS 11.0, tvOS 14.0, watchOS 7.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 14.0, macOS 11.0, tvOS 14.0, watchOS 7.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 14.0, macOS 11.0, tvOS 14.0, watchOS 7.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 14.0, macOS 11.0, tvOS 14.0, watchOS 7.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 14.0, macOS 11.0, tvOS 14.0, watchOS 7.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 {
/// 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 {
/// 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 {
/// 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 {
/// 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
/// 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
}
/// A representation of an action sheet presentation.
///
/// Use an action sheet when you want the user to make a choice between two
/// or more options, in response to their own action. If you want the user to
/// act in response to the state of the app or the system, rather than a user
/// action, use an ``Alert`` instead.
///
/// You show an action sheet by using the
/// ``View/actionSheet(isPresented:content:)`` view modifier to create an
/// action sheet, which then appears whenever the bound `isPresented` value is
/// `true`. The `content` closure you provide to this modifier produces a
/// customized instance of the `ActionSheet` type. To supply the options, create
/// instances of ``ActionSheet/Button`` to distinguish between ordinary options,
/// destructive options, and cancellation of the user's original action.
///
/// The action sheet handles its own dismissal by setting the bound
/// `isPresented` value back to `false` when the user taps a button in the
/// action sheet.
///
/// The following example creates an action sheet with three options: a Cancel
/// button, a destructive button, and a default button. The second and third of
/// these call methods are named `overwriteWorkout` and `appendWorkout`,
/// respectively.
///
/// @State private var showActionSheet = false
/// var body: some View {
/// Button("Tap to show action sheet") {
/// showActionSheet = true
/// }
/// .actionSheet(isPresented: $showActionSheet) {
/// ActionSheet(title: Text("Resume Workout Recording"),
/// message: Text("Choose a destination for workout data"),
/// buttons: [
/// .cancel(),
/// .destructive(
/// Text("Overwrite Current Workout"),
/// action: overwriteWorkout
/// ),
/// .default(
/// Text("Append to Current Workout"),
/// action: appendWorkout
/// )
/// ]
/// )
/// }
/// }
///
/// The system may interpret the order of items as they appear in the `buttons`
/// array to accommodate platform conventions. In this example, the Cancel
/// button is the first member of the array, but the action sheet puts it in its
/// standard position at the bottom of the sheet.
///
/// ![An action sheet with the title Resume Workout Recording in bold text and
/// the message Choose a destination for workout data in smaller text. Below
/// the text, three buttons: a destructive Overwrite Current Workout button in
/// red, a default-styled Overwrite Current Workout button, and a Cancel button,
/// farther below and set off in its own button
/// group.](SwiftUI-ActionSheet-cancel-and-destructive.png)
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "use `View.confirmationDialog(title:isPresented:titleVisibility:presenting::actions:)`instead.")
@available(macOS, unavailable)
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "use `View.confirmationDialog(title:isPresented:titleVisibility:presenting:actions:)`instead.")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "use `View.confirmationDialog(title:isPresented:titleVisibility:presenting:actions:)`instead.")
public struct ActionSheet {
/// Creates an action sheet with the provided buttons.
/// - Parameters:
/// - title: The title of the action sheet.
/// - message: The message to display in the body of the action sheet.
/// - buttons: The buttons to show in the action sheet.
public init(title: Text, message: Text? = nil, buttons: [ActionSheet.Button] = [.cancel()])
/// A button representing an operation of an action sheet presentation.
///
/// The ``ActionSheet`` button is type-aliased to the ``Alert`` button type,
/// which provides default, cancel, and destructive styles.
public typealias Button = Alert.Button
}
/// 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.
///
/// The following table shows the various alignment guides next to each other.
///
/// ![A table showing the various alignment guides next to each
/// other.](SwiftUI-Alignment-table.png)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Alignment : Equatable {
/// The alignment on the horizontal axis.
public var horizontal: HorizontalAlignment
/// The alignment on the vertical axis.
public var vertical: VerticalAlignment
/// Creates an instance with the given horizontal and vertical alignments.
///
/// - Parameters:
/// - horizontal: The alignment on the horizontal axis.
/// - vertical: The alignment on the vertical axis.
@inlinable public init(horizontal: HorizontalAlignment, vertical: VerticalAlignment)
/// A guide marking the center of the view.
public static let center: Alignment
/// A guide marking the leading edge of the view.
public static let leading: Alignment
/// A guide marking the trailing edge of the view.
public static let trailing: Alignment
/// A guide marking the top edge of the view.
public static let top: Alignment
/// A guide marking the bottom edge of the view.
public static let bottom: Alignment
/// A guide marking the top and leading edges of the view.
public static let topLeading: Alignment
/// A guide marking the top and trailing edges of the view.
public static let topTrailing: Alignment
/// A guide marking the bottom and leading edges of the view.
public static let bottomLeading: Alignment
/// A guide marking the bottom and trailing edges of the view.
public static let bottomTrailing: Alignment
/// 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 : Sendable {
}
/// Types used to identify alignment guides.
///
/// Types conforming to `AlignmentID` have a corresponding alignment guide
/// value, typically declared as a static constant property of
/// ``HorizontalAlignment`` or ``VerticalAlignment``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol AlignmentID {
/// The value of the corresponding guide in the given context when not
/// otherwise set in that context.
static func defaultValue(in context: ViewDimensions) -> CGFloat
}
/// 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 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { 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 }
}
@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 {
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?
}
/// 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
/// 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
/// 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: Never call `finalize()` on `hasher`. 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.
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:)``,
/// ``ShapeStyle/conicGradient(_:center:angle:)``, or similar methods.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AngularGradient : ShapeStyle, View {
/// 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
}
/// 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 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
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, *)
@frozen public struct Animation : 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: Animation, rhs: Animation) -> Bool
}
@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
/// 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.55, dampingFraction: Double = 0.825, blendDuration: Double = 0) -> Animation
/// 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: Double = 0.25) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
public static let `default`: Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
public static func easeInOut(duration: Double) -> Animation
public static var easeInOut: Animation { get }
public static func easeIn(duration: Double) -> Animation
public static var easeIn: Animation { get }
public static func easeOut(duration: Double) -> Animation
public static var easeOut: Animation { get }
public static func linear(duration: Double) -> Animation
public static var linear: Animation { get }
public static func timingCurve(_ c0x: Double, _ c0y: Double, _ c1x: Double, _ c1y: Double, duration: Double = 0.35) -> 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
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
public func delay(_ delay: Double) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// Returns an animation that has its speed multiplied by `speed`. For
/// example, if you had `oneSecondAnimation.speed(0.25)`, it would be at 25%
/// of its normal speed, so you would have an animation that would last 4
/// seconds.
public func speed(_ speed: Double) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
public func repeatCount(_ repeatCount: Int, autoreverses: Bool = true) -> Animation
public func repeatForever(autoreverses: Bool = true) -> Animation
}
@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 }
}
/// A pausable schedule of dates updating at a frequency no more quickly than
/// the provided interval.
///
/// Do not use this type directly. Instead, use
/// ``TimelineSchedule/animation(minimumInterval:paused:)``.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AnimationTimelineSchedule : TimelineSchedule {
/// 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.
@available(iOS, introduced: 15.0, deprecated: 15.0, message: "Use `.animation(minimumInterval:paused:)` instead.")
@available(macOS, introduced: 12.0, deprecated: 12.0, message: "Use `.animation(minimumInterval:paused:)` instead.")
@available(tvOS, introduced: 15.0, deprecated: 15.0, message: "Use `.animation(minimumInterval:paused:)` instead.")
@available(watchOS, introduced: 8.0, deprecated: 8.0, message: "Use `.animation(minimumInterval:paused:)` instead.")
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 {
/// 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 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
}
/// A type-erased transition.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct 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 {
public static var scale: AnyTransition { get }
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 {
/// 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 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 {
/// Attaches an animation to this transition.
public func animation(_ animation: Animation?) -> AnyTransition
}
@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
}
/// 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 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.
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.
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 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 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 primitive 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>.
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 {
/// 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.
///
/// Do not use this type directly. Instead, use ``ControlGroupStyle/automatic``.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@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`.
public func makeBody(configuration: AutomaticControlGroupStyle.Configuration) -> some View
/// A view representing the body of a control group.
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 background style in the current context.
///
/// Do not use this type directly. Instead, use ``ShapeStyle/background``.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@frozen public struct BackgroundStyle {
/// Creates a background style instance.
@inlinable public init()
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension BackgroundStyle : ShapeStyle {
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension BackgroundStyle : 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(action: {
/// self.isPlaying.toggle()
/// }) {
/// Image(systemName: isPlaying ? "pause.circle" : "play.circle")
/// }
/// }
/// }
///
/// 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)
/// Text(episode.showTitle)
/// PlayButton(isPlaying: $isPlaying)
/// }
/// }
/// }
///
/// 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.
@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. For instance, 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(action: {
/// self.isPlaying.toggle()
/// }) {
/// Image(systemName: isPlaying ? "pause.circle" : "play.circle")
/// }
/// }
/// }
///
/// 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)
/// Text(episode.showTitle)
/// 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 sequence that represents a contiguous subrange of the collection's
/// elements.
///
/// This associated type appears as a requirement in the `Sequence`
/// protocol, but it is restated here with stricter constraints. In a
/// collection, the subsequence should also conform to `Collection`.
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 {
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: Never call `finalize()` on `hasher`. 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.
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 button style that applies standard border artwork based on the button's
/// context.
///
/// Do not use this type directly. Instead, use
/// ``PrimitiveButtonStyle/bordered``.
@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
}
@available(*, deprecated, message: "Use View.buttonBorderShape(_:) instead.")
extension BorderedButtonStyle {
/// A type that describes the shape of a bordered button.
public struct BorderShape {
/// A shape that defers to the system to determine an appropriate shape
/// for the given context and platform.
public static let automatic: BorderedButtonStyle.BorderShape
/// A capsule shape.
@available(tvOS, unavailable)
@available(macOS, unavailable)
public static let capsule: BorderedButtonStyle.BorderShape
/// A rounded rectangle shape.
public static let roundedRectangle: BorderedButtonStyle.BorderShape
}
/// Creates a bordered button style with a shape.
///
/// - Parameter shape: a shape used to draw the button's border.
public init(shape: BorderedButtonStyle.BorderShape)
}
/// A button style that applies standard border prominent artwork based
/// on the button's context.
///
/// You can also use ``ButtonStyle/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
}
/// A menu style that displays a borderless button that toggles the display of
/// the menu's contents when pressed.
///
/// Do not use this type directly. Instead, use ``MenuStyle/borderlessButton``.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct BorderlessButtonMenuStyle : MenuStyle {
/// Creates a borderless 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: 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.
///
/// Do not use this type directly. Instead, use
/// ``PrimitiveButtonStyle/borderless``.
@available(iOS 13.0, macOS 10.15, watchOS 8.0, *)
@available(tvOS, unavailable)
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 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:
///
/// Button(action: signIn) {
/// Text("Sign In")
/// }
///
/// For the common case of text-only labels, you can use the convenience
/// initializer that takes a title string or ``LocalizedStringKey`` as its first
/// parameter, instead of a trailing closure:
///
/// Button("Sign In", action: signIn)
///
/// 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 primitive 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>.
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 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
}
/// 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 {
/// 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.
@available(tvOS, unavailable)
@available(macOS, unavailable)
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.
@available(tvOS, unavailable)
@available(macOS, unavailable)
public static func roundedRectangle(radius: CGFloat) -> 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
}
/// 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 {
/// 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)
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.
///
/// Do not use this type directly. Instead, use ``ToggleStyle/button``.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct ButtonToggleStyle : ToggleStyle {
/// Creates a button toggle style.
@available(iOS, introduced: 15.0, deprecated: 15.0, message: "Use `.button` instead.")
@available(macOS, introduced: 12.0, deprecated: 12.0, message: "Use `.button` instead.")
public init()
/// Creates a view that represents the body of a toggle.
///
/// The system calls this method for each ``Toggle`` instance in a view
/// hierarchy where this style is the current toggle style.
///
/// - Parameter configuration: The properties of the toggle, such as its
/// label and its “on” state.
public func makeBody(configuration: ButtonToggleStyle.Configuration) -> some View
/// A view that represents the appearance and interaction of a toggle.
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/CoreGraphics/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
@inlinable public init(style: RoundedCornerStyle = .circular)
/// 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
/// 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 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
@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 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
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Circle : Sendable {
}
/// A progress view that visually indicates its progress using a circular gauge.
///
/// Do not use this type directly. Instead, use ``ProgressViewStyle/circular``.
@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.")
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 {
/// 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`.
@available(iOS 14.0, macOS 11, tvOS 14.0, watchOS 7.0, *)
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.
public var hashValue: Int { get }
}
@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, 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")
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 {
/// A profile that specifies how to interpret a color value for display.
public enum RGBColorSpace {
/// 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: Never call `finalize()` on `hasher`. 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.
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 {
/// 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 {
/// 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 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 {
/// 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, introduced: 13.0, deprecated: 100000.0, message: "Use Color(uiColor:) when converting a UIColor, or create a standard Color directly")
@available(macOS, unavailable)
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Use Color(uiColor:) when converting a UIColor, or create a standard Color directly")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Use Color(uiColor:) when converting a UIColor, or create a standard Color directly")
extension Color {
/// Creates a color from a UIKit color.
///
/// Use this method to create a SwiftUI color from a
/// <doc://com.apple.documentation/documentation/UIKit/UIColor> instance.
/// The new color preserves the adaptability of the original.
/// For example, you can create a rectangle using
/// <doc://com.apple.documentation/documentation/UIKit/UIColor/3173132-link>
/// to see how the shade adjusts to match the user's system settings:
///
/// struct Box: View {
/// var body: some View {
/// Color(UIColor.link)
/// .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-3)
///
/// > Note: Use this initializer only if you need to convert an existing
/// <doc://com.apple.documentation/documentation/UIKit/UIColor> 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: A
/// <doc://com.apple.documentation/documentation/UIKit/UIColor> instance
/// from which to create a color.
public init(_ color: UIColor)
}
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, *)
@available(macOS, unavailable)
extension Color {
/// Creates a color from a UIKit color.
///
/// Use this method to create a SwiftUI color from a
/// <doc://com.apple.documentation/documentation/UIKit/UIColor> instance.
/// The new color preserves the adaptability of the original.
/// For example, you can create a rectangle using
/// <doc://com.apple.documentation/documentation/UIKit/UIColor/3173132-link>
/// to see how the shade adjusts to match the user's system settings:
///
/// struct Box: View {
/// var body: some View {
/// Color(uiColor: .link)
/// .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-3)
///
/// > Note: Use this initializer only if you need to convert an existing
/// <doc://com.apple.documentation/documentation/UIKit/UIColor> 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: A
/// <doc://com.apple.documentation/documentation/UIKit/UIColor> instance
/// from which to create a color.
public init(uiColor: UIColor)
}
@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.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 primitive 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>.
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 {
/// 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: Never call `finalize()` on `hasher`. 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.
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 types of color schemes, like Dark Mode.
///
/// The color scheme enumerates the user setting options for Light or Dark Mode.
/// It also provides the light or dark options for any particular view when the
/// app wants to override the user setting.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum ColorScheme : CaseIterable {
case light
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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
extension ColorScheme {
/// Create a color scheme from its UIUserInterfaceStyle equivalent.
@available(iOS 14.0, tvOS 14.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
public init?(_ uiUserInterfaceStyle: UIUserInterfaceStyle)
}
@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 {
}
/// Options indicating whether the system uses standard or increased contrast
/// between the app's foreground and background colors.
///
/// The user sets the Increase Contrast option using the Settings app. Your app
/// cannot override the user's choice.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum ColorSchemeContrast : CaseIterable {
/// An option indicating that the system is using standard contrast between
/// the app's foreground and background colors.
case standard
/// An option indicating that the system is using 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
extension ColorSchemeContrast {
/// Create a contrast from its UIAccessibilityContrast equivalent.
@available(iOS 14.0, tvOS 14.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
public init?(_ uiAccessibilityContrast: UIAccessibilityContrast)
}
@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.
///
/// Do not use this type directly. Instead, use ``NavigationViewStyle/columns``.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct ColumnNavigationViewStyle : NavigationViewStyle {
}
/// Command groups describe additional groupings of controls to add to existing
/// command menus.
///
/// On macOS, command groups are realized as collections of menu items in a menu
/// bar menu. On 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 primitive 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
}
/// Identifier types for standard locations that new command groups can be
/// placed relative to.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct CommandGroupPlacement {
/// Standard placement for commands that provide information about the app,
/// the terms of the user's license agreement, etc.
///
/// Includes the following by default on macOS:
/// * About App
public static let appInfo: CommandGroupPlacement
/// Standard placement for commands that expose app settings and
/// preferences.
///
/// Includes the following by default on macOS:
/// * Preferences
public static let appSettings: CommandGroupPlacement
/// Standard placement for commands that expose services provided by other
/// apps.
///
/// Includes the following by default on macOS:
/// * Services submenu (managed automatically)
public static let systemServices: CommandGroupPlacement
/// Standard placement for commands that control the visibility of running
/// apps.
///
/// Includes the following by default on macOS:
/// * Hide App
/// * Hide Others
/// * Show All
public static let appVisibility: CommandGroupPlacement
/// Standard placement for commands that result in app termination.
///
/// Includes the following by default on macOS:
/// * Quit App
public static let appTermination: CommandGroupPlacement
/// Standard placement for commands that create and open different kinds of
/// documents.
///
/// Includes the following by default on macOS:
/// * New
/// * Open
/// * Open Recent submenu (managed automatically)
public static let newItem: CommandGroupPlacement
/// Standard placement for commands that save open documents and close
/// windows.
///
/// Includes the following by default on macOS:
/// * Close
/// * Save
/// * Save As/Duplicate
/// * Revert to Saved
public static let saveItem: CommandGroupPlacement
/// Standard placement for commands that relate to importing and exporting
/// data using formats that the app doesn't natively support.
///
/// Empty by default on macOS.
public static let importExport: CommandGroupPlacement
/// Standard placement for commands related to printing app content.
///
/// Includes the following by default on macOS:
/// * Page Setup
/// * Print
public static let printItem: CommandGroupPlacement
/// Standard placement for commands that control the Undo Manager.
///
/// Includes the following by default on macOS:
/// * Undo
/// * Redo
public static let undoRedo: CommandGroupPlacement
/// Standard placement for commands that interact with the pasteboard and
/// manipulate content that is currently selected in the app's view
/// hierarchy.
///
/// Includes the following by default on macOS:
/// * Cut
/// * Copy
/// * Paste
/// * Paste and Match Style
/// * Delete
/// * Select All
public static let pasteboard: CommandGroupPlacement
/// Standard placement for commands that manipulate and transform text
/// selections.
///
/// Includes the following by default on macOS:
/// * Find submenu
/// * Spelling and Grammar submenu
/// * Substitutions submenu
/// * Transformations submenu
/// * Speech submenu
public static let textEditing: CommandGroupPlacement
/// Standard placement for commands that manipulate and transform the styles
/// applied to text selections.
///
/// Includes the following by default on macOS:
/// * Font submenu
/// * Text submenu
public static let textFormatting: CommandGroupPlacement
/// Standard placement for commands that manipulate the toolbar.
///
/// Includes the following by default on macOS:
/// * Show/Hide Toolbar
/// * Customize Toolbar
public static let toolbar: CommandGroupPlacement
/// Standard placement for commands that control the app's sidebar and full
/// screen modes.
///
/// Includes the following by default on macOS:
/// * Show/Hide Sidebar
/// * Enter/Exit Full Screen
public static let sidebar: CommandGroupPlacement
/// Standard placement for commands that control the size of the window.
///
/// Includes the following by default on macOS:
/// * Minimize
/// * Zoom
public static let windowSize: CommandGroupPlacement
/// Standard placement for commands that arrange all of an app's windows.
///
/// Includes the following by default on macOS:
/// * Bring All to Front
public static let windowArrangement: CommandGroupPlacement
/// Standard placement for commands that present documentation and helpful
/// information to the user.
///
/// Includes the following by default on 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 primitive 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 primitive 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 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<Content>(_ content: Content) -> Content where Content : 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.
///
/// Do not use this type directly. Instead, use ``DatePickerStyle/compact``.
@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()
}
/// 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
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ContainerRelativeShape : Sendable {
}
/// 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 {
case fit
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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ContentMode : Sendable {
}
@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")
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: Never call `finalize()` on `hasher`. 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.
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
}
extension ContentSizeCategory {
/// Create a size category from its UIContentSizeCategory equivalent.
@available(iOS 14.0, tvOS 14.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
public init?(_ uiSizeCategory: UIContentSizeCategory)
}
/// A container for views that you present as menu items in a contextual menu
/// after completion of the standard system gesture.
///
/// A context menu view allows you to present a situationally specific menu to
/// the user allowing them to perform actions relevant to the current task
/// they're performing in your app.
///
/// You create a context menu by first defining a `ContextMenu` container
/// with the buttons that will represent the actions the user can select
/// from. Next, you add a ``View/contextMenu(_:)`` view modifier to the view that
/// will enable the context menu. The context menu view modifier takes
/// the menu items you defined above as its argument.
///
/// The example below creates a four-item context menu container
/// used by the context menu view modifier. The Boolean value
/// `shouldShowMenu` controls the attachment of context menu; it is set to
/// `true`, enabling the contextual menu.
///
/// Note that it is possible to place the actions performed by the menu
/// selection directly inside the button closures or, as shown below, to invoke
/// them via function references.
///
/// func selectHearts() {
/// // Act on hearts selection.
/// }
/// func selectClubs() { ... }
/// func selectSpades() { ... }
/// func selectDiamonds() { ... }
///
/// let menuItems = ContextMenu {
/// Button("♥️ - Hearts", action: selectHearts)
/// Button("♣️ - Clubs", action: selectClubs)
/// Button("♠️ - Spades", action: selectSpades)
/// Button("♦️ - Diamonds", action: selectDiamonds)
/// }
///
/// struct ContextMenuMenuItems: View {
/// private var shouldShowMenu = true
/// var body: some View {
/// VStack {
/// Text("Favorite Card Suit")
/// .padding()
/// .contextMenu(shouldShowMenu ? menuItems : nil)
/// }
/// }
/// }
///
/// ![A screenshot of a context menu showing four menu items: Hearts, Clubs,
/// Spades and Diamonds.](SwiftUI-contextMenu.png)
///
@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)
public struct ContextMenu<MenuItems> where MenuItems : View {
public init(@ViewBuilder menuItems: () -> MenuItems)
}
/// A container view that displays semantically-related controls
/// in a visually-appropriate manner for the context
///
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@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 primitive 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>.
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, *)
@available(tvOS, unavailable)
@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)
}
/// 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, *)
@available(tvOS, unavailable)
@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 func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a `ControlGroup` instance being created.
typealias Configuration = ControlGroupStyleConfiguration
}
@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 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@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 }
}
/// The properties of a control group.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@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
}
/// The size classes, like regular or small, that you can apply to controls
/// within a view.
@available(iOS 15.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public enum ControlSize : CaseIterable {
/// 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
/// 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
@available(iOS 15.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ControlSize : Equatable {
}
@available(iOS 15.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ControlSize : Hashable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum CoordinateSpace {
case global
case local
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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
/// 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 {
}
/// 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, *)
@available(tvOS, unavailable)
@available(watchOS, 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 primitive 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>.
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, *)
@available(tvOS, unavailable)
@available(watchOS, 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]`.
/// - label: A view that describes the use of the date.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
/// - label: A view that describes the use of the date.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
/// - label: A view that describes the use of the date.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
/// - label: A view that describes the use of the date.
@available(tvOS, unavailable)
@available(watchOS, 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, *)
@available(tvOS, unavailable)
@available(watchOS, 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]`.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
@available(tvOS, unavailable)
@available(watchOS, 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]`.
@available(tvOS, unavailable)
@available(watchOS, 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, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DatePickerComponents : 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: 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.
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public protocol DatePickerStyle {
}
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DatePickerStyle where Self == DefaultDatePickerStyle {
/// The default style for date pickers.
public static var automatic: DefaultDatePickerStyle { 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 13.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension DatePickerStyle where Self == WheelDatePickerStyle {
/// A date picker style that displays each component as columns in a
/// scrollable wheel.
public static var wheel: WheelDatePickerStyle { 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 default button style, based on the button's context.
///
/// Do not use this type directly. Instead, use
/// ``PrimitiveButtonStyle/automatic``.
@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 control group style.
///
/// Do not use this type directly. Instead, use ``ControlGroupStyle/automatic``.
@available(iOS, deprecated, renamed: "AutomaticControlGroupStyle")
@available(macOS, introduced: 12.0, deprecated: 12.0, renamed: "AutomaticControlGroupStyle")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DefaultControlGroupStyle : ControlGroupStyle {
/// Creates a default 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`.
public func makeBody(configuration: DefaultControlGroupStyle.Configuration) -> some View
/// A view representing the body of a control group.
public typealias Body = some View
}
/// The default style for date pickers.
///
/// Do not use this type directly. Instead, use ``DatePickerStyle/automatic``.
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DefaultDatePickerStyle : DatePickerStyle {
/// Creates an instance of the default date picker style.
public init()
}
/// The default style for group box views.
///
/// Do not use this type directly. Instead, use ``GroupBoxStyle/automatic``.
@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.
///
/// Do not use this type directly. Instead, use ``LabelStyle/automatic``.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct DefaultLabelStyle : LabelStyle {
/// Creates a default 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.
///
/// Do not use this type directly. Instead, use ``ListStyle/automatic``.
@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 style, based on the menu's context.
///
/// Do not use this type directly. Instead, use ``MenuStyle/automatic``.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@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.
///
/// Do not use this type directly. Instead, use
/// ``NavigationViewStyle/automatic``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
public struct DefaultNavigationViewStyle : NavigationViewStyle {
public init()
}
/// The default picker style, based on the picker's context.
///
/// Do not use this type directly. Instead, use ``PickerStyle/automatic``.
@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.
///
/// Do not use this type directly. Instead, use ``ProgressViewStyle/automatic``.
@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 `TabView` style.
///
/// Do not use this type directly. Instead, use ``TabViewStyle/automatic``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
public struct DefaultTabViewStyle : TabViewStyle {
public init()
}
/// The default text field style, based on the text field's context.
///
/// Do not use this type directly. Instead, use ``TextFieldStyle/automatic``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct DefaultTextFieldStyle : TextFieldStyle {
public init()
}
/// The default toggle style.
///
/// Do not use this type directly. Instead, use ``ToggleStyle/automatic``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct DefaultToggleStyle : ToggleStyle {
/// Creates a default toggle style.
public init()
/// Creates a view that represents the body of a toggle.
///
/// The system calls this method for each ``Toggle`` instance in a view
/// hierarchy where this style is the current toggle style.
///
/// - Parameter configuration: The properties of the toggle.
public func makeBody(configuration: DefaultToggleStyle.Configuration) -> some View
/// A view that represents the appearance and interaction of a toggle.
public typealias Body = some View
}
/// Disables text selection by the user.
///
/// Do not 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 {
/// Whether text allows selection or not.
///
/// This should produce a constant value that is not affected 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 primitive 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>.
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
}
/// Provides functionality for dismissing a presentation.
///
/// The `DismissAction` instance in the app's ``Environment`` offers a handler
/// that you can use to dismiss a presentation. The action has no effect if the
/// view is not currently being presented. You can use
/// ``EnvironmentValues/isPresented`` to query whether the view is currently
/// being presented.
///
/// Use the ``EnvironmentValues/dismiss`` environment value to get the handler.
/// Then call the action's handler to perform the dismissal. For example,
/// you can use the action to add a done button to a sheet's toolbar:
///
/// struct SheetView: View {
/// @Environment(\.dismiss) var dismiss
///
/// var body: some View {
/// NavigationView {
/// SheetContents()
/// .toolbar {
/// Button("Done") {
/// dismiss()
/// }
/// }
/// }
/// }
/// }
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct DismissAction {
/// Dismisses the view if it is currently presented.
///
/// Use this method to attempt to dismiss a presentation. This function
/// is used when you call the function ``dismiss()``.
public func callAsFunction()
}
/// Provides functionality for dismissing a search interaction.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct DismissSearchAction {
/// Requests the current view hierarchy to end searching.
public func callAsFunction()
}
/// 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
}
/// 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. In 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)
/// }
/// }
/// }
///
/// 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)
/// }
/// }
/// }
///
/// 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)
/// }
/// }
/// }
///
@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 primitive 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.
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 : 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. In 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)
}
@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)
}
/// A navigation view style represented by a primary view stack that
/// navigates to a detail view.
@available(iOS, introduced: 13.0, deprecated: 100000, message: "Use NavigationViewStyle.columns")
@available(macOS, introduced: 10.15, deprecated: 100000, message: "Use NavigationViewStyle.columns")
@available(tvOS, introduced: 13.0, deprecated: 100000, message: "Use NavigationViewStyle.stack")
@available(watchOS, unavailable)
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 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 {
/// 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 }
/// 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.
public init(minimumDistance: CGFloat = 10, coordinateSpace: CoordinateSpace = .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)
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`.
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.
func performDrop(info: DropInfo) -> Bool
/// Tells the delegate a validated drop has entered the modified view.
///
/// The default implementation does nothing.
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``.
func dropUpdated(info: DropInfo) -> DropProposal?
/// Tells the delegate a validated drop operation has exited the modified
/// view.
///
/// The default implementation does nothing.
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`.
public func validateDrop(info: DropInfo) -> Bool
/// Tells the delegate a validated drop has entered the modified view.
///
/// The default implementation does nothing.
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``.
public func dropUpdated(info: DropInfo) -> DropProposal?
/// Tells the delegate a validated drop operation has exited the modified
/// view.
///
/// The default implementation does nothing.
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)
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 {
/// 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: Never call `finalize()` on `hasher`. 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.
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 {
/// 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 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 {
/// 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
extension DynamicTypeSize {
/// Create a Dynamic Type size from its `UIContentSizeCategory` equivalent.
@available(iOS 15.0, tvOS 15.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
public init?(_ uiSizeCategory: UIContentSizeCategory)
}
/// 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 }
}
@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
}
@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 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.")
public func onInsert(of acceptedTypeIdentifiers: [String], perform action: @escaping (Int, [NSItemProvider]) -> 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 button that toggles the edit mode for the current edit scope.
///
/// An Edit button toggles the ``EditMode`` for content within a container that
/// supports ``EditMode/active``. In the following example, an `EditButton`
/// placed inside a ``NavigationView`` supports editing of a ``List``:
///
/// @State private var fruits = [
/// "Apple",
/// "Banana",
/// "Papaya",
/// "Mango"
/// ]
///
/// var body: some View {
/// NavigationView{
/// List {
/// ForEach(
/// fruits,
/// id: \.self
/// ) { fruit in
/// Text(fruit)
/// }
/// .onDelete { self.deleteFruit(at :$0) }
/// .onMove { self.moveFruit(from: $0, to: $1) }
/// }
/// .navigationTitle("Fruits")
/// .toolbar { EditButton() }
/// }
/// }
///
/// Because the list defines behaviors for
/// ``DynamicViewContent/onDelete(perform:)`` and
/// ``DynamicViewContent/onMove(perform:)``, the editable list displays the
/// delete and move UI when the user taps Edit, as seen in the
/// following screenshot. Also notice that the Edit button displays the title
/// "Done", because the list is in editing mode.
///
/// ![A screenshot of an app with an navigation with an EditButton as its
/// right-side button, labeled Done to indicate it is active. Below the
/// navigation, a list labeled Fruits contains four members, each showing
/// its delete and move user interface
/// elements.](SwiftUI-EditButton-editingList.png)
///
@available(iOS 13.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct EditButton : View {
/// Creates an Edit button instance.
public init()
/// 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 primitive 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>.
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 mode of a view indicating whether the user can edit its content.
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
public enum EditMode {
/// The view content cannot be edited.
case inactive
/// The view is in a temporary edit mode.
///
/// The definition of temporary might vary by platform or specific control.
/// As an example, temporary edit mode may be engaged over the duration of a
/// swipe gesture.
case transient
/// The view content can be edited.
case active
/// Indicates whether a view is being edited.
public var isEditing: 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: EditMode, b: EditMode) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
extension EditMode : Equatable {
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
extension EditMode : Hashable {
}
/// 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
@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 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
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Ellipse : Sendable {
}
/// 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:)``.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public struct EllipticalGradient : ShapeStyle, View {
/// 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
}
/// 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.
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 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 {
}
/// An empty widget configuration.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, 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, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension EmptyWidgetConfiguration : Sendable {
}
/// Enables text selection by the user.
///
/// Do not 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 {
/// Whether text allows selection or not.
///
/// This should produce a constant value that is not affected 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 }
}
/// 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 value".
/// }
/// }
///
@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 supplied by a parent or
/// ancestor view.
///
/// An environment object invalidates the current view whenever the observable
/// object 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.
@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.
@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.
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(_:)`` 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 {
/// 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 13.0, macOS 10.15, tvOS 13.0, watchOS 8.0, *)
public var disableAutocorrection: Bool?
}
@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
}
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")
public var sizeCategory: ContentSizeCategory
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
public var managedObjectContext: NSManagedObjectContext
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
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`.
public var undoManager: UndoManager? { get }
}
@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 whether the environment uses a left-to-right
/// or right-to-left orientation.
public var layoutDirection: LayoutDirection
}
@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 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 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The prominence to apply to controls within a view.
///
/// The default is ``Prominence/standard``.
public var controlProminence: Prominence
/// The prominence to apply to section headers within a view.
///
/// The default is ``Prominence/standard``.
public var headerProminence: Prominence
}
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// The menu indicator visibility to apply to controls within a view.
public var menuIndicatorVisibility: Visibility
}
@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
}
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 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
}
@available(iOS 13.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// The horizontal size class of this environment.
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public var horizontalSizeClass: UserInterfaceSizeClass?
/// The vertical size class of this environment.
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public var verticalSizeClass: UserInterfaceSizeClass?
}
@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(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 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 }
}
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.
///
/// On macOS, this value cannot be changed by users and does not affect the
/// text size.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public var dynamicTypeSize: DynamicTypeSize
}
@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?
}
extension EnvironmentValues {
/// Whether the user is currently interacting with a search field that has
/// been placed by a surrounding searchable modifier.
///
/// struct ContentView: View {
/// @State var text = ""
///
/// var body: some View {
/// SearchReadingView()
/// .searchable(text: $text)
/// }
/// }
///
/// struct SearchReadingView: View {
/// @Environment(\.isSearching) var isSearching
///
/// var body: some View {
/// if isSearching {
/// Text("Searching!")
/// } else {
/// Text("Not searching.")
/// }
/// }
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public var isSearching: Bool { get }
/// Asks the system to dismiss the current search interaction.
///
/// When able, this will cause ``EnvironmentValues/isSearching`` to
/// become false, any search text to be cleared, and the search field to
/// lose focus.
///
/// NavigationView {
/// MyList()
/// .searchable(text: $text)
/// }
///
/// struct MyList: View {
/// @State private var isPresented = false
/// @Environment(\.isSearching) private var isSearching
///
/// var body: some View {
/// Text("Main List")
/// .frame(maxWidth: .infinity, maxHeight: .infinity)
/// .overlay {
/// if isSearching {
/// Button {
/// isPresented = true
/// } label: {
/// Text("Present")
/// .frame(
/// maxWidth: .infinity,
/// maxHeight: .infinity
/// )
/// .background()
/// }
/// .sheet(isPresented: $isPresented) {
/// NavigationView {
/// DetailView()
/// }
/// }
/// }
/// }
/// }
/// }
///
/// struct DetailView: View {
/// @Environment(\.dismiss) private var dismiss
/// @Environment(\.dismissSearch) private var dismissSearch
///
/// var body: some View {
/// Text("Detail Content")
/// .toolbar {
/// Button("Add") {
/// dismiss()
/// dismissSearch()
/// }
/// }
/// }
/// }
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public var dismissSearch: DismissSearchAction { 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.
///
/// If you design a custom view that can support a refresh operation,
/// like a view that displays a collection of model objects stored on a server,
/// use the existence of an action in the view's environment
/// to change the view's appearance and behavior to provide
/// a way for the user to initiate the refresh action. An action of `nil`
/// indicates that the view doesn't need to support refresh.
///
/// Set a value for this action on a view using the
/// ``View/refreshable(action:)`` modifier.
public var refresh: RefreshAction? { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension EnvironmentValues {
/// Opens a URL using the appropriate system service.
public var openURL: OpenURLAction { get }
}
@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 }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// Dismisses the current presentation.
public var dismiss: DismissAction { get }
/// A Boolean value that indicates whether the view associated with this
/// environment is currently being presented.
public var isPresented: Bool { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// A value that indicates how text instance aligns its lines when the
/// content wraps or contains newlines.
///
/// Use alignment parameters on a parent view to align ``Text`` with respect
/// to its parent. Because the horizontal bounds of ``TextField`` never
/// exceed its graphical extent, this value has little to no effect on
/// single-line text.
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``.
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 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`.
public var lineLimit: Int?
/// 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?
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// The mode indicating whether the user can edit the contents of a view
/// associated with this environment.
@available(macOS, unavailable)
@available(watchOS, unavailable)
public var editMode: Binding<EditMode>?
}
@available(iOS 15.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// The size to apply to controls within a view.
///
/// The default is ``ControlSize/regular``.
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public var controlSize: ControlSize
}
@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")
public var presentationMode: Binding<PresentationMode> { get }
}
extension EnvironmentValues {
/// The color scheme of this environment.
///
/// When writing custom drawing code that depends on the current color
/// scheme, you should also consider the
/// ``EnvironmentValues/colorSchemeContrast`` property. You can specify
/// images and colors in asset catalogs according to either the
/// ``ColorScheme/light`` or ``ColorScheme/dark`` color scheme, as well as
/// standard or increased contrast. The correct image or color displays
/// automatically for the current environment.
///
/// You only need to check `colorScheme` and
/// ``EnvironmentValues/colorSchemeContrast`` for custom drawing if the
/// differences go beyond images and colors.
///
/// Setting the `colorScheme` environment value directly is an advanced use
/// case, as it changes the color scheme of the contained views but *not* of
/// the container. Instead, consider using the
/// ``View/preferredColorScheme(_:)`` modifier, which propagates to the
/// presentation containing the view.
public var colorScheme: ColorScheme
/// The contrast associated with the color scheme of this environment.
public var colorSchemeContrast: ColorSchemeContrast { 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?
}
/// 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")
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.
///
/// Do not use this type directly. Instead, use
/// ``TimelineSchedule/everyMinute``.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct EveryMinuteTimelineSchedule : TimelineSchedule {
/// 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 {
/// 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.
@available(iOS, introduced: 15.0, deprecated: 15.0, message: "Use `.everyMinute` instead.")
@available(macOS, introduced: 12.0, deprecated: 12.0, message: "Use `.everyMinute` instead.")
@available(tvOS, introduced: 15.0, deprecated: 15.0, message: "Use `.everyMinute` instead.")
@available(watchOS, introduced: 8.0, deprecated: 8.0, message: "Use `.everyMinute` instead.")
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 : 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 schedule for updating a timeline view at explicit points in time.
///
/// Do not use this type directly. Instead, use
/// ``TimelineSchedule/explicit(_:)``.
@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.
@available(iOS, introduced: 15.0, deprecated: 15.0, message: "Use `.explicit(_:)` instead.")
@available(macOS, introduced: 12.0, deprecated: 12.0, message: "Use `.explicit(_:)` instead.")
@available(tvOS, introduced: 15.0, deprecated: 15.0, message: "Use `.explicit(_:)` instead.")
@available(watchOS, introduced: 8.0, deprecated: 8.0, message: "Use `.explicit(_:)` instead.")
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 makes fetch requests and retrieves the results
/// from a Core Data store.
///
/// The fetch request and its results use the managed object context provided by
/// the environment value ``EnvironmentValues/managedObjectContext``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper public struct FetchRequest<Result> where Result : NSFetchRequestResult {
/// The fetched results of the fetch request.
///
/// This property returns an empty array when there are no fetched results.
public var wrappedValue: FetchedResults<Result> { get }
/// The request's configurable properties.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct Configuration {
/// The request's sort descriptors.
public var nsSortDescriptors: [NSSortDescriptor]
/// The request's predicate.
public var nsPredicate: NSPredicate?
}
/// A binding to the request's mutable configuration properties
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
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.
public mutating func update()
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension FetchRequest {
/// Creates an instance by defining a fetch request based on the parameters.
/// - Parameters:
/// - entity: The kind of modeled object to fetch.
/// - sortDescriptors: An array of sort descriptors defines the sort
/// order of the fetched results.
/// - predicate: An NSPredicate defines a filter for the fetched results.
/// - animation: The animation used for any changes to the fetched
/// results.
public init(entity: NSEntityDescription, sortDescriptors: [NSSortDescriptor], predicate: NSPredicate? = nil, animation: Animation? = nil)
/// Creates an instance from a fetch request.
/// - Parameters:
/// - fetchRequest: The request used to produce the fetched results.
/// - animation: The animation used for any changes to the fetched
/// results.
public init(fetchRequest: NSFetchRequest<Result>, animation: Animation? = nil)
/// Creates an instance from a fetch request.
/// - Parameters:
/// - fetchRequest: The request used to produce the fetched results.
/// - transaction: The transaction used for any changes to the fetched
/// results.
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 an instance by defining a fetch request based on the parameters.
/// The fetch request will automatically infer the entity using Result.entity() at fetch-time.
/// - Parameters:
/// - sortDescriptors: An array of sort descriptors defines the sort
/// order of the fetched results.
/// - predicate: An NSPredicate defines a filter for the fetched results.
/// - animation: The animation used for any changes to the fetched
/// results.
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 an instance by defining a fetch request based on the parameters.
///
/// The fetch request will automatically infer the entity using Result.entity() at fetch-time.
/// - Parameters:
/// - sortDescriptors: An array of sort descriptors defines the sort
/// order of the fetched results.
/// - predicate: An NSPredicate defines a filter for the fetched results.
/// - animation: The animation used for any changes to the fetched
/// results.
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 {
public var sortDescriptors: [SortDescriptor<Result>]
}
/// The FetchedResults collection type represents the results of performing a
/// fetch request. Internally, it may use strategies such as batching and
/// transparent futures to minimize memory use and I/O.
@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.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public var nsSortDescriptors: [NSSortDescriptor] { get nonmutating set }
/// The request's predicate.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public var nsPredicate: NSPredicate? { get nonmutating set }
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
public var startIndex: Int { 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: Int { get }
/// 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: 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 sequence that represents a contiguous subrange of the collection's
/// elements.
///
/// This associated type appears as a requirement in the `Sequence`
/// protocol, but it is restated here with stricter constraints. In a
/// collection, the subsequence should also conform to `Collection`.
public typealias SubSequence = Slice<FetchedResults<Result>>
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension FetchedResults where Result : NSManagedObject {
public var sortDescriptors: [SortDescriptor<Result>] { get nonmutating set }
}
/// A document model definition used to serialize documents to and from file
/// contents.
///
/// Conformance to `FileDocument` requires value semantics and thread-safety.
/// Serialization and deserialization occur on a background thread.
///
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public protocol FileDocument {
/// The types the document is able to open.
static var readableContentTypes: [UTType] { get }
/// The types the document is able to save or export to.
///
/// If you don't implement this property, the protocol returns
/// the value in ``readableContentTypes`` by default.
static var writableContentTypes: [UTType] { get }
/// Creates a file document from the given configuration.
init(configuration: Self.ReadConfiguration) throws
/// The configuration for reading document contents.
typealias ReadConfiguration = FileDocumentReadConfiguration
/// Serializes the document to file contents for a specified configuration.
///
/// - Parameter configuration: The configuration for the current document
/// contents.
///
/// - 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 updated file wrapper of the one provided in `configuration`.
func fileWrapper(configuration: Self.WriteConfiguration) throws -> FileWrapper
/// The configuration for serializing document contents.
typealias WriteConfiguration = FileDocumentWriteConfiguration
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension FileDocument {
/// The types the document is able to save or export to.
///
/// If you don't implement this property, the protocol returns
/// the value in ``readableContentTypes`` by default.
public static var writableContentTypes: [UTType] { get }
}
/// The properties of an open file document.
@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 won't have an effect
/// and the document is in viewing mode.
public var document: Document { get nonmutating set }
public var $document: Binding<Document> { get }
/// The URL of the open file document.
public var fileURL: URL?
/// Whether the document is editable.
///
/// 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 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 {
}
/// 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.
@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 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 }
}
/// A protocol for identifier types used when publishing and observing focused
/// values.
///
/// Unlike `EnvironmentKey`, `FocusedValuesHostKey` 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 {
/// 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: Never call `finalize()` on `hasher`. 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.
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 with the given style and design.
public static func system(_ style: Font.TextStyle, design: Font.Design = .default) -> Font
/// A dynamic text style to use for fonts.
public enum TextStyle : CaseIterable {
/// 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: Never call `finalize()` on `hasher`. 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.
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
/// Adjusts the font to use monospace digits.
public func monospacedDigit() -> Font
/// Sets the weight of the font.
public func weight(_ weight: Font.Weight) -> Font
/// Adds bold styling to the font.
public func bold() -> Font
/// Switches the font to a monospaced version of the same family
/// as the base font or a default monospaced font
/// if no suitable font face in the same family is found.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public func monospaced() -> Font
/// Create a version of `self` that uses leading (line spacing) adjustment.
///
/// The availability of leading adjustments depends on font.
///
/// For example, `Font.body.tightLeading()` will return a `Font` in `body`
/// text style with tight line spacing. This modifier may return the
/// original `Font` unchanged for some fonts.
@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
/// 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
/// 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public enum Leading {
case standard
case tight
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: Never call `finalize()` on `hasher`. 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.
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))
///
/// 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))
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 {
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: Never call `finalize()` on `hasher`. 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.
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 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 }
}
@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 {
/// The type for the internal content of this `AccessibilityRotorContent`.
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.
/// - 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)
}
/// The foreground style in the current context.
///
/// Do not use this type directly. Instead, use ``ShapeStyle/foreground``.
@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()
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForegroundStyle : Sendable {
}
/// 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 primitive 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>.
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 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.
public func frame(in coordinateSpace: CoordinateSpace) -> 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 {
/// 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 {
/// 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(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 users cancels or ends the gesture.
@inlinable public func updating<State>(_ state: GestureState<State>, body: @escaping (Self.Value, inout State, inout Transaction) -> Void) -> GestureStateGesture<Self, State>
}
/// Options that control how adding a gesture to a view affect's 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 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 (GestureStateGesture<Base, State>.Value, inout State, inout Transaction) -> Void)
/// The type of gesture representing the body of `Self`.
public typealias Body = Never
}
/// A color gradient represented as an array of color stops, each having a
/// parametric location value.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Gradient : Equatable {
/// One color stop in the gradient.
@frozen public struct Stop : Equatable {
/// The color for the stop.
public var color: Color
/// The parametric location of the stop.
///
/// This value must be in the range `[0, 1]`.
public var location: CGFloat
/// Creates a color stop with a color and location.
public init(color: Color, location: CGFloat)
/// 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: Gradient.Stop, b: Gradient.Stop) -> Bool
}
/// The array of color stops.
public var stops: [Gradient.Stop]
/// Creates a gradient from an array of color stops.
public init(stops: [Gradient.Stop])
/// Creates a gradient from an array of colors.
///
/// The gradient synthesizes its location values to evenly space the colors
/// along the gradient.
public init(colors: [Color])
/// 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: Gradient, b: Gradient) -> Bool
}
/// A date picker style that displays an interactive calendar or clock.
///
/// Do not use this type directly. Instead, use ``DatePickerStyle/graphical``.
@available(iOS 14.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct GraphicalDatePickerStyle : DatePickerStyle {
/// Creates an instance of the graphical date picker style.
public init()
}
/// An immediate mode drawing destination, and its current state.
///
/// Use a context to execute 2D drawing primitives. For example, you can draw
/// filled shapes using the ``fill(_:with:style:)`` method inside a ``Canvas``
/// view:
///
/// Canvas { context, size in
/// context.fill(
/// Path(ellipseIn: CGRect(origin: .zero, size: size)),
/// with: .color(.green))
/// }
/// .frame(width: 300, height: 200)
///
/// The example above draws an ellipse that just fits inside a canvas that's
/// constrained to 300 points wide and 200 points tall:
///
/// ![A screenshot of a view that shows a green ellipse.](GraphicsContext-1)
///
/// In addition to outlining or filling paths, you can draw images, text,
/// and SwiftUI views. You can also use the context to perform many common
/// graphical operations, like adding masks, applying filters and
/// transforms, and setting a blend mode. For example you can add
/// a mask using the ``clip(to:style:options:)`` method:
///
/// let halfSize = size.applying(CGAffineTransform(scaleX: 0.5, y: 0.5))
/// context.clip(to: Path(CGRect(origin: .zero, size: halfSize)))
/// context.fill(
/// Path(ellipseIn: CGRect(origin: .zero, size: size)),
/// with: .color(.green))
///
/// The rectangular mask hides all but one quadrant of the ellipse:
///
/// ![A screenshot of a view that shows the upper left quarter of a green
/// ellipse.](GraphicsContext-2)
///
/// The order of operations matters. Changes that you make to the state of
/// the context, like adding a mask or a filter, apply to later
/// drawing operations. If you reverse the fill and clip operations in
/// the example above, so that the fill comes first, the mask doesn't
/// affect the ellipse.
///
/// Each context references a particular layer in a tree of transparency layers,
/// and also contains a full copy of the drawing state. You can modify the
/// state of one context without affecting the state of any other, even if
/// they refer to the same layer. For example you can draw the masked ellipse
/// from the previous example into a copy of the main context, and then add a
/// rectangle into the main context:
///
/// // Create a copy of the context to draw a clipped ellipse.
/// var maskedContext = context
/// let halfSize = size.applying(CGAffineTransform(scaleX: 0.5, y: 0.5))
/// maskedContext.clip(to: Path(CGRect(origin: .zero, size: halfSize)))
/// maskedContext.fill(
/// Path(ellipseIn: CGRect(origin: .zero, size: size)),
/// with: .color(.green))
///
/// // Go back to the original context to draw the rectangle.
/// let origin = CGPoint(x: size.width / 4, y: size.height / 4)
/// context.fill(
/// Path(CGRect(origin: origin, size: halfSize)),
/// with: .color(.blue))
///
/// The mask doesn't clip the rectangle because the mask isn't part of the
/// main context. However, both contexts draw into the same view because
/// you created one context as a copy of the other:
///
/// ![A screenshot of a view that shows the upper left quarter of a green
/// ellipse, overlaid by a blue rectangle centered in the
/// view.](GraphicsContext-3)
///
/// The context has access to an ``EnvironmentValues`` instance called
/// ``environment`` that's initially copied from the environment of its
/// enclosing view. SwiftUI uses environment values --- like the display
/// resolution and color scheme --- to resolve types like ``Image`` and
/// ``Color`` that appear in the context. You can also access values stored
/// in the environment for your own purposes.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public struct GraphicsContext {
/// The ways that a graphics context combines new content with background
/// content.
///
/// Use one of these values to set the
/// ``GraphicsContext/blendMode-swift.property`` property of a
/// ``GraphicsContext``. The value that you set affects how content
/// that you draw replaces or combines with content that you
/// previously drew into the context.
///
@frozen public struct BlendMode : RawRepresentable, Equatable {
/// 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: Int32
/// 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.
@inlinable public init(rawValue: Int32)
/// A mode that paints source image samples over the background image
/// samples.
///
/// This is the default blend mode.
@inlinable public static var normal: GraphicsContext.BlendMode { get }
/// A mode that multiplies the source image samples with the background
/// image samples.
///
/// Drawing in this mode results in colors that are at least as
/// dark as either of the two contributing sample colors.
@inlinable public static var multiply: GraphicsContext.BlendMode { get }
/// A mode that multiplies the inverse of the source image samples with
/// the inverse of the background image samples.
///
/// Drawing in this mode results in colors that are at least as light
/// as either of the two contributing sample colors.
@inlinable public static var screen: GraphicsContext.BlendMode { get }
/// A mode that either multiplies or screens the source image samples
/// with the background image samples, depending on the background
/// color.
///
/// Drawing in this mode overlays the existing image samples
/// while preserving the highlights and shadows of the
/// background. The background color mixes with the source
/// image to reflect the lightness or darkness of the
/// background.
@inlinable public static var overlay: GraphicsContext.BlendMode { get }
/// A mode that creates composite image samples by choosing the darker
/// samples from either the source image or the background.
///
/// When you draw in this mode, source image samples that are darker
/// than the background replace the background.
/// Otherwise, the background image samples remain unchanged.
@inlinable public static var darken: GraphicsContext.BlendMode { get }
/// A mode that creates composite image samples by choosing the lighter
/// samples from either the source image or the background.
///
/// When you draw in this mode, source image samples that are lighter
/// than the background replace the background.
/// Otherwise, the background image samples remain unchanged.
@inlinable public static var lighten: GraphicsContext.BlendMode { get }
/// A mode that brightens the background image samples to reflect the
/// source image samples.
///
/// Source image sample values that
/// specify black do not produce a change.
@inlinable public static var colorDodge: GraphicsContext.BlendMode { get }
/// A mode that darkens background image samples to reflect the source
/// image samples.
///
/// Source image sample values that specify
/// white do not produce a change.
@inlinable public static var colorBurn: GraphicsContext.BlendMode { get }
/// A mode that either darkens or lightens colors, depending on the
/// source image sample color.
///
/// If the source image sample color is
/// lighter than 50% gray, the background is lightened, similar
/// to dodging. If the source image sample color is darker than
/// 50% gray, the background is darkened, similar to burning.
/// If the source image sample color is equal to 50% gray, the
/// background is not changed. Image samples that are equal to
/// pure black or pure white produce darker or lighter areas,
/// but do not result in pure black or white. The overall
/// effect is similar to what you'd achieve by shining a
/// diffuse spotlight on the source image. Use this to add
/// highlights to a scene.
@inlinable public static var softLight: GraphicsContext.BlendMode { get }
/// A mode that either multiplies or screens colors, depending on the
/// source image sample color.
///
/// If the source image sample color
/// is lighter than 50% gray, the background is lightened,
/// similar to screening. If the source image sample color is
/// darker than 50% gray, the background is darkened, similar
/// to multiplying. If the source image sample color is equal
/// to 50% gray, the source image is not changed. Image samples
/// that are equal to pure black or pure white result in pure
/// black or white. The overall effect is similar to what you'd
/// achieve by shining a harsh spotlight on the source image.
/// Use this to add highlights to a scene.
@inlinable public static var hardLight: GraphicsContext.BlendMode { get }
/// A mode that subtracts the brighter of the source image sample color
/// or the background image sample color from the other.
///
/// Source image sample values that are black produce no change; white
/// inverts the background color values.
@inlinable public static var difference: GraphicsContext.BlendMode { get }
/// A mode that produces an effect similar to that produced by the
/// difference blend mode, but with lower contrast.
///
/// Source image sample values that are black don't produce a change;
/// white inverts the background color values.
@inlinable public static var exclusion: GraphicsContext.BlendMode { get }
/// A mode that uses the luminance and saturation values of the
/// background with the hue of the source image.
@inlinable public static var hue: GraphicsContext.BlendMode { get }
/// A mode that uses the luminance and hue values of the background with
/// the saturation of the source image.
///
/// Areas of the background that have no saturation --- namely,
/// pure gray areas --- don't produce a change.
@inlinable public static var saturation: GraphicsContext.BlendMode { get }
/// A mode that uses the luminance values of the background with the hue
/// and saturation values of the source image.
///
/// This mode preserves the gray levels in the image. You can use this
/// mode to color monochrome images or to tint color images.
@inlinable public static var color: GraphicsContext.BlendMode { get }
/// A mode that uses the hue and saturation of the background with the
/// luminance of the source image.
///
/// This mode creates an effect that is inverse to the effect created
/// by the ``color`` mode.
@inlinable public static var luminosity: GraphicsContext.BlendMode { get }
/// A mode that clears any pixels that the source image overwrites.
///
/// With this mode, you can use the source image like an eraser.
///
/// This mode implements the equation `R = 0` where
/// `R` is the composite image.
@inlinable public static var clear: GraphicsContext.BlendMode { get }
/// A mode that replaces background image samples with source image
/// samples.
///
/// Unlike the ``normal`` mode, the source image completely replaces
/// the background, so that even transparent pixels in the source image
/// replace opaque pixels in the background, rather than letting the
/// background show through.
///
/// This mode implements the equation `R = S` where
/// * `R` is the composite image.
/// * `S` is the source image.
@inlinable public static var copy: GraphicsContext.BlendMode { get }
/// A mode that you use to paint the source image, including
/// its transparency, onto the opaque parts of the background.
///
/// This mode implements the equation `R = S*Da` where
/// * `R` is the composite image.
/// * `S` is the source image.
/// * `Da` is the source background's alpha value.
@inlinable public static var sourceIn: GraphicsContext.BlendMode { get }
/// A mode that you use to paint the source image onto the
/// transparent parts of the background, while erasing the background.
///
/// This mode implements the equation `R = S*(1 - Da)` where
/// * `R` is the composite image.
/// * `S` is the source image.
/// * `Da` is the source background's alpha value.
@inlinable public static var sourceOut: GraphicsContext.BlendMode { get }
/// A mode that you use to paint the opaque parts of the
/// source image onto the opaque parts of the background.
///
/// This mode implements the equation `R = S*Da + D*(1 - Sa)` where
/// * `R` is the composite image.
/// * `S` is the source image.
/// * `D` is the background.
/// * `Sa` is the source image's alpha value.
/// * `Da` is the source background's alpha value.
@inlinable public static var sourceAtop: GraphicsContext.BlendMode { get }
/// A mode that you use to paint the source image under
/// the background.
///
/// This mode implements the equation `R = S*(1 - Da) + D` where
/// * `R` is the composite image.
/// * `S` is the source image.
/// * `D` is the background.
/// * `Da` is the source background's alpha value.
@inlinable public static var destinationOver: GraphicsContext.BlendMode { get }
/// A mode that you use to erase any of the background that
/// isn't covered by opaque source pixels.
///
/// This mode implements the equation `R = D*Sa` where
/// * `R` is the composite image.
/// * `S` is the source image.
/// * `Da` is the source background's alpha value.
@inlinable public static var destinationIn: GraphicsContext.BlendMode { get }
/// A mode that you use to erase any of the background that
/// is covered by opaque source pixels.
///
/// This mode implements the equation `R = D*(1 - Sa)` where
/// * `R` is the composite image.
/// * `D` is the background.
/// * `Sa` is the source image's alpha value.
@inlinable public static var destinationOut: GraphicsContext.BlendMode { get }
/// A mode that you use to paint the source image under
/// the background, while erasing any of the background not matched
/// by opaque pixels from the source image.
///
/// This mode implements the equation `R = S*(1 - Da) + D*Sa` where
/// * `R` is the composite image.
/// * `S` is the source image.
/// * `D` is the background.
/// * `Sa` is the source image's alpha value.
/// * `Da` is the source background's alpha value.
@inlinable public static var destinationAtop: GraphicsContext.BlendMode { get }
/// A mode that you use to clear pixels where both the source and
/// background images are opaque.
///
/// This mode implements the equation `R = S*(1 - Da) + D*(1 - Sa)` where
/// * `R` is the composite image.
/// * `S` is the source image.
/// * `D` is the background.
/// * `Sa` is the source image's alpha value.
/// * `Da` is the source background's alpha value.
///
/// This XOR mode is only nominally related to the classical bitmap
/// XOR operation, which SwiftUI doesn't support.
@inlinable public static var xor: GraphicsContext.BlendMode { get }
/// A mode that adds the inverse of the color components of the source
/// and background images, and then inverts the result, producing
/// a darkened composite.
///
/// This mode implements the equation `R = MAX(0, 1 - ((1 - D) + (1 - S)))` where
/// * `R` is the composite image.
/// * `S` is the source image.
/// * `D` is the background.
@inlinable public static var plusDarker: GraphicsContext.BlendMode { get }
/// A mode that adds the components of the source and background images,
/// resulting in a lightened composite.
///
/// This mode implements the equation `R = MIN(1, S + D)` where
/// * `R` is the composite image.
/// * `S` is the source image.
/// * `D` is the background.
@inlinable public static var plusLighter: GraphicsContext.BlendMode { get }
/// 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 = Int32
}
/// The opacity of drawing operations in the context.
///
/// Set this value to affect the opacity of content that you subsequently
/// draw into the context. Changing this value has no impact on the
/// content you previously drew into the context.
public var opacity: Double
/// The blend mode used by drawing operations in the context.
///
/// Set this value to affect how any content that you subsequently draw
/// into the context blends with content that's already in the context.
/// Use one of the ``GraphicsContext/BlendMode-swift.struct`` values.
public var blendMode: GraphicsContext.BlendMode
/// The environment associated with the graphics context.
///
/// SwiftUI initially sets this to the environment of the context's
/// enclosing view. The context uses values like display
/// resolution and teh color scheme from the environment to resolve types
/// like ``Image`` and ``Color``. You can also access values stored in the
/// environment for your own purposes.
public var environment: EnvironmentValues { get }
/// The current transform matrix, defining user space coordinates.
///
/// Modify this matrix to transform content that you subsequently
/// draw into the context. Changes that you make don't affect
/// existing content.
public var transform: CGAffineTransform
/// Scales subsequent drawing operations by an amount in each dimension.
///
/// Calling this method is equivalent to updating the context's
/// ``transform`` directly using the given scale factors:
///
/// transform = transform.scaledBy(x: x, y: y)
///
/// - Parameters:
/// - x: The amount to scale in the horizontal direction.
/// - y: The amount to scale in the vertical direction.
public mutating func scaleBy(x: CGFloat, y: CGFloat)
/// Moves subsequent drawing operations by an amount in each dimension.
///
/// Calling this method is equivalent to updating the context's
/// ``transform`` directly using the given translation amount:
///
/// transform = transform.translatedBy(x: x, y: y)
///
/// - Parameters:
/// - x: The amount to move in the horizontal direction.
/// - y: The amount to move in the vertical direction.
public mutating func translateBy(x: CGFloat, y: CGFloat)
/// Rotates subsequent drawing operations by an angle.
///
/// Calling this method is equivalent to updating the context's
/// ``transform`` directly using the `angle` parameter:
///
/// transform = transform.rotated(by: angle.radians)
///
/// - Parameters:
/// - angle: The amount to rotate.
public mutating func rotate(by angle: Angle)
/// Appends the given transform to the context's existing transform.
///
/// Calling this method is equivalent to updating the context's
/// ``transform`` directly using the `matrix` parameter:
///
/// transform = matrix.concatenating(transform)
///
/// - Parameter matrix: A transform to append to the existing transform.
public mutating func concatenate(_ matrix: CGAffineTransform)
/// Options that affect the use of clip shapes.
///
/// Use these options to affect how SwiftUI interprets a clip shape
/// when you call ``clip(to:style:options:)`` to add a path to the array of
/// clip shapes, or when you call ``clipToLayer(opacity:options:content:)``
/// to add a clipping layer.
@frozen public struct ClipOptions : 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.
@inlinable public init(rawValue: UInt32)
/// An option to invert the shape or layer alpha as the clip mask.
///
/// When you use this option, SwiftUI uses `1 - alpha` instead of
/// `alpha` for the given clip shape.
@inlinable public static var inverse: GraphicsContext.ClipOptions { get }
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = GraphicsContext.ClipOptions
/// 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 = GraphicsContext.ClipOptions
/// 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
}
/// The bounding rectangle of the intersection of all current clip
/// shapes in the current user space.
public var clipBoundingRect: CGRect { get }
/// Adds a path to the context's array of clip shapes.
///
/// Call this method to add a shape to the array of clip shapes that
/// the context uses to define a clipping mask. Shapes that you add
/// affect only subsequent drawing operations.
///
/// - Parameters:
/// - path: A ``Path`` that defines the shape of the clipping mask.
/// - style: A ``FillStyle`` that defines how to rasterize the shape.
/// - options: Clip options that tell SwiftUI how to interpret the `path`
/// as a clip shape. For example, you can invert the clip
/// shape by setting the ``ClipOptions/inverse`` option.
public mutating func clip(to path: Path, style: FillStyle = FillStyle(), options: GraphicsContext.ClipOptions = ClipOptions())
/// Adds a clip shape that you define in a new layer to the context's array
/// of clip shapes.
///
/// Call this method to add a shape to the array of clip shapes that
/// the context uses to define a clipping mask. Shapes that you add
/// affect only subsequent drawing operations.
///
/// - Parameters:
/// - opacity: A value that SwiftUI uses to multiply the alpha channel of
/// the rasterized layer that you define in the `content` closure. The
/// alpha values that result define the clip shape.
/// - options: A set of options that tell SwiftUI how to interpret the
/// clip shape. For example, you can invert the clip
/// shape by setting the ``ClipOptions/inverse`` option.
/// - content: A closure that receives as input a new ``GraphicsContext``,
/// which represents a new transparency layer. The alpha channel of
/// content that you draw into this context, multiplied by the `opacity`
/// parameter, defines the clip shape.
public mutating func clipToLayer(opacity: Double = 1, options: GraphicsContext.ClipOptions = ClipOptions(), content: (inout GraphicsContext) throws -> Void) rethrows
/// A type that applies image processing operations to rendered content.
///
/// Create and configure a filter that produces an image processing effect,
/// like adding a drop shadow or a blur effect, by calling one of the
/// factory methods defined by the `Filter` structure. Call the
/// ``addFilter(_:options:)`` method to add the filter to a
/// ``GraphicsContext``. The filter only affects content that you draw
/// into the context after adding the filter.
public struct Filter {
/// Returns a filter that that transforms the rasterized form
/// of subsequent graphics primitives.
///
/// - Parameters:
/// - matrix: A projection transform to apply to the rasterized
/// form of graphics primitives.
/// - Returns: A filter that applies a transform.
public static func projectionTransform(_ matrix: ProjectionTransform) -> GraphicsContext.Filter
/// Returns a filter that adds a shadow.
///
/// SwiftUI produces the shadow by blurring the alpha channel of the
/// object receiving the shadow, multiplying the result by a color,
/// optionally translating the shadow by an amount,
/// and then blending the resulting shadow into a new layer below the
/// source primitive. You can customize some of these steps by adding
/// one or more shadow options.
///
/// - Parameters:
/// - color: A ``Color`` that tints the shadow.
/// - radius: A measure of how far the shadow extends from the edges
/// of the content receiving the shadow.
/// - x: An amount to translate the shadow horizontally.
/// - y: An amount to translate the shadow vertically.
/// - blendMode: The ``GraphicsContext/BlendMode-swift.struct`` to use
/// when blending the shadow into the background layer.
/// - options: A set of options that you can use to customize the
/// process of adding the shadow. Use one or more of the options
/// in ``GraphicsContext/ShadowOptions``.
/// - Returns: A filter that adds a shadow style.
public static func shadow(color: Color = Color(.sRGBLinear, white: 0, opacity: 0.33), radius: CGFloat, x: CGFloat = 0, y: CGFloat = 0, blendMode: GraphicsContext.BlendMode = .normal, options: GraphicsContext.ShadowOptions = ShadowOptions()) -> GraphicsContext.Filter
/// Returns a filter that multiplies each color component by
/// the matching component of a given color.
///
/// - Parameters:
/// - color: The color that the filter uses for the multiplication
/// operation.
/// - Returns: A filter that multiplies color components.
public static func colorMultiply(_ color: Color) -> GraphicsContext.Filter
/// Returns a filter that multiplies by a given color matrix.
///
/// This filter is equivalent to the `feColorMatrix` filter primitive
/// defined by the Scalable Vector Graphics (SVG) specification.
///
/// The filter creates the output color `[R', G', B', A']` at each pixel
/// from an input color `[R, G, B, A]` by multiplying the input color by
/// the square matrix formed by the first four columns of the
/// ``ColorMatrix``, then adding the fifth column to the result:
///
/// R' = r1 ✕ R + r2 ✕ G + r3 ✕ B + r4 ✕ A + r5
/// G' = g1 ✕ R + g2 ✕ G + g3 ✕ B + g4 ✕ A + g5
/// B' = b1 ✕ R + b2 ✕ G + b3 ✕ B + b4 ✕ A + b5
/// A' = a1 ✕ R + a2 ✕ G + a3 ✕ B + a4 ✕ A + a5
///
/// - Parameters:
/// - matrix: A ``ColorMatrix`` instance used by the filter.
/// - Returns: A filter that transforms color using the given matrix.
public static func colorMatrix(_ matrix: ColorMatrix) -> GraphicsContext.Filter
/// Returns a filter that applies a hue rotation adjustment.
///
/// This filter is equivalent to the `hue-rotate` filter primitive
/// defined by the Scalable Vector Graphics (SVG) specification.
///
/// - Parameters:
/// - angle: The amount by which to rotate the hue value of each
/// pixel.
/// - Returns: A filter that applies a hue rotation adjustment.
public static func hueRotation(_ angle: Angle) -> GraphicsContext.Filter
/// Returns a filter that applies a saturation adjustment.
///
/// This filter is equivalent to the `saturate` filter primitive
/// defined by the Scalable Vector Graphics (SVG) specification.
///
/// - Parameters:
/// - amount: The amount of the saturation adjustment. A value
/// of zero to completely desaturates each pixel, while a value of
/// one makes no change. You can use values greater than one.
/// - Returns: A filter that applies a saturation adjustment.
public static func saturation(_ amount: Double) -> GraphicsContext.Filter
/// Returns a filter that applies a brightness adjustment.
///
/// This filter is different than `brightness` filter primitive
/// defined by the Scalable Vector Graphics (SVG) specification.
/// You can obtain an effect like that filter using a ``grayscale(_:)``
/// color multiply. However, this filter does match the
/// <doc://com.apple.documentation/documentation/CoreImage/CIColorControls>
/// filter's brightness adjustment.
///
/// - Parameters:
/// - amount: An amount to add to the pixel's color components.
/// - Returns: A filter that applies a brightness adjustment.
public static func brightness(_ amount: Double) -> GraphicsContext.Filter
/// Returns a filter that applies a contrast adjustment.
///
/// This filter is equivalent to the `contrast` filter primitive
/// defined by the Scalable Vector Graphics (SVG) specification.
///
/// - Parameters:
/// - amount: An amount to adjust the contrast. A value of
/// zero leaves the result completely gray. A value of one leaves
/// the result unchanged. You can use values greater than one.
/// - Returns: A filter that applies a contrast adjustment.
public static func contrast(_ amount: Double) -> GraphicsContext.Filter
/// Returns a filter that inverts the color of their results.
///
/// This filter is equivalent to the `invert` filter primitive
/// defined by the Scalable Vector Graphics (SVG) specification.
///
/// - Parameters:
/// - amount: The inversion amount. A value of one results in total
/// inversion, while a value of zero leaves the result unchanged.
/// Other values apply a linear multiplier effect.
/// - Returns: A filter that applies a color inversion.
public static func colorInvert(_ amount: Double = 1) -> GraphicsContext.Filter
/// Returns a filter that applies a grayscale adjustment.
///
/// This filter is equivalent to the `grayscale` filter primitive
/// defined by the Scalable Vector Graphics (SVG) specification.
///
/// - Parameters:
/// - amount: An amount that controls the effect. A value of one
/// makes the image completely gray. A value of zero leaves the
/// result unchanged. Other values apply a linear multiplier effect.
/// - Returns: A filter that applies a grayscale adjustment.
public static func grayscale(_ amount: Double) -> GraphicsContext.Filter
/// Returns a filter that sets the opacity of each pixel based on its
/// luminance.
///
/// The filter computes the luminance of each pixel
/// and uses it to define the opacity of the result, combined
/// with black (zero) color components.
///
/// - Returns: A filter that applies a luminance to alpha transformation.
public static var luminanceToAlpha: GraphicsContext.Filter { get }
/// Returns a filter that applies a Gaussian blur.
///
/// - Parameters:
/// - radius: The standard deviation of the Gaussian blur.
/// - options: A set of options controlling the application of the
/// effect.
/// - Returns: A filter that applies Gaussian blur.
public static func blur(radius: CGFloat, options: GraphicsContext.BlurOptions = BlurOptions()) -> GraphicsContext.Filter
/// Returns a filter that replaces each pixel with alpha components
/// within a range by a constant color, or transparency otherwise.
///
/// - Parameters:
/// - min: The minimum alpha threshold. Pixels whose alpha
/// component is less than this value will render as
/// transparent. Results are undefined unless `min < max`.
/// - max: The maximum alpha threshold. Pixels whose alpha
/// component is greater than this value will render
/// as transparent. Results are undefined unless `min < max`.
/// - color: The color that is output for pixels with an alpha
/// component between the two threshold values.
/// - Returns: A filter that applies a threshold to alpha values.
public static func alphaThreshold(min: Double, max: Double = 1, color: Color = Color.black) -> GraphicsContext.Filter
}
/// Options that configure the graphics context filter that creates shadows.
///
/// You can use a set of these options when you call
/// ``Filter/shadow(color:radius:x:y:blendMode:options:)`` to create a
/// ``Filter`` that adds a drop shadow to an object that you draw into a
/// ``GraphicsContext``.
@frozen public struct ShadowOptions : 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.
@inlinable public init(rawValue: UInt32)
/// An option that causes the filter to draw the shadow above the
/// object, rather than below it.
@inlinable public static var shadowAbove: GraphicsContext.ShadowOptions { get }
/// An option that causes the filter to draw only the shadow, and
/// omit the source object.
@inlinable public static var shadowOnly: GraphicsContext.ShadowOptions { get }
/// An option that causes the filter to invert the alpha of the shadow.
///
/// You can create an "inner shadow" effect by combining this option
/// with ``shadowAbove`` and using the
/// ``GraphicsContext/BlendMode-swift.struct/sourceAtop`` blend mode.
@inlinable public static var invertsAlpha: GraphicsContext.ShadowOptions { get }
/// An option that causes the filter to composite the object and its
/// shadow separately in the current layer.
@inlinable public static var disablesGroup: GraphicsContext.ShadowOptions { get }
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = GraphicsContext.ShadowOptions
/// 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 = GraphicsContext.ShadowOptions
/// 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
}
/// Options that configure the graphics context filter that creates blur.
///
/// You can use a set of these options when you call
/// ``Filter/blur(radius:options:)`` to create a ``Filter`` that adds
/// blur to an object that you draw into a ``GraphicsContext``.
@frozen public struct BlurOptions : 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.
@inlinable public init(rawValue: UInt32)
/// An option that causes the filter to ensure the result is completely
/// opaque.
///
/// The filter ensure opacity by dividing each pixel by its alpha
/// value. The result may be undefined if the input to the filter
/// isn't also completely opaque.
@inlinable public static var opaque: GraphicsContext.BlurOptions { get }
/// An option that causes the filter to dither the result, to reduce
/// banding.
@inlinable public static var dithersResult: GraphicsContext.BlurOptions { get }
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = GraphicsContext.BlurOptions
/// 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 = GraphicsContext.BlurOptions
/// 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
}
/// Options that configure a filter that you add to a graphics context.
///
/// You can use filter options to configure a ``Filter`` that you apply
/// to a ``GraphicsContext`` with the ``addFilter(_:options:)`` method.
@frozen public struct FilterOptions : 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.
@inlinable public init(rawValue: UInt32)
/// An option that causes the filter to perform calculations in a
/// linear color space.
@inlinable public static var linearColor: GraphicsContext.FilterOptions { get }
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = GraphicsContext.FilterOptions
/// 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 = GraphicsContext.FilterOptions
/// 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
}
/// Adds a filter that applies to subsequent drawing operations.
///
/// To draw with filtering, SwiftUI:
///
/// - Rasterizes the drawing operation to an implicit transparency layer
/// without blending, adjusting opacity, or applying any clipping.
/// - Applies the filter to the layer containing the rasterized image.
/// - Composites the layer onto the background, using the context's
/// current blend mode, opacity setting, and clip shapes.
///
/// When SwiftUI draws with a filter, the blend mode might apply to regions
/// outside the drawing operation's intrinsic shape, but inside its clip
/// shape. That might result in unexpected behavior for certain blend
/// modes like ``GraphicsContext/BlendMode-swift.struct/copy``, where
/// the drawing operation completely overwrites the background even if
/// the source alpha is zero.
///
/// - Parameters:
/// - filter: A graphics context filter that you create by calling one
/// of the ``Filter`` factory methods.
/// - options: A set of options from ``FilterOptions`` that you can use to
/// configure filter operations.
public mutating func addFilter(_ filter: GraphicsContext.Filter, options: GraphicsContext.FilterOptions = FilterOptions())
/// A color or pattern that you can use to outline or fill a path.
///
/// Use a shading instance to describe the color or pattern of a path that
/// you outline with a method like ``stroke(_:with:style:)``, or of the
/// interior of a region that you fill with the ``fill(_:with:style:)``
/// method. Get a shading instance by calling one of the `Shading`
/// structure's factory methods. You can base shading on:
/// - A ``Color``.
/// - A ``Gradient``.
/// - Any type that conforms to ``ShapeStyle``.
/// - An ``Image``.
/// - What you've already drawn into the context.
/// - A collection of other shading instances.
public struct Shading {
/// A shading instance that draws a copy of the current background.
public static var backdrop: GraphicsContext.Shading { get }
/// A shading instance that fills with the foreground style from
/// the graphics context's environment.
public static var foreground: GraphicsContext.Shading { get }
/// Returns a multilevel shading instance constructed from an
/// array of shading instances.
///
/// - Parameter array: An array of shading instances. The array must
/// contain at least one element.
/// - Returns: A shading instance composed from the given instances.
public static func palette(_ array: [GraphicsContext.Shading]) -> GraphicsContext.Shading
/// Returns a shading instance that fills with a color.
///
/// - Parameter color: A ``Color`` instance that defines the color
/// of the shading.
/// - Returns: A shading instance filled with a color.
public static func color(_ color: Color) -> GraphicsContext.Shading
/// Returns a shading instance that fills with a color in the given
/// color space.
///
/// - Parameters:
/// - colorSpace: The RGB color space used to define the color. The
/// default is ``Color/RGBColorSpace/sRGB``.
/// - red: The red component of the color.
/// - green: The green component of the color.
/// - blue: The blue component of the color.
/// - opacity: The opacity of the color. The default is `1`, which
/// means fully opaque.
/// - Returns: A shading instance filled with a color.
public static func color(_ colorSpace: Color.RGBColorSpace = .sRGB, red: Double, green: Double, blue: Double, opacity: Double = 1) -> GraphicsContext.Shading
/// Returns a shading instance that fills with a monochrome color in
/// the given color space.
///
/// - Parameters:
/// - colorSpace: The RGB color space used to define the color. The
/// default is ``Color/RGBColorSpace/sRGB``.
/// - white: The value to use for each of the red, green, and blue
/// components of the color.
/// - opacity: The opacity of the color. The default is `1`, which
/// means fully opaque.
/// - Returns: A shading instance filled with a color.
public static func color(_ colorSpace: Color.RGBColorSpace = .sRGB, white: Double, opacity: Double = 1) -> GraphicsContext.Shading
/// Returns a shading instance that fills with the given shape style.
///
/// Styles with geometry defined in a unit coordinate space
/// map that space to the rectangle associated with the drawn
/// object. You can adjust that using the ``ShapeStyle/in`(_:)``
/// method. The shape style might affect the blend mode and opacity
/// of the drawn object.
///
/// - Parameter style: A ``ShapeStyle`` instance to draw with.
/// - Returns: A shading instance filled with a shape style.
public static func style<S>(_ style: S) -> GraphicsContext.Shading where S : ShapeStyle
/// Returns a shading instance that fills a linear (axial) gradient.
///
/// The shading instance defines an axis from `startPoint` to `endPoint`
/// in the current user space and maps colors from `gradient`
/// to lines perpendicular to the axis.
///
/// - Parameters:
/// - gradient: A ``Gradient`` instance that defines the colors
/// of the gradient.
/// - startPoint: The start point of the gradient axis.
/// - endPoint: The end point of the gradient axis.
/// - options: Options that you use to configure the gradient.
/// - Returns: A shading instance filled with a linear gradient.
public static func linearGradient(_ gradient: Gradient, startPoint: CGPoint, endPoint: CGPoint, options: GraphicsContext.GradientOptions = GradientOptions()) -> GraphicsContext.Shading
/// Returns a shading instance that fills a radial gradient.
///
/// - Parameters:
/// - gradient: A ``Gradient`` instance that defines the colors
/// of the gradient.
/// - center: The point in the current user space on which SwiftUI
/// centers the gradient.
/// - startRadius: The distance from the center where the gradient
/// starts.
/// - endRadius:The distance from the center where the gradient ends.
/// - options: Options that you use to configure the gradient.
/// - Returns: A shading instance filled with a radial gradient.
public static func radialGradient(_ gradient: Gradient, center: CGPoint, startRadius: CGFloat, endRadius: CGFloat, options: GraphicsContext.GradientOptions = GradientOptions()) -> GraphicsContext.Shading
/// Returns a shading instance that fills a conic (angular) gradient.
///
/// - Parameters:
/// - gradient: A ``Gradient`` instance that defines the colors
/// of the gradient.
/// - center: The point in the current user space on which SwiftUI
/// centers the gradient.
/// - angle: The angle about the center that SwiftUI uses to start and
/// finish the gradient. The gradient sweeps all the way around the
/// center.
/// - options: Options that you use to configure the gradient.
/// - Returns: A shading instance filled with a conic gradient.
public static func conicGradient(_ gradient: Gradient, center: CGPoint, angle: Angle = Angle(), options: GraphicsContext.GradientOptions = GradientOptions()) -> GraphicsContext.Shading
/// Returns a shading instance that tiles an image across the infinite
/// plane.
///
/// - Parameters:
/// - image: An ``Image`` to use as fill.
/// - origin: The point in the current user space where SwiftUI
/// places the bottom left corner of the part of the image
/// defined by `sourceRect`. The image repeats as needed.
/// - sourceRect: A unit space subregion of the image. The default
/// is a unit rectangle, which selects the whole image.
/// - scale: A factor that you can use to control the image size.
/// - Returns: A shading instance filled with a tiled image.
public static func tiledImage(_ image: Image, origin: CGPoint = .zero, sourceRect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1), scale: CGFloat = 1) -> GraphicsContext.Shading
}
/// Options that affect the rendering of color gradients.
///
/// Use these options to affect how SwiftUI manages a gradient that you
/// create for a ``Shading`` instance for use in a ``GraphicsContext``.
@frozen public struct GradientOptions : 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.
@inlinable public init(rawValue: UInt32)
/// An option that repeats the gradient outside its nominal range.
///
/// Use this option to cause the gradient to repeat its pattern in
/// areas that exceed the bounds of its start and end points.
/// The repetitions use the same start and end value for each
/// repetition.
///
/// Without this option or ``mirror``, the gradient stops at
/// the end of its range. The ``mirror`` option takes precendence if
/// you set both this one and that one.
@inlinable public static var `repeat`: GraphicsContext.GradientOptions { get }
/// An option that repeats the gradient outside its nominal range,
/// reflecting every other instance.
///
/// Use this option to cause the gradient to repeat its pattern in
/// areas that exceed the bounds of its start and end points.
/// The repetitions alternately reverse the start and end points,
/// producing a pattern like `0 -> 1`, `1 -> 0`, `0 -> 1`, and so on.
///
/// Without either this option or ``repeat``, the gradient stops at
/// the end of its range. This option takes precendence if
/// you set both this one and ``repeat``.
@inlinable public static var mirror: GraphicsContext.GradientOptions { get }
/// An option that interpolates between colors in a linear color space.
@inlinable public static var linearColor: GraphicsContext.GradientOptions { get }
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = GraphicsContext.GradientOptions
/// 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 = GraphicsContext.GradientOptions
/// 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
}
/// Returns a version of a shading resolved with the current values
/// of the graphics context's environment.
///
/// Calling this function once and then drawing multiple times with
/// the result will often have less overhead than drawing with the
/// original shading multiple times.
public func resolve(_ shading: GraphicsContext.Shading) -> GraphicsContext.Shading
/// Draws a new layer, created by drawing code that you provide, into the
/// context.
///
/// - Parameter context: A closure that receives a new ``GraphicsContext``
/// as input. This context represents a new transparency layer that you
/// can draw into. When the closure returns, SwiftUI draws the new layer
/// into the current context.
public func drawLayer(content: (inout GraphicsContext) throws -> Void) rethrows
/// Draws a path into the context and fills the outlined region.
///
/// The current drawing state of the context defines the
/// full drawing operation. For example, the current transformation and
/// clip shapes, and any styles applied to the result, affect the final
/// result.
///
/// - Parameters:
/// - path: The outline of the region to fill.
/// - shading: The color or pattern to use when filling the region
/// bounded by `path`.
/// - style: A style that indicates how to rasterize the path.
public func fill(_ path: Path, with shading: GraphicsContext.Shading, style: FillStyle = FillStyle())
/// Draws a path into the context with a specified stroke style.
///
/// If you only need to control the style's ``StrokeStyle/lineWidth``
/// property, use ``stroke(_:with:lineWidth:)`` instead.
///
/// - Parameters:
/// - path: The path to outline.
/// - shading: The color or pattern to use when outlining the `path`.
/// - style: A style that indicates how to outline the path.
public func stroke(_ path: Path, with shading: GraphicsContext.Shading, style: StrokeStyle)
/// Draws a path into the context with a specified line width.
///
/// When you call this method, all ``StrokeStyle`` properties other than
/// ``StrokeStyle/lineWidth`` take their default values. To control other
/// style properties, use ``stroke(_:with:style:)`` instead.
///
/// - Parameters:
/// - path: The path to outline.
/// - shading: The color or pattern to use when outlining the `path`.
/// - lineWidth: The width of the stroke, which defaults to `1`.
public func stroke(_ path: Path, with shading: GraphicsContext.Shading, lineWidth: CGFloat = 1)
/// An image resolved to a particular environment.
///
/// You resolve an ``Image`` in preparation for drawing it into a context,
/// either manually by calling ``resolve(_:)-898z6``, or automatically
/// when calling ``draw(_:in:style:)-blhz`` or ``draw(_:at:anchor:)-1z5wt``.
/// The resolved image takes into account environment values like the
/// display resolution and current color scheme.
public struct ResolvedImage {
/// The size of the image.
public var size: CGSize { get }
/// The distance from the top of the image to its baseline.
///
/// If the image has no baseline, this value is equivalent to the
/// image's height.
public let baseline: CGFloat
/// An optional shading to fill the image with.
///
/// The value of this property defaults to
/// ``GraphicsContext/Shading/foreground`` for template images, and
/// to `nil` otherwise.
public var shading: GraphicsContext.Shading?
}
/// Gets a version of an image that's fixed with the current values of
/// the graphics context's environment.
///
/// You can measure the resolved image by looking at its
/// ``ResolvedImage/size`` and ``ResolvedImage/baseline`` properties.
/// You can draw the resolved image with the context's
/// ``draw(_:in:style:)-7rvee`` or ``draw(_:at:anchor:)-1z5wt`` method.
///
/// - Parameter image: The ``Image`` to resolve.
/// - Returns: An image that's resolved into the current context's
/// environment, taking into account environment values like the
/// display resolution and current color scheme.
public func resolve(_ image: Image) -> GraphicsContext.ResolvedImage
/// Draws a resolved image into the context, using the specified rectangle
/// as a layout frame.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the image.
///
/// - Parameters:
/// - image: The ``ResolvedImage`` to draw. Get a resolved image from an
/// ``Image`` by calling ``resolve(_:)-898z6``. Alternatively, you can
/// call ``draw(_:in:style:)-blhz`` with an ``Image``, and that method
/// performs the resolution automatically.
/// - rect: The rectangle in the current user space to draw the image in.
/// - style: A fill style to use when rasterizing the image.
public func draw(_ image: GraphicsContext.ResolvedImage, in rect: CGRect, style: FillStyle = FillStyle())
/// Draws a resolved image into the context, aligning an anchor within the
/// image to a point in the context.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the image.
///
/// - Parameters:
/// - image: The ``ResolvedImage`` to draw. Get a resolved image from an
/// ``Image`` by calling ``resolve(_:)-898z6``. Alternatively, you can
/// call ``draw(_:at:anchor:)-7l217`` with an ``Image``, and that method
/// performs the resolution automatically.
/// - point: A point within the rectangle of the resolved image to anchor
/// to a point in the context.
/// - anchor: A ``UnitPoint`` within the context to align the image with.
/// The default is ``UnitPoint/center``.
public func draw(_ image: GraphicsContext.ResolvedImage, at point: CGPoint, anchor: UnitPoint = .center)
/// Draws an image into the context, using the specified rectangle
/// as a layout frame.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the image.
///
/// - Parameters:
/// - image: The ``Image`` to draw. Before drawing, the method converts
/// the image to a ``ResolvedImage`` by calling ``resolve(_:)-898z6``.
/// - rect: The rectangle in the current user space to draw the image in.
/// - style: A fill style to use when rasterizing the image.
public func draw(_ image: Image, in rect: CGRect, style: FillStyle = FillStyle())
/// Draws an image into the context, aligning an anchor within the image
/// to a point in the context.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the image.
///
/// - Parameters:
/// - image: The ``Image`` to draw. Before drawing, the method converts
/// the image to a ``ResolvedImage`` by calling ``resolve(_:)-898z6``.
/// - point: A point within the rectangle of the resolved image to anchor
/// to a point in the context.
/// - anchor: A ``UnitPoint`` within the context to align the image with.
/// The default is ``UnitPoint/center``.
public func draw(_ image: Image, at point: CGPoint, anchor: UnitPoint = .center)
/// A text view resolved to a particular environment.
///
/// You resolve a ``Text`` view in preparation for drawing it into a context,
/// either manually by calling ``resolve(_:)-4dx65`` or automatically
/// when calling ``draw(_:in:)-5opqf`` or ``draw(_:at:anchor:)-5dgmd``.
/// The resolved text view takes into account environment values like the
/// display resolution and current color scheme.
public struct ResolvedText {
/// The shading to fill uncolored text regions with.
///
/// This value defaults to the ``GraphicsContext/Shading/foreground``
/// shading.
public var shading: GraphicsContext.Shading
/// Measures the size of the resolved text for a given
/// area into which the text should be placed.
///
/// - Parameter size: The area to place the ``Text`` view in.
public func measure(in size: CGSize) -> CGSize
/// Gets the distance from the first line's ascender to its baseline.
public func firstBaseline(in size: CGSize) -> CGFloat
/// Gets the distance from the first line's ascender to the last
/// line's baseline.
public func lastBaseline(in size: CGSize) -> CGFloat
}
/// Gest a version of a text view that's fixed with the current values of
/// the graphics context's environment.
///
/// You can measure the resolved text by calling its
/// ``ResolvedText/measure(in:)`` method.
/// You can draw the resolved text with the context's
/// ``draw(_:in:)-69ad8`` or ``draw(_:at:anchor:)-6xr87`` method.
///
/// - Parameter text: The ``Text`` view to resolve.
/// - Returns: A text view that's resolved into the current context's
/// environment, taking into account environment values like the
/// display resolution and current color scheme.
public func resolve(_ text: Text) -> GraphicsContext.ResolvedText
/// Draws resolved text into the context using the specified rectangle
/// as a layout frame.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the text.
///
/// - Parameters:
/// - text: The ``ResolvedText`` to draw. Get resolved text from a
/// ``Text`` view by calling ``resolve(_:)-4dx65``. Alternatively, you
/// can call ``draw(_:in:)-5opqf`` with a ``Text`` view, and that
/// method performs the resolution automatically.
/// - rect: The rectangle in the current user space to draw the text in.
/// - shading: The shading to use when coloring the text.
public func draw(_ text: GraphicsContext.ResolvedText, in rect: CGRect)
/// Draws resolved text into the context, aligning an anchor within the
/// ideal size of the text to a point in the context.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the text.
///
/// - Parameters:
/// - text: The ``ResolvedText`` to draw. Get resolved text from a
/// ``Text`` view by calling ``resolve(_:)-4dx65``. Alternatively, you
/// can call ``draw(_:at:anchor:)-5dgmd`` with a ``Text`` view, and that
/// method performs the resolution automatically.
/// - point: A point within the rectangle of the ideal size of the
/// resolved text to anchor to a point in the context.
/// - anchor: A ``UnitPoint`` within the context to align the text with.
/// The default is ``UnitPoint/center``.
public func draw(_ text: GraphicsContext.ResolvedText, at point: CGPoint, anchor: UnitPoint = .center)
/// Draws text into the context using the specified rectangle
/// as a layout frame.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the text.
///
/// - Parameters:
/// - text: The ``Text`` view to draw. Before drawing, the method converts
/// the view to ``ResolvedText`` by calling ``resolve(_:)-4dx65``.
/// - rect: The rectangle in the current user space to draw the text in.
public func draw(_ text: Text, in rect: CGRect)
/// Draws text into the context, aligning an anchor within the ideal size
/// of the rendered text to a point in the context.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the text.
///
/// - Parameters:
/// - text: The ``Text`` view to draw. Before drawing, the method converts
/// the view to ``ResolvedText`` by calling ``resolve(_:)-4dx65``.
/// - point: A point within the rectangle of the resolved text to anchor
/// to a point in the context.
/// - anchor: A ``UnitPoint`` within the context to align the text with.
/// The default is ``UnitPoint/center``.
public func draw(_ text: Text, at point: CGPoint, anchor: UnitPoint = .center)
/// A static sequence of drawing operations that may be drawn
/// multiple times, preserving their resolution independence.
///
/// You resolve a child view in preparation for drawing it into a context
/// by calling ``resolveSymbol(id:)``. The resolved view takes into account
/// environment values like the display resolution and current color scheme.
public struct ResolvedSymbol {
/// The dimensions of the resolved symbol.
public var size: CGSize { get }
}
/// Gets the identified child view as a resolved symbol, if the view exists.
///
/// - Parameter id: The value that you used to tag the view when you
/// define it in the `symbols` parameter of the ``Canvas`` initializer
/// ``Canvas/init(opaque:colorMode:rendersAsynchronously:renderer:symbols:)``.
/// - Returns: The resolved symbol, or `nil` if SwiftUI can't find a child
/// view with the given `id`.
public func resolveSymbol<ID>(id: ID) -> GraphicsContext.ResolvedSymbol? where ID : Hashable
/// Draws a resolved symbol into the context, using the specified rectangle
/// as a layout frame.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the symbol.
///
/// - Parameters:
/// - symbol: The ``ResolvedSymbol`` to draw. Get a resolved symbol
/// by calling ``resolveSymbol(id:)`` with the identifier that you
/// use to tag the corresponding child view during ``Canvas``
/// initialization.
/// - rect: The rectangle in the current user space to draw the symbol in.
public func draw(_ symbol: GraphicsContext.ResolvedSymbol, in rect: CGRect)
/// Draws a resolved symbol into the context, aligning an anchor within the
/// symbol to a point in the context.
///
/// The current context state defines the full drawing operation. For
/// example, the current transformation and clip shapes affect how SwiftUI
/// draws the symbol.
///
/// - Parameters:
/// - symbol: The ``ResolvedSymbol`` view to draw. Get a resolved symbol
/// by calling ``resolveSymbol(id:)`` with the identifier that you
/// use to tag the corresponding child view during ``Canvas``
/// initialization.
/// - point: A point within the rectangle of the resolved symbol to anchor
/// to a point in the context.
/// - anchor: A ``UnitPoint`` within the context to align the symbol with.
/// The default is ``UnitPoint/center``.
public func draw(_ symbol: GraphicsContext.ResolvedSymbol, at point: CGPoint, anchor: UnitPoint = .center)
/// Provides a Core Graphics context that you can use as a proxy to draw
/// into this context.
///
/// Use this method to use existing drawing code that relies on
/// Core Graphics primitives.
///
/// - Parameter content: A closure that receives a
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGContext>
/// that you use to perform drawing operations, just like you draw into a
/// ``GraphicsContext`` instance. Any filters, blend mode settings, clip
/// masks, and other state set before calling `withCGContext(content:)`
/// apply to drawing operations in the Core Graphics context as well. Any
/// state you set on the Core Graphics context is lost when the closure
/// returns. Accessing the Core Graphics context after the closure
/// returns produces undefined behavior.
public func withCGContext(content: (CGContext) throws -> Void) rethrows
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension GraphicsContext.BlendMode : Sendable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension GraphicsContext.ClipOptions : Sendable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension GraphicsContext.ShadowOptions : Sendable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension GraphicsContext.BlurOptions : Sendable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension GraphicsContext.FilterOptions : Sendable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension GraphicsContext.GradientOptions : Sendable {
}
/// A description of a single grid item, such as a row or a column.
///
/// You use `GridItem` instances to configure the layout of items in
/// ``LazyHGrid`` and ``LazyVGrid`` views. Each grid item specifies layout
/// properties like spacing and alignment, which the grid view uses to size and
/// position all items in a given column or row.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct GridItem {
/// The size in the minor axis of one or more rows or columns in a grid
/// layout.
public enum Size {
/// A single item with the specified fixed size.
case fixed(CGFloat)
/// A single flexible item.
///
/// The size of this item is the size of the grid with spacing and
/// inflexible items removed, divided by the number of flexible items,
/// clamped to the provided bounds.
case flexible(minimum: CGFloat = 10, maximum: CGFloat = .infinity)
/// Multiple items in the space of a single flexible item.
///
/// This size case places one or more items into the space assigned to
/// a single `flexible` item, using the provided bounds and
/// spacing to decide exactly how many items fit. This approach prefers
/// to insert as many items of the `minimum` size as possible
/// but lets them increase to the `maximum` size.
case adaptive(minimum: CGFloat, maximum: CGFloat = .infinity)
}
/// The size of the item, which is the width of a column item or the
/// height of a row item.
public var size: GridItem.Size
/// The spacing to the next item.
///
/// If this value is `nil`, the item uses a reasonable default for the
/// current platform.
public var spacing: CGFloat?
/// The alignment to use when placing each view.
///
/// Use this property to anchor the view's relative position to the same
/// relative position in the view's assigned grid space.
public var alignment: Alignment?
/// Creates a grid item with the provided size, spacing, and alignment
/// properties.
///
/// - Parameters:
/// - size: The size of the grid item.
/// - spacing: The spacing to use between this and the next item.
/// - alignment: The alignment to use for this grid item.
public init(_ size: GridItem.Size = .flexible(), spacing: CGFloat? = nil, alignment: Alignment? = nil)
}
/// A type that collects multiple instances of a content type --- like views,
/// scenes, or commands --- into a single unit.
///
/// Use a group to collect multiple views into a single instance, without
/// affecting the layout of those views, like an ``SwiftUI/HStack``,
/// ``SwiftUI/VStack``, or ``SwiftUI/Section`` would. After creating a group,
/// any modifier you apply to the group affects all of that group's members.
/// For example, the following code applies the ``SwiftUI/Font/headline``
/// font to three views in a group.
///
/// Group {
/// Text("SwiftUI")
/// Text("Combine")
/// Text("Swift System")
/// }
/// .font(.headline)
///
/// Because you create a group of views with a ``SwiftUI/ViewBuilder``, you can
/// use the group's initializer to produce different kinds of views from a
/// conditional, and then optionally apply modifiers to them. The following
/// example uses a `Group` to add a navigation bar title,
/// regardless of the type of view the conditional produces:
///
/// Group {
/// if isLoggedIn {
/// WelcomeView()
/// } else {
/// LoginView()
/// }
/// }
/// .navigationBarTitle("Start")
///
/// The modifier applies to all members of the group --- and not to the group
/// itself. For example, if you apply ``View/onAppear(perform:)`` to the above
/// group, it applies to all of the views produced by the `if isLoggedIn`
/// conditional, and it executes every time `isLoggedIn` changes.
///
/// Because a group of views itself is a view, you can compose a group within
/// other view builders, including nesting within other groups. This allows you
/// to add large numbers of views to different view builder containers. The
/// following example uses a `Group` to collect 10 ``SwiftUI/Text`` instances,
/// meaning that the vertical stack's view builder returns only two views ---
/// the group, plus an additional ``SwiftUI/Text``:
///
/// var body: some View {
/// VStack {
/// Group {
/// Text("1")
/// Text("2")
/// Text("3")
/// Text("4")
/// Text("5")
/// Text("6")
/// Text("7")
/// Text("8")
/// Text("9")
/// Text("10")
/// }
/// Text("11")
/// }
/// }
///
/// You can initialize groups with several types other than ``SwiftUI/View``,
/// such as ``SwiftUI/Scene`` and ``SwiftUI/ToolbarContent``. The closure you
/// provide to the group initializer uses the corresponding builder type
/// (``SwiftUI/SceneBuilder``, ``SwiftUI/ToolbarContentBuilder``, and so on),
/// and the capabilities of these builders vary between types. For example,
/// you can use groups to return large numbers of scenes or toolbar content
/// instances, but not to return different scenes or toolbar content based
/// on conditionals.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Group<Content> {
/// 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 Group : AccessibilityRotorContent where Content : AccessibilityRotorContent {
/// The internal content of this `AccessibilityRotorContent`.
public var body: Never { get }
/// Creates an instance that generates Rotor content by combining, in order,
/// all the Rotor content specified in the passed-in result builder.
///
/// - Parameter content: The result builder that generates Rotor content for
/// the group.
public init(@AccessibilityRotorContentBuilder content: () -> Content)
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Group : ToolbarContent where Content : ToolbarContent {
/// Creates a group of toolbar content instances.
///
/// - Parameter content: A ``SwiftUI/ToolbarContentBuilder`` that produces
/// the toolbar content instances to group.
public init(@ToolbarContentBuilder content: () -> Content)
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Group : CustomizableToolbarContent where Content : CustomizableToolbarContent {
/// Creates a group of customizable toolbar content instances.
///
/// - Parameter content: A ``SwiftUI/ToolbarContentBuilder`` that produces
/// the customizable toolbar content instances to group.
public init(@ToolbarContentBuilder content: () -> Content)
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Group : Scene where Content : Scene {
/// Creates a group of scenes.
///
/// - Parameter content: A ``SwiftUI/SceneBuilder`` that produces the scenes
/// to group.
@inlinable public init(@SceneBuilder content: () -> Content)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Group : View where Content : View {
/// Creates a group of views.
/// - Parameter content: A ``SwiftUI/ViewBuilder`` that produces the views
/// to group.
@inlinable public init(@ViewBuilder content: () -> Content)
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension Group : Commands where Content : Commands {
/// Creates a group of commands.
///
/// - Parameter content: A ``SwiftUI/CommandsBuilder`` that produces the
/// commands to group.
@inlinable public init(@CommandsBuilder content: () -> Content)
}
/// A stylized view, with an optional label, that visually collects a logical
/// grouping of content.
///
/// Use a group box when you want to visually distinguish a portion of your
/// user interface with an optional title for the boxed content.
///
/// The following example sets up a `GroupBox` with the label "End-User
/// Agreement", and a long `agreementText` string in a ``SwiftUI/Text`` view
/// wrapped by a ``SwiftUI/ScrollView``. The box also contains a
/// ``SwiftUI/Toggle`` for the user to interact with after reading the text.
///
/// var body: some View {
/// GroupBox(label:
/// Label("End-User Agreement", systemImage: "building.columns")
/// ) {
/// ScrollView(.vertical, showsIndicators: true) {
/// Text(agreementText)
/// .font(.footnote)
/// }
/// .frame(height: 100)
/// Toggle(isOn: $userAgreed) {
/// Text("I agree to the above terms")
/// }
/// }
/// }
///
/// ![An iOS status bar above a gray rounded rectangle region marking the bounds
/// of the group box. At the top of the region, the title End-User Agreement
/// in a large bold font with an icon of a building with columns. Below this,
/// a scroll view with six lines of text visible. At the bottom of the gray
/// group box region, a toggle switch with the label I agree to the above
/// terms.](SwiftUI-GroupBox-EULA.png)
///
@available(iOS 14.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct GroupBox<Label, Content> : View where Label : View, Content : View {
/// Creates a group box with the provided label and view content.
/// - Parameters:
/// - content: A ``SwiftUI/ViewBuilder`` that produces the content for the
/// group box.
/// - label: A ``SwiftUI/ViewBuilder` that produces a label for the group
/// box.
@available(iOS 14.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public init(@ViewBuilder content: () -> 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 primitive 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>.
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 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension GroupBox where Label == GroupBoxStyleConfiguration.Label, Content == GroupBoxStyleConfiguration.Content {
/// Creates a group box based on a style configuration.
///
/// Use this initializer within the ``GroupBoxStyle/makeBody(configuration:)``
/// method of a ``GroupBoxStyle`` instance to create a styled group box,
/// with customizations, while preserving its existing style.
///
/// The following example adds a pink border around the group box,
/// without overriding its current style:
///
/// struct PinkBorderGroupBoxStyle: GroupBoxStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// GroupBox(configuration)
/// .border(Color.pink)
/// }
/// }
/// - Parameter configuration: The properties of the group box instance being created.
public init(_ configuration: GroupBoxStyleConfiguration)
}
@available(iOS 14.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension GroupBox where Label == EmptyView {
/// Creates an unlabeled group box with the provided view content.
/// - Parameters:
/// - content: A ``SwiftUI/ViewBuilder`` that produces the content for
/// the group box.
public init(@ViewBuilder content: () -> Content)
}
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension GroupBox where Label == Text {
/// Creates a group box with the provided view content and title.
/// - Parameters:
/// - titleKey: The key for the group box's title, which describes the
/// content of the group box.
/// - content: A ``SwiftUI/ViewBuilder`` that produces the content for the
/// group box.
public init(_ titleKey: LocalizedStringKey, @ViewBuilder content: () -> Content)
/// Creates a group box with the provided view content.
/// - Parameters:
/// - title: A string that describes the content of the group box.
/// - content: A ``SwiftUI/ViewBuilder`` that produces the content for the
/// group box.
public init<S>(_ title: S, @ViewBuilder content: () -> Content) where S : StringProtocol
}
@available(iOS 14.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension GroupBox {
@available(iOS, deprecated: 100000.0, renamed: "GroupBox(content:label:)")
@available(macOS, deprecated: 100000.0, renamed: "GroupBox(content:label:)")
public init(label: Label, @ViewBuilder content: () -> Content)
}
/// A type that specifies the appearance and interaction of all group boxes
/// within a view hierarchy.
///
/// To configure the current `GroupBoxStyle` for a view hierarchy, use the
/// ``View/groupBoxStyle(_:)`` modifier.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public protocol GroupBoxStyle {
/// A view that represents the body of a group box.
associatedtype Body : View
/// 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.
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a group box instance.
typealias Configuration = GroupBoxStyleConfiguration
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension GroupBoxStyle where Self == DefaultGroupBoxStyle {
/// The default style for group box views.
public static var automatic: DefaultGroupBoxStyle { get }
}
/// The properties of a group box instance.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct GroupBoxStyleConfiguration {
/// A type-erased label of a group box.
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 content of a group box.
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 provides the title of the group box.
public let label: GroupBoxStyleConfiguration.Label
/// A view that represents the content of the group box.
public let content: GroupBoxStyleConfiguration.Content
}
/// The list style that describes the behavior and appearance of a grouped list.
///
/// Do not use this type directly. Instead, use ``ListStyle/grouped``.
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
public struct GroupedListStyle : ListStyle {
/// Creates a grouped list style.
public init()
}
/// A view that arranges its children in a horizontal line.
///
/// Unlike ``LazyHStack``, which only renders the views when your app needs to
/// display them onscreen, an `HStack` renders the views all at once, regardless
/// of whether they are on- or offscreen. Use the regular `HStack` when you have
/// a small number of child views or don't want the delayed rendering behavior
/// of the "lazy" version.
///
/// The following example shows a simple horizontal stack of five text views:
///
/// var body: some View {
/// HStack(
/// alignment: .top,
/// spacing: 10
/// ) {
/// ForEach(
/// 1...5,
/// id: \.self
/// ) {
/// Text("Item \($0)")
/// }
/// }
/// }
/// ![Five text views, named Item 1 through Item 5, arranged in a
/// horizontal row.](SwiftUI-HStack-simple.png)
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct HStack<Content> : View where Content : View {
/// Creates a horizontal stack with the given spacing and vertical alignment.
///
/// - Parameters:
/// - alignment: The guide for aligning the subviews in this stack. This
/// guide has the same vertical screen coordinate for every child view.
/// - spacing: The distance between adjacent subviews, or `nil` if you
/// want the stack to choose a default distance for each pair of
/// subviews.
/// - content: A view builder that creates the content of this stack.
@inlinable public init(alignment: VerticalAlignment = .center, spacing: CGFloat? = nil, @ViewBuilder 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 shape style that maps to one of the numbered content styles.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public struct HierarchicalShapeStyle : ShapeStyle {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension HierarchicalShapeStyle : Sendable {
}
/// An alignment position along the horizontal axis.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct HorizontalAlignment : Equatable {
/// Creates an instance with the given identifier.
///
/// Each instance needs a unique identifier.
///
/// - Parameter id: An identifier that uniquely identifies the horizontal
/// alignment.
public init(_ id: AlignmentID.Type)
/// 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: HorizontalAlignment, b: HorizontalAlignment) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension HorizontalAlignment {
/// A guide marking the leading edge of the view.
public static let leading: HorizontalAlignment
/// A guide marking the horizontal center of the view.
public static let center: HorizontalAlignment
/// A guide marking the trailing edge of the view.
public static let trailing: HorizontalAlignment
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension HorizontalAlignment : Sendable {
}
/// An edge on the horizontal axis.
///
/// Use a horizontal edge for tasks like setting a swipe action with the
/// ``View/swipeActions(edge:allowsFullSwipe:content:)``
/// view modifier. The positions of the leading and trailing edges
/// depend on the locale chosen by the user.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public enum HorizontalEdge : Int8, CaseIterable, Codable {
/// The leading edge.
case leading
/// The trailing edge.
case trailing
/// An efficient set of `HorizontalEdge`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 = HorizontalEdge.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)
/// A set containing only the leading horizontal edge.
public static let leading: HorizontalEdge.Set
/// A set containing only the trailing horizontal edge.
public static let trailing: HorizontalEdge.Set
/// A set containing the leading and trailing horizontal edges.
public static let all: HorizontalEdge.Set
/// Creates an instance containing just `e`.
public init(_ edge: HorizontalEdge)
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = HorizontalEdge.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 = [HorizontalEdge]
/// 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: [HorizontalEdge] { 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 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension HorizontalEdge : Equatable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension HorizontalEdge : Hashable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension HorizontalEdge : RawRepresentable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension HorizontalEdge : Sendable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension HorizontalEdge.Set : Sendable {
}
/// An effect applied when the pointer hovers over a view.
@available(iOS 13.4, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct HoverEffect {
/// An effect that attempts to determine the effect automatically.
/// This is the default effect.
public static let automatic: HoverEffect
/// An effect that morphs the pointer into a platter behind the view
/// and shows a light source indicating position.
public static let highlight: HoverEffect
/// An effect that slides the pointer under the view and disappears as the
/// view scales up and gains a shadow.
public static let lift: HoverEffect
}
/// A label style that only displays the icon of the label.
///
/// Do not use this type directly. Instead, use ``LabelStyle/iconOnly``.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct IconOnlyLabelStyle : LabelStyle {
/// Creates an icon-only 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: IconOnlyLabelStyle.Configuration) -> some View
/// A view that represents the body of a label.
public typealias Body = some View
}
/// A view that displays an image.
///
/// Use an `Image` instance when you want to add images to your SwiftUI app.
/// You can create images from many sources:
///
/// * Image files in your app's asset library or bundle. Supported types include
/// PNG, JPEG, HEIC, and more.
/// * Instances of platform-specific image types, like
/// <doc://com.apple.documentation/documentation/UIKit/UIImage> and
/// <doc://com.apple.documentation/documentation/AppKit/NSImage>.
/// * A bitmap stored in a Core Graphics
/// <doc://com.apple.documentation/documentation/coregraphics/cgimage>
/// instance.
/// * System graphics from the SF Symbols set.
///
/// The following example shows how to load an image from the app's asset
/// library or bundle and scale it to fit within its container:
///
/// Image("Landscape_4")
/// .resizable()
/// .aspectRatio(contentMode: .fit)
/// Text("Water wheel")
///
/// ![An image of a water wheel and its adjoining building, resized to fit the
/// width of an iPhone display. The words Water wheel appear under this
/// image.](SwiftUI-Image-waterWheel-resize.png)
///
/// You can use methods on the `Image` type as well as
/// standard view modifiers to adjust the size of the image to fit your app's
/// interface. Here, the `Image` type's
/// ``Image/resizable(capInsets:resizingMode:)`` method scales the image to fit
/// the current view. Then, the
/// ``View/aspectRatio(_:contentMode:)-771ow`` view modifier adjusts
/// this resizing behavior to maintain the image's original aspect ratio, rather
/// than scaling the x- and y-axes independently to fill all four sides of the
/// view. The article
/// <doc:Fitting-Images-into-Available-Space> shows how to apply scaling,
/// clipping, and tiling to `Image` instances of different sizes.
///
/// An `Image` is a late-binding token; the system resolves its actual value
/// only when it's about to use the image in an environment.
///
/// ### Making Images Accessible
///
/// To use an image as a control, use one of the initializers that takes a
/// `label` parameter. This allows the system's accessibility frameworks to use
/// the label as the name of the control for users who use features like
/// VoiceOver. For images that are only present for aesthetic reasons, use an
/// initializer with the `decorative` parameter; the accessibility systems
/// ignore these images.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Image : 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: Image, rhs: Image) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image {
/// Creates a labeled image that you can use as content for controls.
///
/// - Parameters:
/// - name: The name of the image resource to lookup, as well as the
/// localization key with which to label the image.
/// - bundle: The bundle to search for the image resource and localization
/// content. If `nil`, SwiftUI uses the main `Bundle`. Defaults to `nil`.
public init(_ name: String, bundle: Bundle? = nil)
/// Creates a labeled image that you can use as content for controls, with
/// the specified label.
///
/// - Parameters:
/// - name: The name of the image resource to lookup
/// - bundle: The bundle to search for the image resource. If `nil`,
/// SwiftUI uses the main `Bundle`. Defaults to `nil`.
/// - label: The label associated with the image. SwiftUI uses the label
/// for accessibility.
public init(_ name: String, bundle: Bundle? = nil, label: Text)
/// Creates an unlabeled, decorative image.
///
/// SwiftUI ignores this image for accessibility purposes.
///
/// - Parameters:
/// - name: The name of the image resource to lookup
/// - bundle: The bundle to search for the image resource. If `nil`,
/// SwiftUI uses the main `Bundle`. Defaults to `nil`.
public init(decorative name: String, bundle: Bundle? = nil)
/// Creates a system symbol image.
///
/// This initializer creates an image using a system-provided symbol. To
/// create a custom symbol image from your app's asset catalog, use
/// ``Image/init(_:bundle:)`` instead.
///
/// - Parameters:
/// - systemName: The name of the system symbol image.
/// Use the SF Symbols app to look up the names of system symbol images.
@available(macOS 11.0, *)
public init(systemName: String)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image : 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 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image {
/// Indicates whether SwiftUI renders an image as-is, or
/// by using a different mode.
///
/// The ``TemplateRenderingMode`` enumeration has two cases:
/// ``TemplateRenderingMode/original`` and ``TemplateRenderingMode/template``.
/// The original mode renders pixels as they appear in the original source
/// image. Template mode renders all nontransparent pixels as the
/// foreground color, which you can use for purposes like creating image
/// masks.
///
/// The following example shows both rendering modes, as applied to an icon
/// image of a green circle with darker green border:
///
/// Image("dot_green")
/// .renderingMode(.original)
/// Image("dot_green")
/// .renderingMode(.template)
///
/// ![Two identically-sized circle images. The circle on top is green
/// with a darker green border. The circle at the bottom is a solid color,
/// either white on a black background, or black on a white background,
/// depending on the system's current dark mode
/// setting.](SwiftUI-Image-TemplateRenderingMode-dots.png)
///
/// You also use `renderingMode` to produce multicolored system graphics
/// from the SF Symbols set. Use the ``TemplateRenderingMode/original``
/// mode to apply a foreground color to all parts of the symbol except
/// those that have a distinct color in the graphic. The following
/// example shows three uses of the `person.crop.circle.badge.plus` symbol
/// to achieve different effects:
///
/// * A default appearance with no foreground color or template rendering
/// mode specified. The symbol appears all black in light mode, and all
/// white in Dark Mode.
/// * The multicolor behavior achieved by using `original` template
/// rendering mode, along with a blue foreground color. This mode causes the
/// graphic to override the foreground color for distinctive parts of the
/// image, in this case the plus icon.
/// * A single-color template behavior achieved by using `template`
/// rendering mode with a blue foreground color. This mode applies the
/// foreground color to the entire image, regardless of the user's Appearance preferences.
///
///```swift
///HStack {
/// Image(systemName: "person.crop.circle.badge.plus")
/// Image(systemName: "person.crop.circle.badge.plus")
/// .renderingMode(.original)
/// .foregroundColor(.blue)
/// Image(systemName: "person.crop.circle.badge.plus")
/// .renderingMode(.template)
/// .foregroundColor(.blue)
///}
///.font(.largeTitle)
///```
///
/// ![A horizontal layout of three versions of the same symbol: a person
/// icon in a circle with a plus icon overlaid at the bottom left. Each
/// applies a diffent set of colors based on its rendering mode, as
/// described in the preceding
/// list.](SwiftUI-Image-TemplateRenderingMode-sfsymbols.png)
///
/// Use the SF Symbols app to find system images that offer the multicolor
/// feature. Keep in mind that some multicolor symbols use both the
/// foreground and accent colors.
///
/// - Parameter renderingMode: The mode SwiftUI uses to render images.
/// - Returns: A modified ``Image``.
public func renderingMode(_ renderingMode: Image.TemplateRenderingMode?) -> Image
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image {
/// The orientation of an image.
///
/// Many image formats such as JPEG include orientation metadata in the
/// image data. In other cases, you can specify image orientation
/// in code. Properly specifying orientation is often important both for
/// displaying the image and for certain kinds of image processing.
///
/// In SwiftUI, you provide an orientation value when initializing an
/// ``Image`` from an existing
/// <doc://com.apple.documentation/documentation/coregraphics/cgimage>.
@frozen public enum Orientation : UInt8, CaseIterable, Hashable {
/// A value that indicates the original pixel data matches the image's
/// intended display orientation.
case up
/// A value that indicates a horizontal flip of the image from the
/// orientation of its original pixel data.
case upMirrored
/// A value that indicates a 180° rotation of the image from the
/// orientation of its original pixel data.
case down
/// A value that indicates a vertical flip of the image from the
/// orientation of its original pixel data.
case downMirrored
/// A value that indicates a 90° counterclockwise rotation from the
/// orientation of its original pixel data.
case left
/// A value that indicates a 90° clockwise rotation and horizontal
/// flip of the image from the orientation of its original pixel
/// data.
case leftMirrored
/// A value that indicates a 90° clockwise rotation of the image from
/// the orientation of its original pixel data.
case right
/// A value that indicates a 90° counterclockwise rotation and
/// horizontal flip from the orientation of its original pixel data.
case rightMirrored
/// 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: UInt8)
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [Image.Orientation]
/// 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 = UInt8
/// A collection of all values of this type.
public static var allCases: [Image.Orientation] { 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: UInt8 { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image {
/// A type that indicates how SwiftUI renders images.
public enum TemplateRenderingMode {
/// A mode that renders all non-transparent pixels as the foreground
/// color.
case template
/// A mode that renders pixels of bitmap images as-is.
///
/// For system images created from the SF Symbol set, multicolor symbols
/// respect the current foreground and accent colors.
case original
/// 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: Image.TemplateRenderingMode, b: Image.TemplateRenderingMode) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
/// A scale to apply to vector images relative to text.
///
/// Use this type with the ``View/imageScale(_:)`` modifier, or the
/// ``EnvironmentValues/imageScale`` environment key, to set the image scale.
///
/// The following example shows the three `Scale` values as applied to
/// a system symbol image, each set against a text view:
///
/// HStack { Image(systemName: "swift").imageScale(.small); Text("Small") }
/// HStack { Image(systemName: "swift").imageScale(.medium); Text("Medium") }
/// HStack { Image(systemName: "swift").imageScale(.large); Text("Large") }
///
/// ![Vertically arranged text views that read Small, Medium, and
/// Large. On the left of each view is a system image that uses the Swift symbol.
/// The image next to the Small text is slightly smaller than the text.
/// The image next to the Medium text matches the size of the text. The
/// image next to the Large text is larger than the
/// text.](SwiftUI-EnvironmentAdditions-Image-scale.png)
///
@available(macOS 11.0, *)
public enum Scale {
/// A scale that produces small images.
case small
/// A scale that produces medium-sized images.
case medium
/// A scale that produces large images.
case large
/// 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: Image.Scale, b: Image.Scale) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image {
/// The level of quality for rendering an image that requires interpolation,
/// such as a scaled image.
///
/// The ``Image/interpolation(_:)`` modifier specifies the interpolation
/// behavior when using the ``Image/resizable(capInsets:resizingMode:)``
/// modifier on an ``Image``. Use this behavior to prioritize rendering
/// performance or image quality.
public enum Interpolation {
/// A value that indicates SwiftUI doesn't interpolate image data.
case none
/// A value that indicates a low level of interpolation quality, which may
/// speed up image rendering.
case low
/// A value that indicates a medium level of interpolation quality,
/// between the low- and high-quality values.
case medium
/// A value that indicates a high level of interpolation quality, which
/// may slow down image rendering.
case high
/// 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: Image.Interpolation, b: Image.Interpolation) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image {
/// Specifies the current level of quality for rendering an
/// image that requires interpolation.
///
/// See the article <doc:Fitting-Images-into-Available-Space> for examples
/// of using `interpolation(_:)` when scaling an ``Image``.
/// - Parameter interpolation: The quality level, expressed as a value of
/// the `Interpolation` type, that SwiftUI applies when interpolating
/// an image.
/// - Returns: An image with the given interpolation value set.
public func interpolation(_ interpolation: Image.Interpolation) -> Image
/// Specifies whether SwiftUI applies antialiasing when rendering
/// the image.
/// - Parameter isAntialiased: A Boolean value that specifies whether to
/// allow antialiasing. Pass `true` to allow antialising, `false` otherwise.
/// - Returns: An image with the antialiasing behavior set.
public func antialiased(_ isAntialiased: Bool) -> Image
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Image {
/// Sets the rendering mode for symbol images within this view.
///
/// - Parameter mode: The symbol rendering mode to use.
///
/// - Returns: A view that uses the rendering mode you supply.
public func symbolRenderingMode(_ mode: SymbolRenderingMode?) -> Image
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image {
/// Creates a labeled image based on a Core Graphics image instance, usable
/// as content for controls.
///
/// - Parameters:
/// - cgImage: The base graphical image.
/// - scale: The scale factor for the image,
/// with a value like `1.0`, `2.0`, or `3.0`.
/// - orientation: The orientation of the image. The default is
/// ``Image/Orientation/up``.
/// - label: The label associated with the image. SwiftUI uses the label
/// for accessibility.
public init(_ cgImage: CGImage, scale: CGFloat, orientation: Image.Orientation = .up, label: Text)
/// Creates an unlabeled, decorative image based on a Core Graphics image
/// instance.
///
/// SwiftUI ignores this image for accessibility purposes.
///
/// - Parameters:
/// - cgImage: The base graphical image.
/// - scale: The scale factor for the image,
/// with a value like `1.0`, `2.0`, or `3.0`.
/// - orientation: The orientation of the image. The default is
/// ``Image/Orientation/up``.
public init(decorative cgImage: CGImage, scale: CGFloat, orientation: Image.Orientation = .up)
}
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@available(macOS, unavailable)
extension Image {
/// Creates a SwiftUI image from a UIKit image instance.
/// - Parameter uiImage: The UIKit image to wrap with a SwiftUI ``Image``
/// instance.
public init(uiImage: UIImage)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image {
/// The modes that SwiftUI uses to resize an image to fit within its containing view.
public enum ResizingMode {
/// A mode to repeat the image at its original size, as many times as
/// necessary to fill the available space.
case tile
/// A mode to enlarge or reduce the size of an image so that it fills the available space.
case stretch
/// 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: Image.ResizingMode, b: Image.ResizingMode) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
/// Sets the mode by which SwiftUI resizes an image to fit its space.
/// - Parameters:
/// - capInsets: Inset values that indicate a portion of the image that
/// SwiftUI doesn't resize.
/// - resizingMode: The mode by which SwiftUI resizes the image.
/// - Returns: An image, with the new resizing behavior set.
public func resizable(capInsets: EdgeInsets = EdgeInsets(), resizingMode: Image.ResizingMode = .stretch) -> Image
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image.Orientation : RawRepresentable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image.Orientation : Sendable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image.TemplateRenderingMode : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image.TemplateRenderingMode : Hashable {
}
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 11.0, *)
extension Image.Scale : Equatable {
}
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 11.0, *)
extension Image.Scale : Hashable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image.Interpolation : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image.Interpolation : Hashable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image.ResizingMode : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image.ResizingMode : Hashable {
}
/// A shape style that fills a shape by repeating a region of an image.
///
/// Do not use this type directly. Use ``ShapeStyle/image(_:sourceRect:scale:)``
/// instead.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct ImagePaint : ShapeStyle {
/// The image to be drawn.
public var image: Image
/// A unit-space rectangle defining how much of the source image to draw.
///
/// The results are undefined if this rectangle selects areas outside the
/// `[0, 1]` range in either axis.
public var sourceRect: CGRect
/// A scale factor applied to the image while being drawn.
public var scale: CGFloat
/// Creates a shape-filling shape style.
///
/// - Parameters:
/// - image: The image to be drawn.
/// - sourceRect: A unit-space rectangle defining how much of the source
/// image to draw. The results are undefined if `sourceRect` selects
/// areas outside the `[0, 1]` range in either axis.
/// - scale: A scale factor applied to the image during rendering.
public init(image: Image, sourceRect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1), scale: CGFloat = 1)
}
/// Defines the implementation of all `IndexView` instances within a view
/// hierarchy.
///
/// To configure the current `IndexViewStyle` for a view hierarchy, use the
/// `.indexViewStyle()` modifier.
@available(iOS 14.0, tvOS 14.0, watchOS 8.0, *)
@available(macOS, unavailable)
public protocol IndexViewStyle {
}
@available(iOS 14.0, tvOS 14.0, watchOS 8.0, *)
@available(macOS, unavailable)
extension IndexViewStyle where Self == PageIndexViewStyle {
/// An index view style that places a page index view over its content.
public static var page: PageIndexViewStyle { get }
/// An index view style that places a page index view over its content.
///
/// - Parameter backgroundDisplayMode: The display mode of the background of
/// any page index views receiving this style
public static func page(backgroundDisplayMode: PageIndexViewStyle.BackgroundDisplayMode) -> PageIndexViewStyle
}
/// A `PickerStyle` where each option is displayed inline with other views in
/// the current container.
///
/// Do not use this type directly. Instead, use ``PickerStyle/inline``.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct InlinePickerStyle : PickerStyle {
/// Creates an inline picker style.
public init()
}
/// The list style that describes the behavior and appearance of an inset
/// grouped list.
///
/// Do not use this type directly. Instead, use ``ListStyle/insetGrouped``.
@available(iOS 14.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct InsetGroupedListStyle : ListStyle {
/// Creates an inset grouped list style.
public init()
}
/// The list style that describes the behavior and appearance of an inset list.
///
/// Do not use this type directly. Instead, use ``ListStyle/inset``.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct InsetListStyle : ListStyle {
/// Creates an inset list style.
public init()
}
/// A shape type that is able to inset itself to produce another shape.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol InsettableShape : Shape {
/// The type of the inset shape.
associatedtype InsetShape : InsettableShape
/// Returns `self` inset by `amount`.
func inset(by amount: CGFloat) -> Self.InsetShape
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension InsettableShape {
/// Returns a view that is the result of insetting `self` by
/// `style.lineWidth / 2`, stroking the resulting shape with
/// `style`, and then filling with `content`.
@inlinable public func strokeBorder<S>(_ content: S, style: StrokeStyle, antialiased: Bool = true) -> some View where S : ShapeStyle
/// Returns a view that is the result of insetting `self` by
/// `style.lineWidth / 2`, stroking the resulting shape with
/// `style`, and then filling with the foreground color.
@inlinable public func strokeBorder(style: StrokeStyle, antialiased: Bool = true) -> some View
/// Returns a view that is the result of filling the `width`-sized
/// border (aka inner stroke) of `self` with `content`. This is
/// equivalent to insetting `self` by `width / 2` and stroking the
/// resulting shape with `width` as the line-width.
@inlinable public func strokeBorder<S>(_ content: S, lineWidth: CGFloat = 1, antialiased: Bool = true) -> some View where S : ShapeStyle
/// Returns a view that is the result of filling the `width`-sized
/// border (aka inner stroke) of `self` with the foreground color.
/// This is equivalent to insetting `self` by `width / 2` and
/// stroking the resulting shape with `width` as the line-width.
@inlinable public func strokeBorder(lineWidth: CGFloat = 1, antialiased: Bool = true) -> some View
}
/// The orientation of the interface from the user's perspective.
///
/// By default, device previews appear right side up, using orientation
/// ``InterfaceOrientation/portrait``. You can change the orientation
/// with a call to the ``View/previewInterfaceOrientation(_:)`` modifier:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// CircleImage()
/// .previewInterfaceOrientation(.landscapeRight)
/// }
/// }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct InterfaceOrientation : CaseIterable, Identifiable, Equatable {
/// A collection of all values of this type.
public static var allCases: [InterfaceOrientation] { get }
/// The stable identity of the entity associated with this instance.
public var id: String { get }
/// The device is in portrait mode, with the top of the device on top.
public static let portrait: InterfaceOrientation
/// The device is in portrait mode, but is upside down.
public static let portraitUpsideDown: InterfaceOrientation
/// The device is in landscape mode, with the top of the device on the left.
public static let landscapeLeft: InterfaceOrientation
/// The device is in landscape mode, with the top of the device on the right.
public static let landscapeRight: InterfaceOrientation
/// 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: InterfaceOrientation, b: InterfaceOrientation) -> Bool
/// A type that can represent a collection of all values of this type.
public typealias AllCases = [InterfaceOrientation]
/// A type representing the stable identity of the entity associated with
/// an instance.
public typealias ID = String
}
/// Key equivalents consist of a letter, punctuation, or function key that can
/// be combined with an optional set of modifier keys to specify a keyboard
/// shortcut.
///
/// Key equivalents are used to establish keyboard shortcuts to app
/// functionality. Any key can be used as a key equivalent as long as pressing
/// it produces a single character value. Key equivalents are typically
/// initialized using a single-character string literal, with constants for
/// unprintable or hard-to-type values.
///
/// The modifier keys necessary to type a key equivalent are factored in to the
/// resulting keyboard shortcut. That is, a key equivalent whose raw value is
/// the capitalized string "A" corresponds with the keyboard shortcut
/// Command-Shift-A. The exact mapping may depend on the keyboard layout—for
/// example, a key equivalent with the character value "}" produces a shortcut
/// equivalent to Command-Shift-] on ANSI keyboards, but would produce a
/// different shortcut for keyboard layouts where punctuation characters are in
/// different locations.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct KeyEquivalent {
/// Up Arrow (U+F700)
public static let upArrow: KeyEquivalent
/// Down Arrow (U+F701)
public static let downArrow: KeyEquivalent
/// Left Arrow (U+F702)
public static let leftArrow: KeyEquivalent
/// Right Arrow (U+F703)
public static let rightArrow: KeyEquivalent
/// Escape (U+001B)
public static let escape: KeyEquivalent
/// Delete (U+0008)
public static let delete: KeyEquivalent
/// Delete Forward (U+F728)
public static let deleteForward: KeyEquivalent
/// Home (U+F729)
public static let home: KeyEquivalent
/// End (U+F72B)
public static let end: KeyEquivalent
/// Page Up (U+F72C)
public static let pageUp: KeyEquivalent
/// Page Down (U+F72D)
public static let pageDown: KeyEquivalent
/// Clear (U+F739)
public static let clear: KeyEquivalent
/// Tab (U+0009)
public static let tab: KeyEquivalent
/// Space (U+0020)
public static let space: KeyEquivalent
/// Return (U+000D)
public static let `return`: KeyEquivalent
/// The character value that the key equivalent represents.
public var character: Character
/// Creates a new key equivalent from the given character value.
public init(_ character: Character)
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension KeyEquivalent : ExpressibleByExtendedGraphemeClusterLiteral {
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
public init(extendedGraphemeClusterLiteral: Character)
/// A type that represents an extended grapheme cluster literal.
///
/// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,
/// `String`, and `StaticString`.
public typealias ExtendedGraphemeClusterLiteralType = Character
/// A type that represents a Unicode scalar literal.
///
/// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,
/// `Character`, `String`, and `StaticString`.
public typealias UnicodeScalarLiteralType = Character
}
/// Keyboard shortcuts describe combinations of keys on a keyboard that the user
/// can press in order to activate a button or toggle.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct KeyboardShortcut {
/// Options for how a keyboard shortcut participates in automatic localization.
///
/// A shortcut's `key` that is defined on an US-English keyboard
/// layout might not be reachable on international layouts.
/// For example the shortcut `⌘[` works well for the US layout but is
/// hard to reach for German users.
/// On the German keyboard layout, pressing `⌥5` will produce
/// `[`, which causes the shortcut to become `⌥⌘5`.
/// If configured, which is the default behavior, automatic shortcut
/// remapping will convert it to `⌘Ö`.
///
/// In addition to that, some keyboard shortcuts carry information
/// about directionality.
/// Right-aligning a block of text or seeking forward in context of music
/// playback are such examples. These kinds of shortcuts benefit from the option
/// ``KeyboardShortcut/Localization-swift.struct/withoutMirroring``
/// to tell the system that they won't be flipped when running in a
/// right-to-left context.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct Localization {
/// Remap shortcuts to their international counterparts, mirrored for
/// right-to-left usage if appropriate.
///
/// This is the default configuration.
public static let automatic: KeyboardShortcut.Localization
/// Don't mirror shortcuts.
///
/// Use this for shortcuts that always have a specific directionality, like
/// aligning something on the right.
///
/// Don't use this option for navigational shortcuts like "Go Back" because navigation
/// is flipped in right-to-left contexts.
public static let withoutMirroring: KeyboardShortcut.Localization
/// Don't use automatic shortcut remapping.
///
/// When you use this mode, you have to take care of international use-cases separately.
public static let custom: KeyboardShortcut.Localization
}
/// The standard keyboard shortcut for the default button, consisting of
/// the Return (↩) key and no modifiers.
///
/// On macOS, the default button is designated with special coloration. If
/// more than one control is assigned this shortcut, only the first one is
/// emphasized.
public static let defaultAction: KeyboardShortcut
/// The standard keyboard shortcut for cancelling the in-progress action
/// or dismissing a prompt, consisting of the Escape (⎋) key and no
/// modifiers.
public static let cancelAction: KeyboardShortcut
/// The key equivalent that the user presses in conjunction with any
/// specified modifier keys to activate the shortcut.
public var key: KeyEquivalent
/// The modifier keys that the user presses in conjunction with a key
/// equivalent to activate the shortcut.
public var modifiers: EventModifiers
/// The localization strategy to apply to this shortcut.
public var localization: KeyboardShortcut.Localization
/// Creates a new keyboard shortcut with the given key equivalent and set of
/// modifier keys.
///
/// The localization configuration defaults to ``KeyboardShortcut/Localization-swift.struct/automatic``.
public init(_ key: KeyEquivalent, modifiers: EventModifiers = .command)
/// Creates a new keyboard shortcut with the given key equivalent and set of
/// modifier keys.
///
/// Use the `localization` parameter to specify a localization strategy
/// for this shortcut.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public init(_ key: KeyEquivalent, modifiers: EventModifiers = .command, localization: KeyboardShortcut.Localization)
}
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension KeyboardShortcut : Hashable {
/// 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: KeyboardShortcut, rhs: KeyboardShortcut) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
/// A standard label for user interface items, consisting of an icon with a
/// title.
///
/// One of the most common and recognizable user interface components is the
/// combination of an icon and a label. This idiom appears across many kinds of
/// apps and shows up in collections, lists, menus of action items, and
/// disclosable lists, just to name a few.
///
/// You create a label, in its simplest form, by providing a title and the name
/// of an image, such as an icon from the
/// [SF Symbols](https://developer.apple.com/design/human-interface-guidelines/sf-symbols/overview/)
/// collection:
///
/// Label("Lightning", systemImage: "bolt.fill")
///
/// You can also apply styles to labels in several ways. In the case of dynamic
/// changes to the view after device rotation or change to a window size you
/// might want to show only the text portion of the label using the
/// ``LabelStyle/titleOnly`` label style:
///
/// Label("Lightning", systemImage: "bolt.fill")
/// .labelStyle(.titleOnly)
///
/// Conversely, there's also an icon-only label style:
///
/// Label("Lightning", systemImage: "bolt.fill")
/// .labelStyle(.iconOnly)
///
/// Some containers might apply a different default label style, such as only
/// showing icons within toolbars on macOS and iOS. To opt in to showing both
/// the title and the icon, you can apply the ``LabelStyle/titleAndIcon`` label
/// style:
///
/// Label("Lightning", systemImage: "bolt.fill")
/// .labelStyle(.titleAndIcon)
///
/// You can also create a customized label style by modifying an existing
/// style; this example adds a red border to the default label style:
///
/// struct RedBorderedLabelStyle: LabelStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// Label(configuration)
/// .border(Color.red)
/// }
/// }
///
/// For more extensive customization or to create a completely new label style,
/// you'll need to adopt the ``LabelStyle`` protocol and implement a
/// ``LabelStyleConfiguration`` for the new style.
///
/// To apply a common label style to a group of labels, apply the style
/// to the view hierarchy that contains the labels:
///
/// VStack {
/// Label("Rain", systemImage: "cloud.rain")
/// Label("Snow", systemImage: "snow")
/// Label("Sun", systemImage: "sun.max")
/// }
/// .labelStyle(.iconOnly)
///
/// It's also possible to make labels using views to compose the label's icon
/// programmatically, rather than using a pre-made image. In this example, the
/// icon portion of the label uses a filled ``Circle`` overlaid
/// with the user's initials:
///
/// Label {
/// Text(person.fullName)
/// .font(.body)
/// .foregroundColor(.primary)
/// Text(person.title)
/// .font(.subheadline)
/// .foregroundColor(.secondary)
/// } icon: {
/// Circle()
/// .fill(person.profileColor)
/// .frame(width: 44, height: 44, alignment: .center)
/// .overlay(Text(person.initials))
/// }
///
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct Label<Title, Icon> : View where Title : View, Icon : View {
/// Creates a label with a custom title and icon.
public init(@ViewBuilder title: () -> Title, @ViewBuilder icon: () -> Icon)
/// 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 primitive 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>.
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, tvOS 14.0, watchOS 7.0, *)
extension Label where Title == Text, Icon == Image {
/// Creates a label with an icon image and a title generated from a
/// localized string.
///
/// - Parameters:
/// - titleKey: A title generated from a localized string.
/// - image: The name of the image resource to lookup.
public init(_ titleKey: LocalizedStringKey, image name: String)
/// Creates a label with a system icon image and a title generated from a
/// localized string.
///
/// - Parameters:
/// - titleKey: A title generated from a localized string.
/// - systemImage: The name of the image resource to lookup.
public init(_ titleKey: LocalizedStringKey, systemImage name: String)
/// Creates a label with an icon image and a title generated from a string.
///
/// - Parameters:
/// - title: A string used as the label's title.
/// - image: The name of the image resource to lookup.
public init<S>(_ title: S, image name: String) where S : StringProtocol
/// Creates a label with a system icon image and a title generated from a
/// string.
///
/// - Parameters:
/// - title: A string used as the label's title.
/// - systemImage: The name of the image resource to lookup.
public init<S>(_ title: S, systemImage name: String) where S : StringProtocol
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Label where Title == LabelStyleConfiguration.Title, Icon == LabelStyleConfiguration.Icon {
/// Creates a label representing the configuration of a style.
///
/// You can use this initializer within the ``LabelStyle/makeBody(configuration:)``
/// method of a ``LabelStyle`` instance to create an instance of the label
/// that's being styled. This is useful for custom label styles that only
/// wish to modify the current style, as opposed to implementing a brand new
/// style.
///
/// For example, the following style adds a red border around the label,
/// but otherwise preserves the current style:
///
/// struct RedBorderedLabelStyle: LabelStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// Label(configuration)
/// .border(Color.red)
/// }
/// }
///
/// - Parameter configuration: The label style to use.
public init(_ configuration: LabelStyleConfiguration)
}
/// A type that applies a custom appearance to all labels within a view.
///
/// To configure the current label style for a view hierarchy, use the
/// ``View/labelStyle(_:)`` modifier.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public protocol LabelStyle {
/// A view that represents the body of a label.
associatedtype Body : View
/// 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.
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a label.
typealias Configuration = LabelStyleConfiguration
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension LabelStyle where Self == IconOnlyLabelStyle {
/// A label style that only displays the icon of the label.
///
/// The title of the label is still used for non-visual descriptions, such as
/// VoiceOver.
public static var iconOnly: IconOnlyLabelStyle { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension LabelStyle where Self == TitleOnlyLabelStyle {
/// A label style that only displays the title of the label.
public static var titleOnly: TitleOnlyLabelStyle { get }
}
@available(iOS 14.5, macOS 11.3, tvOS 14.5, watchOS 7.4, *)
extension LabelStyle where Self == TitleAndIconLabelStyle {
/// A label style that shows both the title and icon of the label using a
/// system-standard layout.
///
/// In most cases, labels show both their title and icon by default. However,
/// some containers might apply a different default label style to their
/// content, such as only showing icons within toolbars on macOS and iOS. To
/// opt in to showing both the title and the icon, you can apply the title
/// and icon label style:
///
/// Label("Lightning", systemImage: "bolt.fill")
/// .labelStyle(.titleAndIcon)
///
/// To apply the title and icon style to a group of labels, apply the style
/// to the view hierarchy that contains the labels:
///
/// VStack {
/// Label("Rain", systemImage: "cloud.rain")
/// Label("Snow", systemImage: "snow")
/// Label("Sun", systemImage: "sun.max")
/// }
/// .labelStyle(.titleAndIcon)
///
/// The relative layout of the title and icon is dependent on the context it
/// is displayed in. In most cases, however, the label is arranged
/// horizontally with the icon leading.
public static var titleAndIcon: TitleAndIconLabelStyle { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension LabelStyle where Self == DefaultLabelStyle {
/// A label style that resolves its appearance automatically based on the
/// current context.
public static var automatic: DefaultLabelStyle { get }
}
/// The properties of a label.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct LabelStyleConfiguration {
/// A type-erased title view of a label.
public struct Title {
/// 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 icon view of a label.
public struct Icon {
/// 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 labeled item.
public var title: LabelStyleConfiguration.Title { get }
/// A symbolic representation of the labeled item.
public var icon: LabelStyleConfiguration.Icon { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension LabelStyleConfiguration.Title : View {
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension LabelStyleConfiguration.Icon : View {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum LayoutDirection : Hashable, CaseIterable {
case leftToRight
case rightToLeft
/// 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: LayoutDirection, b: LayoutDirection) -> 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: Never call `finalize()` on `hasher`. 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 = [LayoutDirection]
/// A collection of all values of this type.
public static var allCases: [LayoutDirection] { 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.
public var hashValue: Int { get }
}
extension LayoutDirection {
/// Create a direction from its UITraitEnvironmentLayoutDirection equivalent.
@available(iOS 14.0, tvOS 14.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
public init?(_ uiLayoutDirection: UITraitEnvironmentLayoutDirection)
}
/// A container view that arranges its child views in a grid that
/// grows horizontally, creating items only as needed.
///
/// The grid is "lazy," in that the grid view does not create items until
/// they are needed.
///
/// In the following example, a ``ScrollView`` contains a `LazyHGrid` that
/// consists of a horizontally-arranged grid of ``Text`` views, aligned to
/// the top of the scroll view. For each column in the grid, the top row shows
/// a Unicode code point from the "Smileys" group, and the bottom shows its
/// corresponding emoji.
///
/// var rows: [GridItem] =
/// Array(repeating: .init(.fixed(20)), count: 2)
/// ScrollView(.horizontal) {
/// LazyHGrid(rows: rows, alignment: .top) {
/// ForEach((0...79), id: \.self) {
/// let codepoint = $0 + 0x1f600
/// let codepointString = String(format: "%02X", codepoint)
/// Text("\(codepointString)")
/// .font(.footnote)
/// let emoji = String(Character(UnicodeScalar(codepoint)!))
/// Text("\(emoji)")
/// .font(.largeTitle)
/// }
/// }
/// }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct LazyHGrid<Content> : View where Content : View {
/// Creates a grid that grows horizontally, given the provided properties.
///
/// - Parameters:
/// - rows: An array of grid items to size and position each column of
/// the grid.
/// - alignment: The alignment of the grid within its parent view.
/// - spacing: The spacing between the grid and the next item in its
/// parent view.
/// - pinnedViews: Views to pin to the bounds of a parent scroll view.
/// - content: The content of the grid.
public init(rows: [GridItem], alignment: VerticalAlignment = .center, spacing: CGFloat? = nil, pinnedViews: PinnedScrollableViews = .init(), @ViewBuilder 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 view that arranges its children in a line that grows horizontally,
/// creating items only as needed.
///
/// The stack is "lazy," in that the stack view doesn't create items until
/// it needs to render them onscreen.
///
/// In the following example, a ``ScrollView`` contains a `LazyHStack` that
/// consists of a horizontal row of text views. The stack aligns to the top
/// of the scroll view and uses 10-point spacing between each text view.
///
/// ScrollView(.horizontal) {
/// LazyHStack(alignment: .top, spacing: 10) {
/// ForEach(1...100, id: \.self) {
/// Text("Column \($0)")
/// }
/// }
/// }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct LazyHStack<Content> : View where Content : View {
/// Creates a lazy horizontal stack view with the given spacing,
/// vertical alignment, pinning behavior, and content.
///
/// - Parameters:
/// - alignment: The guide for aligning the subviews in this stack. All
/// child views have the same vertical screen coordinate.
/// - spacing: The distance between adjacent subviews, or `nil` if you
/// want the stack to choose a default distance for each pair of
/// subviews.
/// - pinnedViews: The kinds of child views that will be pinned.
/// - content: A view builder that creates the content of this stack.
public init(alignment: VerticalAlignment = .center, spacing: CGFloat? = nil, pinnedViews: PinnedScrollableViews = .init(), @ViewBuilder 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 container view that arranges its child views in a grid that
/// grows vertically, creating items only as needed.
///
/// The grid is "lazy," in that the grid view does not create items until
/// they are needed.
///
/// In the following example, a ``ScrollView`` contains a
/// `LazyVGrid` consisting of a two-column grid of ``Text`` views, showing
/// Unicode code points from the "Smileys" group and their corresponding emoji:
///
/// var columns: [GridItem] =
/// Array(repeating: .init(.flexible()), count: 2)
/// ScrollView {
/// LazyVGrid(columns: columns) {
/// ForEach((0...79), id: \.self) {
/// let codepoint = $0 + 0x1f600
/// let codepointString = String(format: "%02X", codepoint)
/// Text("\(codepointString)")
/// let emoji = String(Character(UnicodeScalar(codepoint)!))
/// Text("\(emoji)")
/// }
/// }.font(.largeTitle)
/// }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct LazyVGrid<Content> : View where Content : View {
/// Creates a grid that grows vertically, given the provided properties.
///
/// - Parameters:
/// - columns: An array of grid items to size and position each row of
/// the grid.
/// - alignment: The alignment of the grid within its parent view.
/// - spacing: The spacing between the grid and the next item in its
/// parent view.
/// - pinnedViews: Views to pin to the bounds of a parent scroll view.
/// - content: The content of the grid.
public init(columns: [GridItem], alignment: HorizontalAlignment = .center, spacing: CGFloat? = nil, pinnedViews: PinnedScrollableViews = .init(), @ViewBuilder 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 view that arranges its children in a line that grows vertically,
/// creating items only as needed.
///
/// The stack is "lazy," in that the stack view doesn't create items until
/// it needs to render them onscreen.
///
/// In the following example, a ``ScrollView`` contains a `LazyVStack` that
/// consists of a vertical row of text views. The stack aligns to the
/// leading edge of the scroll view, and uses default spacing between the
/// text views.
///
/// ScrollView {
/// LazyVStack(alignment: .leading) {
/// ForEach(1...100, id: \.self) {
/// Text("Row \($0)")
/// }
/// }
/// }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct LazyVStack<Content> : View where Content : View {
/// Creates a lazy vertical stack view with the given spacing,
/// vertical alignment, pinning behavior, and content.
///
/// - Parameters:
/// - alignment: The guide for aligning the subviews in this stack. All
/// child views have the same horizontal screen coordinate.
/// - spacing: The distance between adjacent subviews, or `nil` if you
/// want the stack to choose a default distance for each pair of
/// subviews.
/// - pinnedViews: The kinds of child views that will be pinned.
/// - content: A view builder that creates the content of this stack.
public init(alignment: HorizontalAlignment = .center, spacing: CGFloat? = nil, pinnedViews: PinnedScrollableViews = .init(), @ViewBuilder 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
}
/// The Accessibility Bold Text user setting options.
///
/// The app can't override the user's choice.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum LegibilityWeight : Hashable {
/// Use regular font weight (no Accessibility Bold).
case regular
/// Use heavier font weight (force Accessibility Bold).
case bold
/// 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: LegibilityWeight, b: LegibilityWeight) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
extension LegibilityWeight {
/// Creates a legibility weight from its UILegibilityWeight equivalent.
@available(iOS 14.0, tvOS 14.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
public init?(_ uiLegibilityWeight: UILegibilityWeight)
}
/// A linear gradient.
///
/// The gradient applies the color function along an axis, as defined by its
/// start and end points. The gradient maps the unit space points into the
/// bounding rectangle of each shape filled with the gradient.
///
/// When using a linear gradient as a shape style, you can also use
/// ``ShapeStyle/linearGradient(_:startPoint:endPoint:)``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct LinearGradient : ShapeStyle, View {
/// Creates a linear gradient from a base gradient.
public init(gradient: Gradient, startPoint: UnitPoint, endPoint: UnitPoint)
/// Creates a linear gradient from a collection of colors.
public init(colors: [Color], startPoint: UnitPoint, endPoint: UnitPoint)
/// Creates a linear gradient from a collection of color stops.
public init(stops: [Gradient.Stop], startPoint: UnitPoint, endPoint: UnitPoint)
/// 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 progress view that visually indicates its progress using a horizontal bar.
///
/// Do not use this type directly. Instead, use ``ProgressViewStyle/linear``.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct LinearProgressViewStyle : ProgressViewStyle {
/// Creates a linear progress view style.
public init()
/// Creates a linear 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.")
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: LinearProgressViewStyle.Configuration) -> some View
/// A view representing the body of a progress view.
public typealias Body = some View
}
/// A control for navigating to a URL.
///
/// You create a link by providing a destination URL and a title. The title
/// tells the user the purpose of the link, which can be either a string, or a
/// title key that returns a localized string used to construct a label
/// displayed to the user in your app's UI. The example below creates a link to
/// `example.com` and displays the title string you provide as a
/// link-styled view in your app:
///
/// Link("View Our Terms of Service",
/// destination: URL(string: "https://www.example.com/TOS.html")!)
///
/// When a user taps or clicks a `Link`, where the URL opens depends on the
/// contents of the URL. For example, a Universal Link will open in the
/// associated app, if possible, but otherwise in the user's default web
/// browser.
///
/// As with other views, you can style links using standard view modifiers
/// depending on the view type of the link's label. For example, a ``Text``
/// label could be modified with a custom ``View/font(_:)`` or
/// ``View/foregroundColor(_:)`` to customize the appearance of the link in
/// your app's UI.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct Link<Label> : View where Label : View {
/// Creates a control, consisting of a URL and a label, used to navigate
/// to the given URL.
///
/// - Parameters:
/// - destination: The URL for the link.
/// - label: A view that describes the destination of URL.
public init(destination: URL, @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 primitive 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>.
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, tvOS 14.0, watchOS 7.0, *)
extension Link where Label == Text {
/// Creates a control, consisting of a URL and a title key, used to
/// navigate to a URL.
///
/// Use ``Link`` to create a control that your app uses to navigate to a
/// URL that you provide. The example below creates a link to
/// `example.com` and uses `Visit Example Co` as the title key to
/// generate a link-styled view in your app:
///
/// Link("Visit Example Co",
/// destination: URL(string: "https://www.example.com/")!)
///
/// - Parameters:
/// - titleKey: The key for the localized title that describes the
/// purpose of this link.
/// - destination: The URL for the link.
public init(_ titleKey: LocalizedStringKey, destination: URL)
/// Creates a control, consisting of a URL and a title string, used to
/// navigate to a URL.
///
/// Use ``Link`` to create a control that your app uses to navigate to a
/// URL that you provide. The example below creates a link to
/// `example.com` and displays the title string you provide as a
/// link-styled view in your app:
///
/// func marketingLink(_ callToAction: String) -> Link {
/// Link(callToAction,
/// destination: URL(string: "https://www.example.com/")!)
/// }
///
/// - Parameters:
/// - title: A text string used as the title for describing the
/// underlying `destination` URL.
/// - destination: The URL for the link.
public init<S>(_ title: S, destination: URL) where S : StringProtocol
}
/// A container that presents rows of data arranged in a single column,
/// optionally providing the ability to select one or more members.
///
/// In its simplest form, a `List` creates its contents statically, as shown in
/// the following example:
///
/// var body: some View {
/// List {
/// Text("A List Item")
/// Text("A Second List Item")
/// Text("A Third List Item")
/// }
/// }
///
/// ![A vertical list with three text views.](SwiftUI-List-static.png)
///
/// More commonly, you create lists dynamically from an underlying collection
/// of data. The following example shows how to create a simple list from an
/// array of an `Ocean` type which conforms to
/// <doc://com.apple.documentation/documentation/Swift/Identifiable>:
///
/// struct Ocean: Identifiable {
/// let name: String
/// let id = UUID()
/// }
/// private var oceans = [
/// Ocean(name: "Pacific"),
/// Ocean(name: "Atlantic"),
/// Ocean(name: "Indian"),
/// Ocean(name: "Southern"),
/// Ocean(name: "Arctic")
/// ]
///
/// var body: some View {
/// List(oceans) {
/// Text($0.name)
/// }
/// }
///
/// ![A vertical list with five text views, each with the name of an
/// ocean.](SwiftUI-List-collection.png)
///
/// ### Supporting Selection in Lists
///
/// To make members of a list selectable, provide a binding to a selection
/// variable. Binding to a single instance of the list data's `Identifiable.ID`
/// type creates a single-selection list. Binding to a
/// <doc://com.apple.documentation/documentation/Swift/Set> creates a list that
/// supports multiple selections. The following example shows how to add
/// multi-select to the previous
/// example. A ``Text`` view below the list shows the number of items
/// currently selected.
///
/// struct Ocean: Identifiable, Hashable {
/// let name: String
/// let id = UUID()
/// }
/// private var oceans = [
/// Ocean(name: "Pacific"),
/// Ocean(name: "Atlantic"),
/// Ocean(name: "Indian"),
/// Ocean(name: "Southern"),
/// Ocean(name: "Arctic")
/// ]
/// @State private var multiSelection = Set<UUID>()
///
/// var body: some View {
/// NavigationView {
/// List(oceans, selection: $multiSelection) {
/// Text($0.name)
/// }
/// .navigationTitle("Oceans")
/// .toolbar { EditButton() }
/// }
/// Text("\(multiSelection.count) selections")
/// }
///
/// ![A navigation view with the title Oceans and an active edit button with
/// the title Done. Below this, a vertical list with five text views, each with
/// the name of an ocean. Each text view has a circle to indicate selectability,
/// and two of these circles are selected. At the bottom, a text view reads
/// 2 selection(s).](SwiftUI-List-multi-selection.png)
///
/// ### Refreshing the List Content
///
/// To make the content of the list refreshable using the standard refresh
/// control, use the ``View/refreshable(action:)`` modifier.
///
/// The following example shows how to add a standard refresh control to a list.
/// When the user drags the top of the list downward, SwiftUI reveals the refresh
/// control and executes the specified action. Use an `await` expression
/// inside the `action` closure to refresh your data. The refresh indicator remains
/// visible for the duration of the awaited operation.
///
/// struct Ocean: Identifiable, Hashable {
/// let name: String
/// let id = UUID()
/// let stats: [String: String]
/// }
/// class OceanStore: ObservableObject {
/// @Published var oceans = [Ocean]()
/// func loadStats() async -> Void {}
/// }
/// @EnvironmentObject var store: OceanStore
/// var body: some View {
/// NavigationView {
/// List(store.oceans) { ocean in
/// HStack {
/// Text(ocean.name)
/// StatsSummary(stats: ocean.stats) // A custom view for showing statistics.
/// }
/// }
/// .refreshable {
/// await store.loadStats()
/// }
/// .navigationTitle("Oceans")
/// }
/// }
///
/// ### Supporting Multi-Dimensional Lists
///
/// To support two-dimensional lists, your list's content can create instances
/// of the ``Section`` type, which then provide their own contents.
///
/// The following example creates sections named after the world's oceans,
/// each of which has ``Text`` children named for major seas attached to those
/// oceans. The example also allows for selection of a single list item,
/// identified by the `id` of the example's `Sea` type.
///
/// struct ContentView: View {
/// struct Sea: Hashable, Identifiable {
/// let name: String
/// let id = UUID()
/// }
/// struct OceanRegion: Identifiable {
/// let name: String
/// let seas: [Sea]
/// let id = UUID()
/// }
/// private let oceanRegions: [OceanRegion] = [
/// OceanRegion(name: "Pacific",
/// seas: [Sea(name: "Australasian Mediterranean"),
/// Sea(name: "Philippine"),
/// Sea(name: "Coral"),
/// Sea(name: "South China")]),
/// OceanRegion(name: "Atlantic",
/// seas: [Sea(name: "American Mediterranean"),
/// Sea(name: "Sargasso"),
/// Sea(name: "Caribbean")]),
/// OceanRegion(name: "Indian",
/// seas: [Sea(name: "Bay of Bengal")]),
/// OceanRegion(name: "Southern",
/// seas: [Sea(name:"Weddell")]),
/// OceanRegion(name: "Arctic",
/// seas: [Sea(name: "Greenland")])
/// ]
/// @State private var singleSelection : UUID?
///
/// var body: some View {
/// NavigationView {
/// List(selection: $singleSelection){
/// ForEach(oceanRegions) { region in
/// Section(header: Text("Major \(region.name) Ocean Seas")) {
/// ForEach(region.seas) { sea in
/// Text(sea.name)
/// }
/// }
/// }
/// }
/// .navigationTitle("Oceans and Seas")
/// .toolbar { EditButton() }
/// }
/// }
/// }
///
/// ![A vertical list split into sections titled Major Pacific Ocean Seas,
/// Major Atlantic Ocean Seas, etc. Each section has a different number of
/// rows, with the names of various seas. Within the Major Atlantic Ocean
/// Seas section, the row Sargasso is
/// selected.](SwiftUI-List-sections-defaultListStyle.png)
///
/// ### Creating Hierarchical Lists
///
/// You can also create a hierarchical list of arbitrary depth by providing
/// tree-structured data and a `children` parameter that provides a key path to
/// get the child nodes at any level. The following example uses a deeply-nested
/// collection of a custom `FileItem` type to simulate the contents of a
/// file system. The list created from this data uses collapsing cells to allow
/// the user to navigate the tree structure.
///
/// struct ContentView: View {
/// struct FileItem: Hashable, Identifiable, CustomStringConvertible {
/// var id: Self { self }
/// var name: String
/// var children: [FileItem]? = nil
/// var description: String {
/// switch children {
/// case nil:
/// return "📄 \(name)"
/// case .some(let children):
/// return children.isEmpty ? "📂 \(name)" : "📁 \(name)"
/// }
/// }
/// }
/// let fileHierarchyData: [FileItem] = [
/// FileItem(name: "users", children:
/// [FileItem(name: "user1234", children:
/// [FileItem(name: "Photos", children:
/// [FileItem(name: "photo001.jpg"),
/// FileItem(name: "photo002.jpg")]),
/// FileItem(name: "Movies", children:
/// [FileItem(name: "movie001.mp4")]),
/// FileItem(name: "Documents", children: [])
/// ]),
/// FileItem(name: "newuser", children:
/// [FileItem(name: "Documents", children: [])
/// ])
/// ]),
/// FileItem(name: "private", children: nil)
/// ]
/// var body: some View {
/// List(fileHierarchyData, children: \.children) { item in
/// Text(item.description)
/// }
/// }
/// }
///
/// ![A list providing a drill-down view of a tree structure. Each row
/// expands to show its children, which are indented slightly. The top row
/// is titled users, with users1234 below it, below which are rows titled
/// Photos, Movies, and Documents, each with a folder
/// icon.](SwiftUI-List-hierarchical.png)
///
/// ### Styling Lists
///
/// SwiftUI chooses a display style for a list based on the platform and the
/// view type in which it appears. Use the ``View/listStyle(_:)`` modifier to
/// apply a different ``ListStyle`` to all lists within a view. For example,
/// adding `.listStyle(.insetGrouped)` to the example shown in the
/// "Creating Multi-Dimensional Lists" topic applies the
/// ``ListStyle/insetGrouped`` style, as seen in the following screenshot.
///
/// ![A vertical list split into sections titled Major Pacific Ocean Seas,
/// Major Atlantic Ocean Seas, etc. Each section has a different number of
/// rows, with the names of various seas. Within the Major Atlantic Ocean
/// Seas section, the row Sargasso is selected. The sections display a border
/// around the sides of each list item, connecting with the section headers,
/// which provides a visual grouping not provided by the default list
/// style.](SwiftUI-List-sections-insetGroupedListStyle.png)
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct List<SelectionValue, Content> : View where SelectionValue : Hashable, Content : View {
/// Creates a list with the given content that supports selecting multiple
/// rows.
///
/// On iOS and tvOS, you must explicitly put the list into edit mode for
/// the selection to apply.
///
/// - Parameters:
/// - selection: A binding to a set that identifies selected rows.
/// - content: The content of the list.
@available(watchOS, unavailable)
public init(selection: Binding<Set<SelectionValue>>?, @ViewBuilder content: () -> Content)
/// Creates a list with the given content that supports selecting a single
/// row.
///
/// On iOS and tvOS, you must explicitly put the list into edit mode for
/// the selection to apply.
///
/// - Parameters:
/// - selection: A binding to a selected row.
/// - content: The content of the list.
@available(watchOS, unavailable)
public init(selection: Binding<SelectionValue?>?, @ViewBuilder content: () -> Content)
/// The content of the list.
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 List {
/// Creates a list that computes its rows on demand from an underlying
/// collection of identifiable data, optionally allowing users to select
/// multiple rows.
///
/// - Parameters:
/// - data: The identifiable data for computing the list.
/// - selection: A binding to a set that identifies selected rows.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<Data, RowContent>(_ data: Data, selection: Binding<Set<SelectionValue>>?, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == ForEach<Data, Data.Element.ID, RowContent>, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable
/// Creates a hierarchical list that computes its rows on demand from an
/// underlying collection of identifiable data, optionally allowing users to
/// select multiple rows.
///
/// - Parameters:
/// - data: The identifiable data for computing the list.
/// - selection: A binding to a set that identifies selected rows.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public init<Data, RowContent>(_ data: Data, children: KeyPath<Data.Element, Data?>, selection: Binding<Set<SelectionValue>>?, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == OutlineGroup<Data, Data.Element.ID, RowContent, RowContent, DisclosureGroup<RowContent, OutlineSubgroupChildren>>, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable
/// Creates a list that identifies its rows based on a key path to the
/// identifier of the underlying data, optionally allowing users to select
/// multiple rows.
///
/// - Parameters:
/// - data: The data for populating the list.
/// - id: The key path to the data model's identifier.
/// - selection: A binding to a set that identifies selected rows.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<Data, ID, RowContent>(_ data: Data, id: KeyPath<Data.Element, ID>, selection: Binding<Set<SelectionValue>>?, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == ForEach<Data, ID, RowContent>, Data : RandomAccessCollection, ID : Hashable, RowContent : View
/// Creates a hierarchical list that identifies its rows based on a key path
/// to the identifier of the underlying data, optionally allowing users to
/// select multiple rows.
///
/// - Parameters:
/// - data: The data for populating the list.
/// - id: The key path to the data model's identifier.
/// - children: A key path to a property whose non-`nil` value gives the
/// children of `data`. A non-`nil` but empty value denotes a node capable
/// of having children that is currently childless, such as an empty
/// directory in a file system. On the other hand, if the property at the
/// key path is `nil`, then `data` is treated as a leaf node in the tree,
/// like a regular file in a file system.
/// - selection: A binding to a set that identifies selected rows.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public init<Data, ID, RowContent>(_ data: Data, id: KeyPath<Data.Element, ID>, children: KeyPath<Data.Element, Data?>, selection: Binding<Set<SelectionValue>>?, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == OutlineGroup<Data, ID, RowContent, RowContent, DisclosureGroup<RowContent, OutlineSubgroupChildren>>, Data : RandomAccessCollection, ID : Hashable, RowContent : View
/// Creates a list that computes its views on demand over a constant range,
/// optionally allowing users to select multiple rows.
///
/// This instance only reads the initial value of `data` and doesn't need to
/// identify views across updates. To compute views on demand over a dynamic
/// range, use ``List/init(_:id:selection:rowContent:)-8ef64``.
///
/// - Parameters:
/// - data: A constant range of data to populate the list.
/// - selection: A binding to a set that identifies selected rows.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<RowContent>(_ data: Range<Int>, selection: Binding<Set<SelectionValue>>?, @ViewBuilder rowContent: @escaping (Int) -> RowContent) where Content == ForEach<Range<Int>, Int, HStack<RowContent>>, RowContent : View
/// Creates a list that computes its rows on demand from an underlying
/// collection of identifiable data, optionally allowing users to select a
/// single row.
///
/// - Parameters:
/// - data: The identifiable data for computing the list.
/// - selection: A binding to a selected value.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<Data, RowContent>(_ data: Data, selection: Binding<SelectionValue?>?, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == ForEach<Data, Data.Element.ID, RowContent>, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable
/// Creates a hierarchical list that computes its rows on demand from an
/// underlying collection of identifiable data, optionally allowing users to
/// select a single row.
///
/// - Parameters:
/// - data: The identifiable data for computing the list.
/// - children: A key path to a property whose non-`nil` value gives the
/// children of `data`. A non-`nil` but empty value denotes a node capable
/// of having children that is currently childless, such as an empty
/// directory in a file system. On the other hand, if the property at the
/// key path is `nil`, then `data` is treated as a leaf node in the tree,
/// like a regular file in a file system.
/// - selection: A binding to a selected value.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public init<Data, RowContent>(_ data: Data, children: KeyPath<Data.Element, Data?>, selection: Binding<SelectionValue?>?, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == OutlineGroup<Data, Data.Element.ID, RowContent, RowContent, DisclosureGroup<RowContent, OutlineSubgroupChildren>>, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable
/// Creates a list that identifies its rows based on a key path to the
/// identifier of the underlying data, optionally allowing users to select a
/// single row.
///
/// - Parameters:
/// - data: The data for populating the list.
/// - id: The key path to the data model's identifier.
/// - selection: A binding to a selected value.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<Data, ID, RowContent>(_ data: Data, id: KeyPath<Data.Element, ID>, selection: Binding<SelectionValue?>?, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == ForEach<Data, ID, RowContent>, Data : RandomAccessCollection, ID : Hashable, RowContent : View
/// Creates a hierarchical list that identifies its rows based on a key path
/// to the identifier of the underlying data, optionally allowing users to
/// select a single row.
///
/// - Parameters:
/// - data: The data for populating the list.
/// - id: The key path to the data model's identifier.
/// - children: A key path to a property whose non-`nil` value gives the
/// children of `data`. A non-`nil` but empty value denotes a node capable
/// of having children that is currently childless, such as an empty
/// directory in a file system. On the other hand, if the property at the
/// key path is `nil`, then `data` is treated as a leaf node in the tree,
/// like a regular file in a file system.
/// - selection: A binding to a selected value.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public init<Data, ID, RowContent>(_ data: Data, id: KeyPath<Data.Element, ID>, children: KeyPath<Data.Element, Data?>, selection: Binding<SelectionValue?>?, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == OutlineGroup<Data, ID, RowContent, RowContent, DisclosureGroup<RowContent, OutlineSubgroupChildren>>, Data : RandomAccessCollection, ID : Hashable, RowContent : View
/// Creates a list that computes its views on demand over a constant range,
/// optionally allowing users to select a single row.
///
/// This instance only reads the initial value of `data` and doesn't need to
/// identify views across updates. To compute views on demand over a dynamic
/// range, use ``List/init(_:id:selection:rowContent:)-9r2hz``.
///
/// - Parameters:
/// - data: A constant range of data to populate the list.
/// - selection: A binding to a selected value.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<RowContent>(_ data: Range<Int>, selection: Binding<SelectionValue?>?, @ViewBuilder rowContent: @escaping (Int) -> RowContent) where Content == ForEach<Range<Int>, Int, RowContent>, RowContent : View
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension List where SelectionValue == Never {
/// Creates a list with the given content.
///
/// - Parameter content: The content of the list.
public init(@ViewBuilder content: () -> Content)
/// Creates a list that computes its rows on demand from an underlying
/// collection of identifiable data.
///
/// - Parameters:
/// - data: A collection of identifiable data for computing the list.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
public init<Data, RowContent>(_ data: Data, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == ForEach<Data, Data.Element.ID, RowContent>, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable
/// Creates a hierarchical list that computes its rows on demand from an
/// underlying collection of identifiable data.
///
/// - Parameters:
/// - data: A collection of identifiable data for computing the list.
/// - children: A key path to a property whose non-`nil` value gives the
/// children of `data`. A non-`nil` but empty value denotes a node capable
/// of having children that is currently childless, such as an empty
/// directory in a file system. On the other hand, if the property at the
/// key path is `nil`, then `data` is treated as a leaf node in the tree,
/// like a regular file in a file system.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public init<Data, RowContent>(_ data: Data, children: KeyPath<Data.Element, Data?>, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == OutlineGroup<Data, Data.Element.ID, RowContent, RowContent, DisclosureGroup<RowContent, OutlineSubgroupChildren>>, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable
/// Creates a list that identifies its rows based on a key path to the
/// identifier of the underlying data.
///
/// - Parameters:
/// - data: The data for populating the list.
/// - id: The key path to the data model's identifier.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
public init<Data, ID, RowContent>(_ data: Data, id: KeyPath<Data.Element, ID>, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == ForEach<Data, ID, RowContent>, Data : RandomAccessCollection, ID : Hashable, RowContent : View
/// Creates a hierarchical list that identifies its rows based on a key path
/// to the identifier of the underlying data.
///
/// - Parameters:
/// - data: The data for populating the list.
/// - id: The key path to the data model's identifier.
/// - children: A key path to a property whose non-`nil` value gives the
/// children of `data`. A non-`nil` but empty value denotes a node capable
/// of having children that is currently childless, such as an empty
/// directory in a file system. On the other hand, if the property at the
/// key path is `nil`, then `data` is treated as a leaf node in the tree,
/// like a regular file in a file system.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public init<Data, ID, RowContent>(_ data: Data, id: KeyPath<Data.Element, ID>, children: KeyPath<Data.Element, Data?>, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) where Content == OutlineGroup<Data, ID, RowContent, RowContent, DisclosureGroup<RowContent, OutlineSubgroupChildren>>, Data : RandomAccessCollection, ID : Hashable, RowContent : View
/// Creates a list that computes its views on demand over a constant range.
///
/// This instance only reads the initial value of `data` and doesn't need to
/// identify views across updates. To compute views on demand over a dynamic
/// range, use ``List/init(_:id:rowContent:)``.
///
/// - Parameters:
/// - data: A constant range of data to populate the list.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
public init<RowContent>(_ data: Range<Int>, @ViewBuilder rowContent: @escaping (Int) -> RowContent) where Content == ForEach<Range<Int>, Int, RowContent>, RowContent : View
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension List {
/// Creates a list that computes its rows on demand from an underlying
/// collection of identifiable data, optionally allowing users to select
/// multiple rows.
///
/// - Parameters:
/// - data: The identifiable data for computing the list.
/// - selection: A binding to a set that identifies selected rows.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<Data, RowContent>(_ data: Binding<Data>, selection: Binding<Set<SelectionValue>>?, @ViewBuilder rowContent: @escaping (Binding<Data.Element>) -> RowContent) where Content == ForEach<LazyMapSequence<Data.Indices, (Data.Index, Data.Element.ID)>, Data.Element.ID, RowContent>, Data : MutableCollection, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable, Data.Index : Hashable
/// Creates a list that identifies its rows based on a key path to the
/// identifier of the underlying data, optionally allowing users to select
/// multiple rows.
///
/// - Parameters:
/// - data: The data for populating the list.
/// - id: The key path to the data model's identifier.
/// - selection: A binding to a set that identifies selected rows.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<Data, ID, RowContent>(_ data: Binding<Data>, id: KeyPath<Data.Element, ID>, selection: Binding<Set<SelectionValue>>?, @ViewBuilder rowContent: @escaping (Binding<Data.Element>) -> RowContent) where Content == ForEach<LazyMapSequence<Data.Indices, (Data.Index, ID)>, ID, RowContent>, Data : MutableCollection, Data : RandomAccessCollection, ID : Hashable, RowContent : View, Data.Index : Hashable
/// Creates a list that computes its rows on demand from an underlying
/// collection of identifiable data, optionally allowing users to select a
/// single row.
///
/// - Parameters:
/// - data: The identifiable data for computing the list.
/// - selection: A binding to a selected value.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<Data, RowContent>(_ data: Binding<Data>, selection: Binding<SelectionValue?>?, @ViewBuilder rowContent: @escaping (Binding<Data.Element>) -> RowContent) where Content == ForEach<LazyMapSequence<Data.Indices, (Data.Index, Data.Element.ID)>, Data.Element.ID, RowContent>, Data : MutableCollection, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable, Data.Index : Hashable
/// Creates a list that identifies its rows based on a key path to the
/// identifier of the underlying data, optionally allowing users to select a
/// single row.
///
/// - Parameters:
/// - data: The data for populating the list.
/// - id: The key path to the data model's identifier.
/// - selection: A binding to a selected value.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
@available(watchOS, unavailable)
public init<Data, ID, RowContent>(_ data: Binding<Data>, id: KeyPath<Data.Element, ID>, selection: Binding<SelectionValue?>?, @ViewBuilder rowContent: @escaping (Binding<Data.Element>) -> RowContent) where Content == ForEach<LazyMapSequence<Data.Indices, (Data.Index, ID)>, ID, RowContent>, Data : MutableCollection, Data : RandomAccessCollection, ID : Hashable, RowContent : View, Data.Index : Hashable
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension List where SelectionValue == Never {
/// Creates a list that computes its rows on demand from an underlying
/// collection of identifiable data.
///
/// - Parameters:
/// - data: A collection of identifiable data for computing the list.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
public init<Data, RowContent>(_ data: Binding<Data>, @ViewBuilder rowContent: @escaping (Binding<Data.Element>) -> RowContent) where Content == ForEach<LazyMapSequence<Data.Indices, (Data.Index, Data.Element.ID)>, Data.Element.ID, RowContent>, Data : MutableCollection, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable, Data.Index : Hashable
/// Creates a list that identifies its rows based on a key path to the
/// identifier of the underlying data.
///
/// - Parameters:
/// - data: The data for populating the list.
/// - id: The key path to the data model's identifier.
/// - rowContent: A view builder that creates the view for a single row of
/// the list.
public init<Data, ID, RowContent>(_ data: Binding<Data>, id: KeyPath<Data.Element, ID>, @ViewBuilder rowContent: @escaping (Binding<Data.Element>) -> RowContent) where Content == ForEach<LazyMapSequence<Data.Indices, (Data.Index, ID)>, ID, RowContent>, Data : MutableCollection, Data : RandomAccessCollection, ID : Hashable, RowContent : View, Data.Index : Hashable
}
/// The configuration of a tint effect applied to content within a List.
///
/// - See Also: `View.listItemTint(_:)`
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct ListItemTint {
/// An explicit tint color.
///
/// This tint effect is fixed and not overridable by other
/// system effects.
public static func fixed(_ tint: Color) -> ListItemTint
/// An explicit tint color that is overridable.
///
/// This tint effect is overridable by system effects, for
/// example when the system has a custom user accent
/// color on macOS.
public static func preferred(_ tint: Color) -> ListItemTint
/// A standard grayscale tint effect.
///
/// Monochrome tints are not overridable.
public static let monochrome: ListItemTint
}
/// A protocol that describes the behavior and appearance of a list.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol ListStyle {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ListStyle where Self == DefaultListStyle {
/// The list style that describes a platform's default behavior and
/// appearance for a list.
public static var automatic: DefaultListStyle { get }
}
@available(iOS 14.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ListStyle where Self == SidebarListStyle {
/// The list style that describes the behavior and appearance of a
/// sidebar list.
///
/// On macOS and iOS, the sidebar list style displays disclosure indicators in
/// the section headers that allow the user to collapse and expand sections.
public static var sidebar: SidebarListStyle { get }
}
@available(iOS 14.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ListStyle where Self == InsetGroupedListStyle {
/// The list style that describes the behavior and appearance of an inset
/// grouped list.
///
/// On iOS, the inset grouped list style displays a continuous background color
/// that extends from the section header, around both sides of list items in the
/// section, and down to the section footer. This visually groups the items
/// to a greater degree than either the ``ListStyle/inset`` or
/// ``ListStyle/grouped`` styles do.
public static var insetGrouped: InsetGroupedListStyle { get }
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
@available(watchOS, unavailable)
extension ListStyle where Self == GroupedListStyle {
/// The list style that describes the behavior and appearance of a grouped
/// list.
///
/// On iOS, the grouped list style displays a larger header and footer than
/// the ``ListStyle/plain`` style, which visually distances the members of
/// different sections.
public static var grouped: GroupedListStyle { get }
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ListStyle where Self == InsetListStyle {
/// The list style that describes the behavior and appearance of an inset
/// list.
public static var inset: InsetListStyle { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ListStyle where Self == PlainListStyle {
/// The list style that describes the behavior and appearance of a plain
/// list.
public static var plain: PlainListStyle { get }
}
/// The key used to look up an entry in a strings file or strings dictionary
/// file.
///
/// Initializers for several SwiftUI types -- such as ``Text``, ``Toggle``,
/// ``Picker`` and others -- implicitly look up a localized string when you
/// provide a string literal. When you use the initializer `Text("Hello")`,
/// SwiftUI creates a `LocalizedStringKey` for you and uses that to look up a
/// localization of the `Hello` string. This works because `LocalizedStringKey`
/// conforms to
/// <doc://com.apple.documentation/documentation/Swift/ExpressibleByStringLiteral>.
///
/// Types whose initializers take a `LocalizedStringKey` usually have
/// a corresponding initializer that accepts a parameter that conforms to
/// <doc://com.apple.documentation/documentation/Swift/StringProtocol>. Passing
/// a `String` variable to these initializers avoids localization, which is
/// usually appropriate when the variable contains a user-provided value.
///
/// As a general rule, use a string literal argument when you want
/// localization, and a string variable argument when you don't. In the case
/// where you want to localize the value of a string variable, use the string to
/// create a new `LocalizedStringKey` instance.
///
/// The following example shows how to create ``Text`` instances both
/// with and without localization. The title parameter provided to the
/// ``Section`` is a literal string, so SwiftUI creates a
/// `LocalizedStringKey` for it. However, the string entries in the
/// `messageStore.today` array are `String` variables, so the ``Text`` views
/// in the list use the string values verbatim.
///
/// List {
/// Section(header: Text("Today")) {
/// ForEach(messageStore.today) { message in
/// Text(message.title)
/// }
/// }
/// }
///
/// If the app is localized into Japanese with the following
/// translation of its `Localizable.strings` file:
///
/// ```other
/// "Today" = "今日";
/// ```
///
/// When run in Japanese, the example produces a
/// list like the following, localizing "Today" for the section header, but not
/// the list items.
///
/// ![A list with a single section header displayed in Japanese.
/// The items in the list are all in English: New for Monday, Account update,
/// and Server
/// maintenance.](SwiftUI-LocalizedStringKey-Today-List-Japanese.png)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct LocalizedStringKey : Equatable, ExpressibleByStringInterpolation {
/// Creates a localized string key from the given string value.
///
/// - Parameter value: The string to use as a localization key.
public init(_ value: String)
/// Creates a localized string key from the given string literal.
///
/// - Parameter value: The string literal to use as a localization key.
public init(stringLiteral value: String)
/// Creates a localized string key from the given string interpolation.
///
/// To create a localized string key from a string interpolation, use
/// the `\()` string interpolation syntax. Swift matches the parameter
/// types in the expression to one of the `appendInterpolation` methods
/// in ``LocalizedStringKey/StringInterpolation``. The interpolated
/// types can include numeric values, Foundation types, and SwiftUI
/// ``Text`` and ``Image`` instances.
///
/// The following example uses a string interpolation with two arguments:
/// an unlabeled
/// <doc://com.apple.documentation/documentation/Foundation/Date>
/// and a ``Text/DateStyle`` labeled `style`. The compiler maps these to the
/// method
/// ``LocalizedStringKey/StringInterpolation/appendInterpolation(_:style:)``
/// as it builds the string that it creates the
/// ``LocalizedStringKey`` with.
///
/// let key = LocalizedStringKey("Date is \(company.foundedDate, style: .offset)")
/// let text = Text(key) // Text contains "Date is +45 years"
///
/// You can write this example more concisely, implicitly creating a
/// ``LocalizedStringKey`` as the parameter to the ``Text``
/// initializer:
///
/// let text = Text("Date is \(company.foundedDate, style: .offset)")
///
/// - Parameter stringInterpolation: The string interpolation to use as the
/// localization key.
public init(stringInterpolation: LocalizedStringKey.StringInterpolation)
/// Represents the contents of a string literal with interpolations
/// while it’s being built, for use in creating a localized string key.
public struct StringInterpolation : StringInterpolationProtocol {
/// Creates an empty instance ready to be filled with string literal content.
///
/// Don't call this initializer directly. Instead, initialize a variable or
/// constant using a string literal with interpolated expressions.
///
/// Swift passes this initializer a pair of arguments specifying the size of
/// the literal segments and the number of interpolated segments. Use this
/// information to estimate the amount of storage you will need.
///
/// - Parameter literalCapacity: The approximate size of all literal segments
/// combined. This is meant to be passed to `String.reserveCapacity(_:)`;
/// it may be slightly larger or smaller than the sum of the counts of each
/// literal segment.
/// - Parameter interpolationCount: The number of interpolations which will be
/// appended. Use this value to estimate how much additional capacity will
/// be needed for the interpolated segments.
public init(literalCapacity: Int, interpolationCount: Int)
/// Appends a literal string.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameter literal: The literal string to append.
public mutating func appendLiteral(_ literal: String)
/// Appends a literal string segment to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameter string: The literal string to append.
public mutating func appendInterpolation(_ string: String)
/// Appends an optionally-formatted instance of a Foundation type
/// to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameters:
/// - subject: The Foundation object to append.
/// - formatter: A formatter to convert `subject` to a string
/// representation.
public mutating func appendInterpolation<Subject>(_ subject: Subject, formatter: Formatter? = nil) where Subject : ReferenceConvertible
/// Appends an optionally-formatted instance of an Objective-C subclass
/// to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// The following example shows how to use a
/// <doc://com.apple.documentation/documentation/Foundation/Measurement>
/// value and a
/// <doc://com.apple.documentation/documentation/Foundation/MeasurementFormatter>
/// to create a ``LocalizedStringKey`` that uses the formatter
/// style
/// <doc://com.apple.documentation/documentation/foundation/Formatter/UnitStyle/long>
/// when generating the measurement's string representation. Rather than
/// calling `appendInterpolation(_:formatter)` directly, the code
/// gets the formatting behavior implicitly by using the `\()`
/// string interpolation syntax.
///
/// let siResistance = Measurement(value: 640, unit: UnitElectricResistance.ohms)
/// let formatter = MeasurementFormatter()
/// formatter.unitStyle = .long
/// let key = LocalizedStringKey ("Resistance: \(siResistance, formatter: formatter)")
/// let text1 = Text(key) // Text contains "Resistance: 640 ohms"
///
/// - Parameters:
/// - subject: An <doc://com.apple.documentation/documentation/objectivec/NSObject>
/// to append.
/// - formatter: A formatter to convert `subject` to a string
/// representation.
public mutating func appendInterpolation<Subject>(_ subject: Subject, formatter: Formatter? = nil) where Subject : NSObject
/// Appends the interpolation of `F.FormatInput` using a `FormatStyle`.
///
/// - Parameters:
/// - input: The input to provide to the format style.
/// - format: The specific `FormatStyle` to use to convert the input
/// into a string.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public mutating func appendInterpolation<F>(_ input: F.FormatInput, format: F) where F : FormatStyle, F.FormatInput : Equatable, F.FormatOutput == String
/// Appends a type, convertible to a string by using a default format
/// specifier, to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameters:
/// - value: A primitive type to append, such as
/// <doc://com.apple.documentation/documentation/swift/Int>,
/// <doc://com.apple.documentation/documentation/swift/UInt32>, or
/// <doc://com.apple.documentation/documentation/swift/Double>.
public mutating func appendInterpolation<T>(_ value: T) where T : _FormatSpecifiable
/// Appends a type, convertible to a string with a format specifier,
/// to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameters:
/// - value: The value to append.
/// - specifier: A format specifier to convert `subject` to a string
/// representation, like `%f` for a
/// <doc://com.apple.documentation/documentation/swift/Double>, or
/// `%x` to create a hexidecimal representation of a
/// <doc://com.apple.documentation/documentation/swift/UInt32>. For a
/// list of available specifier strings, see
/// [String Format Specifers](https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFStrings/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265).
public mutating func appendInterpolation<T>(_ value: T, specifier: String) where T : _FormatSpecifiable
/// Appends the string displayed by a text view to a string
/// interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameters:
/// - value: A ``Text`` instance to append.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public mutating func appendInterpolation(_ text: Text)
/// Appends an AttributedString to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameter attributedString: The AttributedString to append.
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
public mutating func appendInterpolation(_ attributedString: AttributedString)
/// The type that should be used for literal segments.
public typealias StringLiteralType = String
}
/// 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: LocalizedStringKey, b: LocalizedStringKey) -> Bool
/// A type that represents an extended grapheme cluster literal.
///
/// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,
/// `String`, and `StaticString`.
public typealias ExtendedGraphemeClusterLiteralType = String
/// A type that represents a string literal.
///
/// Valid types for `StringLiteralType` are `String` and `StaticString`.
public typealias StringLiteralType = String
/// A type that represents a Unicode scalar literal.
///
/// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,
/// `Character`, `String`, and `StaticString`.
public typealias UnicodeScalarLiteralType = String
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension LocalizedStringKey.StringInterpolation {
/// Appends an image to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameter image: The image to append.
public mutating func appendInterpolation(_ image: Image)
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension LocalizedStringKey.StringInterpolation {
/// Appends a formatted date to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameters:
/// - date: The date to append.
/// - style: A predefined style to format the date with.
public mutating func appendInterpolation(_ date: Date, style: Text.DateStyle)
/// Appends a date range to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameter dates: The closed range of dates to append.
public mutating func appendInterpolation(_ dates: ClosedRange<Date>)
/// Appends a date interval to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameter interval: The date interval to append.
public mutating func appendInterpolation(_ interval: DateInterval)
}
/// A gesture that succeeds when the user performs a long press.
///
/// To recognize a long-press gesture on a view, create and configure the
/// gesture, then add it to the view using the ``View/gesture(_:including:)``
/// modifier.
///
/// Add a long-press gesture to a ``Circle`` to animate its color from blue to
/// red, and then change it to green when the gesture ends:
///
/// struct LongPressGestureView: View {
/// @GestureState var isDetectingLongPress = false
/// @State var completedLongPress = false
///
/// var longPress: some Gesture {
/// LongPressGesture(minimumDuration: 3)
/// .updating($isDetectingLongPress) { currentState, gestureState,
/// transaction in
/// gestureState = currentState
/// transaction.animation = Animation.easeIn(duration: 2.0)
/// }
/// .onEnded { finished in
/// self.completedLongPress = finished
/// }
/// }
///
/// var body: some View {
/// Circle()
/// .fill(self.isDetectingLongPress ?
/// Color.red :
/// (self.completedLongPress ? Color.green : Color.blue))
/// .frame(width: 100, height: 100, alignment: .center)
/// .gesture(longPress)
/// }
/// }
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 14.0, *)
public struct LongPressGesture : Gesture {
/// The minimum duration of the long press that must elapse before the
/// gesture succeeds.
public var minimumDuration: Double
/// The maximum distance that the long press can move before the gesture
/// fails.
@available(tvOS, unavailable)
public var maximumDistance: CGFloat
/// Creates a long-press gesture with a minimum duration and a maximum
/// distance that the interaction can move before the gesture fails.
///
/// - Parameters:
/// - minimumDuration: The minimum duration of the long press that must
/// elapse before the gesture succeeds.
/// - maximumDistance: The maximum distance that the fingers or cursor
/// performing the long press can move before the gesture fails.
@available(tvOS, unavailable)
public init(minimumDuration: Double = 0.5, maximumDistance: CGFloat = 10)
/// The type of gesture representing the body of `Self`.
public typealias Body = Never
/// The type representing the gesture's value.
public typealias Value = Bool
}
/// A gesture that recognizes a magnification motion and tracks the amount of
/// magnification.
///
/// A magnification gesture tracks how a magnification event sequence changes.
/// To recognize a magnification gesture on a view, create and configure the
/// gesture, and then add it to the view using the
/// ``View/gesture(_:including:)`` modifier.
///
/// Add a magnification gesture to a ``Circle`` that changes its size while the
/// user performs the gesture:
///
/// struct MagnificationGestureView: View {
///
/// @GestureState var magnifyBy = CGFloat(1.0)
///
/// var magnification: some Gesture {
/// MagnificationGesture()
/// .updating($magnifyBy) { currentState, gestureState, transaction in
/// gestureState = currentState
/// }
/// }
///
/// var body: some View {
/// Circle()
/// .frame(width: 100 * magnifyBy,
/// height: 100 * magnifyBy,
/// alignment: .center)
/// .gesture(magnification)
/// }
/// }
///
/// The circle's size resets to its original size when the gesture finishes.
@available(iOS 13.0, macOS 10.15, *)
@available(watchOS, unavailable)
@available(tvOS, unavailable)
public struct MagnificationGesture : Gesture {
/// The minimum required delta before the gesture starts.
public var minimumScaleDelta: CGFloat
/// Creates a magnification gesture with a given minimum delta for the
/// gesture to start.
///
/// - Parameter minimumScaleDelta: The minimum scale delta required before
/// the gesture starts.
public init(minimumScaleDelta: CGFloat = 0.01)
/// The type of gesture representing the body of `Self`.
public typealias Body = Never
/// The type representing the gesture's value.
public typealias Value = CGFloat
}
/// A set of view properties that may be synchronized between views
/// using the `View.matchedGeometryEffect()` function.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@frozen public struct MatchedGeometryProperties : 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.
@inlinable public init(rawValue: UInt32)
/// The view's position, in window coordinates.
public static let position: MatchedGeometryProperties
/// The view's size, in local coordinates.
public static let size: MatchedGeometryProperties
/// Both the `position` and `size` properties.
public static let frame: MatchedGeometryProperties
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = MatchedGeometryProperties
/// 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 = MatchedGeometryProperties
/// 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 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension MatchedGeometryProperties : Sendable {
}
/// A background material type.
///
/// You can apply a blur effect to a view that appears behind another view by
/// adding a material with the ``View/background(_:ignoresSafeAreaEdges:)``
/// modifier:
///
/// ZStack {
/// Color.teal
/// Label("Flag", systemImage: "flag.fill")
/// .padding()
/// .background(.regularMaterial)
/// }
///
/// In the example above, the ``ZStack`` layers a ``Label`` on top of the color
/// ``ShapeStyle/teal``. The background modifier inserts the
/// regular material below the label, blurring the part of
/// the background that the label --- including its padding --- covers:
///
/// ![A screenshot of a label on a teal background, where the area behind
/// the label appears blurred.](Material-1)
///
/// A material isn't a view, but adding a material is like inserting a
/// translucent layer between the modified view and its background:
///
/// ![An illustration that shows a background layer below a material layer,
/// which in turn appears below a foreground layer.](Material-2)
///
/// The blurring effect provided by the material isn't simple opacity. Instead,
/// it uses a platform-specific blending that produces an effect that resembles
/// heavily frosted glass. You can see this more easily with a complex
/// background, like an image:
///
/// ZStack {
/// Image("chili_peppers")
/// .resizable()
/// .aspectRatio(contentMode: .fit)
/// Label("Flag", systemImage: "flag.fill")
/// .padding()
/// .background(.regularMaterial)
/// }
///
/// ![A screenshot of a label on an image background, where the area behind
/// the label appears blurred.](Material-3)
///
/// For physical materials, the degree to which the background colors pass
/// through depends on the thickness. The effect also varies with light and
/// dark appearance:
///
/// ![An array of labels on a teal background. The first column, labeled light
/// appearance, shows a succession of labels on blurred backgrounds where the
/// blur increases from top to bottom, resulting in lighter and lighter blur.
/// The second column, labeled dark appearance, shows a similar succession of
/// labels, except that the blur gets darker from top to bottom. The rows are
/// labeled, from top to bottom: no material, ultra thin, thin, regular, thick,
/// and ultra thick.](Material-4)
///
/// If you need a material to have a particular shape, you can use the
/// ``View/background(_:in:fillStyle:)-20tq5`` modifier. For example, you can
/// create a material with rounded corners:
///
/// ZStack {
/// Color.teal
/// Label("Flag", systemImage: "flag.fill")
/// .padding()
/// .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 8))
/// }
///
/// ![A screenshot of a label on a teal background, where the area behind
/// the label appears blurred. The blurred area has rounded corners.](Material-5)
///
/// When you add a material, foreground elements exhibit vibrancy,
/// a context-specific blend of the foreground and background colors
/// that improves contrast. However using ``View/foregroundStyle(_:)``
/// to set a custom foreground style --- excluding the hierarchical
/// styles, like ``ShapeStyle/secondary`` --- disables vibrancy.
///
/// > Note: A material blurs a background that's part of your app, but not
/// what appears behind your app on the screen.
/// For example, the content on the Home Screen doesn't affect the appearance
/// of a widget.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct Material {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, *)
@available(watchOS, unavailable)
extension Material {
/// A material that's somewhat translucent.
public static let regular: Material
/// A material that's more opaque than translucent.
public static let thick: Material
/// A material that's more translucent than opaque.
public static let thin: Material
/// A mostly translucent material.
public static let ultraThin: Material
/// A mostly opaque material.
public static let ultraThick: Material
}
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension Material {
/// A material matching the style of system toolbars.
public static let bar: Material
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Material : ShapeStyle {
}
/// A control for presenting a menu of actions.
///
/// The following example presents a menu of three buttons and a submenu, which
/// contains three buttons of its own.
///
/// Menu("Actions") {
/// Button("Duplicate", action: duplicate)
/// Button("Rename", action: rename)
/// Button("Delete…", action: delete)
/// Menu("Copy") {
/// Button("Copy", action: copy)
/// Button("Copy Formatted", action: copyFormatted)
/// Button("Copy Library Path", action: copyPath)
/// }
/// }
///
/// You can create the menu's title with a ``LocalizedStringKey``, as seen in
/// the previous example, or with a view builder that creates multiple views,
/// such as an image and a text view:
///
/// Menu {
/// Button("Open in Preview", action: openInPreview)
/// Button("Save as PDF", action: saveAsPDF)
/// } label: {
/// Label("PDF", systemImage: "doc.fill")
/// }
///
/// ### Primary Action
///
/// Menus can be created with a custom primary action. The primary action will
/// be performed when the user taps or clicks on the body of the control, and
/// the menu presentation will happen on a secondary gesture, such as on
/// long press or on click of the menu indicator. The following example creates
/// a menu that adds bookmarks, with advanced options that are presented in a
/// menu.
///
/// Menu {
/// Button(action: addCurrentTabToReadingList) {
/// Label("Add to Reading List", systemImage: "eyeglasses")
/// }
/// Button(action: bookmarkAll) {
/// Label("Add Bookmarks for All Tabs", systemImage: "book")
/// }
/// Button(action: show) {
/// Label("Show All Bookmarks", systemImage: "books.vertical")
/// }
/// } label: {
/// Label("Add Bookmark", systemImage: "book")
/// } primaryAction: {
/// addBookmark()
/// }
///
/// ### Styling Menus
///
/// Use the ``View/menuStyle(_:)`` modifier to change the style of all menus
/// in a view. The following example shows how to apply a custom style:
///
/// Menu("Editing") {
/// Button("Set In Point", action: setInPoint)
/// Button("Set Out Point", action: setOutPoint)
/// }
/// .menuStyle(EditingControlsMenuStyle())
///
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct Menu<Label, Content> : View where Label : View, 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 primitive 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>.
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 Menu {
/// Creates a menu with a custom label.
///
/// - Parameters:
/// - content: A group of menu items.
/// - label: A view describing the content of the menu.
public init(@ViewBuilder content: () -> Content, @ViewBuilder label: () -> Label)
/// Creates a menu that generates its label from a localized string key.
///
/// - Parameters:
/// - titleKey: The key for the link's localized title, which describes
/// the contents of the menu.
/// - content: A group of menu items.
public init(_ titleKey: LocalizedStringKey, @ViewBuilder content: () -> Content) where Label == Text
/// Creates a menu that generates its label from a string.
///
/// To create the label with a localized string key, use
/// ``Menu/init(_:content:)-7v768`` instead.
///
/// - Parameters:
/// - title: A string that describes the contents of the menu.
/// - content: A group of menu items.
public init<S>(_ title: S, @ViewBuilder content: () -> Content) where Label == Text, S : StringProtocol
}
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension Menu {
/// Creates a menu with a custom primary action and custom label.
///
/// - Parameters:
/// - content: A group of menu items.
/// - label: A view describing the content of the menu.
/// - primaryAction: The action to perform on primary
/// interaction with the menu.
public init(@ViewBuilder content: () -> Content, @ViewBuilder label: () -> Label, primaryAction: @escaping () -> Void)
/// Creates a menu with a custom primary action that generates its label
/// from a localized string key.
///
/// - Parameters:
/// - titleKey: The key for the link's localized title, which describes
/// the contents of the menu.
/// - primaryAction: The action to perform on primary
/// interaction with the menu.
/// - content: A group of menu items.
public init(_ titleKey: LocalizedStringKey, @ViewBuilder content: () -> Content, primaryAction: @escaping () -> Void) where Label == Text
/// Creates a menu with a custom primary action that generates its label
/// from a string.
///
/// To create the label with a localized string key, use
/// `Menu(_:primaryAction:content:)` instead.
///
/// - Parameters:
/// - title: A string that describes the contents of the menu.
/// - primaryAction: The action to perform on primary
/// interaction with the menu.
/// - content: A group of menu items.
public init<S>(_ title: S, @ViewBuilder content: () -> Content, primaryAction: @escaping () -> Void) where Label == Text, S : StringProtocol
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension Menu where Label == MenuStyleConfiguration.Label, Content == MenuStyleConfiguration.Content {
/// Creates a menu based on a style configuration.
///
/// Use this initializer within the ``MenuStyle/makeBody(configuration:)``
/// method of a ``MenuStyle`` instance to create an instance of the menu
/// being styled. This is useful for custom menu styles that modify the
/// current menu style.
///
/// For example, the following code creates a new, custom style that adds a
/// red border around the current menu style:
///
/// struct RedBorderMenuStyle: MenuStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// Menu(configuration)
/// .border(Color.red)
/// }
/// }
///
public init(_ configuration: MenuStyleConfiguration)
}
/// A picker style that presents the options as a menu when the user presses a
/// button, or as a submenu when nested within a larger menu.
///
/// Do not use this type directly. Instead, use ``PickerStyle/menu``.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct MenuPickerStyle : PickerStyle {
/// Creates a menu picker style.
public init()
}
/// A type that applies standard interaction behavior and a custom appearance
/// to all menus within a view hierarchy.
///
/// To configure the current menu style for a view hierarchy, use the
/// ``View/menuStyle(_:)`` modifier.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public protocol MenuStyle {
/// A view that represents the body of a menu.
associatedtype Body : View
/// 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.
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a menu.
typealias Configuration = MenuStyleConfiguration
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension MenuStyle where Self == DefaultMenuStyle {
/// The default menu style, based on the menu's context.
///
/// The default menu style can vary by platform. By default, macOS uses the
/// bordered button style.
///
/// If you create a menu inside a container, the style resolves to the
/// recommended style for menus inside that container for that specific
/// platform. For example, a menu nested within another menu will resolve to
/// a submenu:
///
/// Menu("Edit") {
/// Menu("Arrange") {
/// Button("Bring to Front", action: moveSelectionToFront)
/// Button("Send to Back", action: moveSelectionToBack)
/// }
/// Button("Delete", action: deleteSelection)
/// }
///
/// You can override a menu's style. To apply the default style to a menu,
/// or to a view that contains a menu, use the ``View/menuStyle(_:)``
/// modifier.
public static var automatic: DefaultMenuStyle { get }
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension MenuStyle where Self == BorderlessButtonMenuStyle {
/// A menu style that displays a borderless button that toggles the display of
/// the menu's contents when pressed.
///
/// On macOS, the button optionally displays an arrow indicating that it
/// presents a menu.
///
/// Pressing and then dragging into the contents triggers the chosen action on
/// release.
public static var borderlessButton: BorderlessButtonMenuStyle { get }
}
/// A configuration of a menu.
///
/// Use the ``Menu/init(_:)`` initializer of ``Menu`` to create an
/// instance using the current menu style, which you can modify to create a
/// custom style.
///
/// For example, the following code creates a new, custom style that adds a red
/// border to the current menu style:
///
/// struct RedBorderMenuStyle: MenuStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// Menu(configuration)
/// .border(Color.red)
/// }
/// }
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct MenuStyleConfiguration {
/// A type-erased label of a menu.
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 content of a menu.
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 value with a modifier applied to it.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct ModifiedContent<Content, Modifier> {
/// 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 that the modifier transforms into a new view or new
/// view modifier.
public var content: Content
/// The view modifier.
public var modifier: Modifier
/// A structure that the defines the content and modifier needed to produce
/// a new view or view modifier.
///
/// If `content` is a ``View`` and `modifier` is a ``ViewModifier``, the
/// result is a ``View``. If `content` and `modifier` are both view
/// modifiers, then the result is a new ``ViewModifier`` combining them.
///
/// - Parameters:
/// - content: The content that the modifier changes.
/// - modifier: The modifier to apply to the content.
@inlinable public init(content: Content, modifier: Modifier)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds an accessibility action to the view. Actions allow assistive technologies,
/// such as the VoiceOver, to interact with the view by invoking the action.
///
/// For example, this is how a `.default` action to compose
/// a new email could be added to a view.
///
/// var body: some View {
/// ContentView()
/// .accessibilityAction {
/// // Handle action
/// }
/// }
///
public func accessibilityAction(_ actionKind: AccessibilityActionKind = .default, _ handler: @escaping () -> Void) -> ModifiedContent<Content, Modifier>
/// Adds an accessibility action to the view. Actions allow assistive technologies,
/// such as the VoiceOver, to interact with the view by invoking the action.
///
/// For example, this is how a custom action to compose
/// a new email could be added to a view.
///
/// var body: some View {
/// ContentView()
/// .accessibilityAction(named: Text("New Message")) {
/// // Handle action
/// }
/// }
///
public func accessibilityAction(named name: Text, _ handler: @escaping () -> Void) -> ModifiedContent<Content, Modifier>
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds an accessibility action to the view. Actions allow assistive technologies,
/// such as the VoiceOver, to interact with the view by invoking the action.
///
/// For example, this is how a custom action to compose
/// a new email could be added to a view.
///
/// var body: some View {
/// ContentView()
/// .accessibilityAction(named: "New Message") {
/// // Handle action
/// }
/// }
///
public func accessibilityAction(named nameKey: LocalizedStringKey, _ handler: @escaping () -> Void) -> ModifiedContent<Content, Modifier>
/// Adds an accessibility action to the view. Actions allow assistive technologies,
/// such as the VoiceOver, to interact with the view by invoking the action.
///
/// For example, this is how a custom action to compose
/// a new email could be added to a view.
///
/// var body: some View {
/// ContentView()
/// .accessibilityAction(named: "New Message") {
/// // Handle action
/// }
/// }
///
public func accessibilityAction<S>(named name: S, _ handler: @escaping () -> Void) -> ModifiedContent<Content, Modifier> where S : StringProtocol
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ModifiedContent : Equatable where Content : Equatable, Modifier : 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: ModifiedContent<Content, Modifier>, b: ModifiedContent<Content, Modifier>) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ModifiedContent : View where Content : View, Modifier : ViewModifier {
/// 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 primitive 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>.
public var body: ModifiedContent<Content, Modifier>.Body { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ModifiedContent : ViewModifier where Content : ViewModifier, Modifier : ViewModifier {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ModifiedContent : DynamicViewContent where Content : DynamicViewContent, Modifier : ViewModifier {
/// The collection of underlying data.
public var data: Content.Data { get }
/// The type of the underlying collection of data.
public typealias Data = Content.Data
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Add additional accessibility information to the view.
///
/// Use this method to add information you want accessibility users to be
/// able to access about this element, beyond the basics of label, value,
/// and hint. For example, `accessibilityCustomContent` can be used to add
/// information about the orientation of a photograph, or the number of
/// people found in the picture.
///
/// - Parameter key: Key used to specify the identifier and label of the
/// of the additional accessibility information entry.
/// - Parameter value: Text value for the additional accessibility
/// information. For example: "landscape." A value of `nil` will remove
/// any entry of additional information added earlier for any `key` with
/// the same identifier.
/// - Note: Repeated calls of `accessibilityCustomContent` with `key`s
/// having different identifiers will create new entries of
/// additional information.
/// Calling `accessibilityAdditionalContent` repeatedly with `key`s
/// having matching identifiers will replace the previous entry.
public func accessibilityCustomContent(_ key: AccessibilityCustomContentKey, _ value: Text?, importance: AXCustomContent.Importance = .default) -> ModifiedContent<Content, Modifier>
/// Add additional accessibility information to the view.
///
/// Use this method to add information you want accessibility users to be
/// able to access about this element, beyond the basics of label, value,
/// and hint. For example, `accessibilityCustomContent` can be used to add
/// information about the orientation of a photograph, or the number of
/// people found in the picture.
///
/// - Parameter key: Key used to specify the identifier and label of the
/// of the additional accessibility information entry.
/// - Parameter valueKey: Text value for the additional accessibility
/// information. For example: "landscape." A value of `nil` will remove
/// any entry of additional information added earlier for any `key` with
/// the same identifier.
/// - Parameter importance: Importance of the accessibility information.
/// High-importance information gets read out immediately, while
/// default-importance information must be explicitly asked for by the
/// user.
/// - Note: Repeated calls of `accessibilityCustomContent` with `key`s
/// having different identifiers will create new entries of
/// additional information.
/// Calling `accessibilityAdditionalContent` repeatedly with `key`s
/// having matching identifiers will replace the previous entry.
public func accessibilityCustomContent(_ key: AccessibilityCustomContentKey, _ valueKey: LocalizedStringKey, importance: AXCustomContent.Importance = .default) -> ModifiedContent<Content, Modifier>
/// Add additional accessibility information to the view.
///
/// Use this method to add information you want accessibility users to be
/// able to access about this element, beyond the basics of label, value,
/// and hint. For example, `accessibilityCustomContent` can be used to add
/// information about the orientation of a photograph, or the number of
/// people found in the picture.
///
/// - Parameter key: Key used to specify the identifier and label of the
/// of the additional accessibility information entry.
/// - Parameter value: Text value for the additional accessibility
/// information. For example: "landscape." A value of `nil` will remove
/// any entry of additional information added earlier for any `key` with
/// the same identifier.
/// - Parameter importance: Importance of the accessibility information.
/// High-importance information gets read out immediately, while
/// default-importance information must be explicitly asked for by the
/// user.
/// - Note: Repeated calls of `accessibilityCustomContent` with `key`s
/// having different identifiers will create new entries of
/// additional information.
/// Calling `accessibilityAdditionalContent` repeatedly with `key`s
/// having matching identifiers will replace the previous entry.
public func accessibilityCustomContent<V>(_ key: AccessibilityCustomContentKey, _ value: V, importance: AXCustomContent.Importance = .default) -> ModifiedContent<Content, Modifier> where V : StringProtocol
/// Add additional accessibility information to the view.
///
/// Use this method to add information you want accessibility users to be
/// able to access about this element, beyond the basics of label, value,
/// and hint. For example: `accessibilityCustomContent` can be used to add
/// information about the orientation of a photograph, or the number of
/// people found in the picture.
///
/// - Parameter label: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation".
/// - Parameter value: Text value for the additional accessibility
/// information. For example: "landscape."
/// - Parameter importance: Importance of the accessibility information.
/// High-importance information gets read out immediately, while
/// default-importance information must be explicitly asked for by the
/// user.
/// - Note: Repeated calls of `accessibilityCustomContent` with different
/// labels will create new entries of additional information. Calling
/// `accessibilityAdditionalContent` repeatedly with the same label will
/// instead replace the previous value and importance.
public func accessibilityCustomContent(_ label: Text, _ value: Text, importance: AXCustomContent.Importance = .default) -> ModifiedContent<Content, Modifier>
/// Add additional accessibility information to the view.
///
/// Use this method to add information you want accessibility users to be
/// able to access about this element, beyond the basics of label, value,
/// and hint. For example: `accessibilityCustomContent` can be used to add
/// information about the orientation of a photograph, or the number of
/// people found in the picture.
///
/// - Parameter label: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation".
/// - Parameter value: Text value for the additional accessibility
/// information. For example: "landscape."
/// - Parameter importance: Importance of the accessibility information.
/// High-importance information gets read out immediately, while
/// default-importance information must be explicitly asked for by the
/// user.
/// - Note: Repeated calls of `accessibilityCustomContent` with different
/// labels will create new entries of additional information. Calling
/// `accessibilityAdditionalContent` repeatedly with the same label will
/// instead replace the previous value and importance.
public func accessibilityCustomContent(_ labelKey: LocalizedStringKey, _ value: Text, importance: AXCustomContent.Importance = .default) -> ModifiedContent<Content, Modifier>
/// Add additional accessibility information to the view.
///
/// Use this method to add information you want accessibility users to be
/// able to access about this element, beyond the basics of label, value,
/// and hint. For example, `accessibilityCustomContent` can be used to add
/// information about the orientation of a photograph, or the number of
/// people found in the picture.
///
/// - Parameter labelKey: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation".
/// - Parameter value: Text value for the additional accessibility
/// information. For example: "landscape."
/// - Parameter importance: Importance of the accessibility information.
/// High-importance information gets read out immediately, while
/// default-importance information must be explicitly asked for by the
/// user.
/// - Note: Repeated calls of `accessibilityCustomContent` with different
/// labels will create new entries of additional information. Calling
/// `accessibilityAdditionalContent` repeatedly with the same label will
/// instead replace the previous value and importance.
public func accessibilityCustomContent(_ labelKey: LocalizedStringKey, _ valueKey: LocalizedStringKey, importance: AXCustomContent.Importance = .default) -> ModifiedContent<Content, Modifier>
/// Add additional accessibility information to the view.
///
/// Use this method to add information you want accessibility users to be
/// able to access about this element, beyond the basics of label, value,
/// and hint. For example, `accessibilityCustomContent` can be used to add
/// information about the orientation of a photograph, or the number of
/// people found in the picture.
///
/// - Parameter labelKey: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation".
/// - Parameter value: Text value for the additional accessibility
/// information. For example: "landscape."
/// - Parameter importance: Importance of the accessibility information.
/// High-importance information gets read out immediately, while
/// default-importance information must be explicitly asked for by the
/// user.
/// - Note: Repeated calls of `accessibilityCustomContent` with different
/// labels will create new entries of additional information. Calling
/// `accessibilityAdditionalContent` repeatedly with the same label will
/// instead replace the previous value and importance.
public func accessibilityCustomContent<V>(_ labelKey: LocalizedStringKey, _ value: V, importance: AXCustomContent.Importance = .default) -> ModifiedContent<Content, Modifier> where V : StringProtocol
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Specifies whether to hide this view from system accessibility features.
public func accessibilityHidden(_ hidden: Bool) -> ModifiedContent<Content, Modifier>
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ModifiedContent : Scene where Content : Scene, Modifier : _SceneModifier {
/// 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 primitive 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.
public var body: ModifiedContent<Content, Modifier>.Body { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Explicitly set whether this Accessibility element responds to user
/// interaction and would thus be interacted with by technologies such as
/// Switch Control, Voice Control or Full Keyboard Access.
///
/// If this is not set, the value is inferred from the traits of the
/// Accessibility element, the presence of Accessibility actions on the
/// element, or the presence of gestures on the element or containing views.
public func accessibilityRespondsToUserInteraction(_ respondsToUserInteraction: Bool = true) -> ModifiedContent<Content, Modifier>
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds a label to the view that describes its contents.
///
/// Use this method to provide an accessibility label for a view that doesn't display text, like an icon.
/// For example, you could use this method to label a button that plays music with the text "Play".
/// Don't include text in the label that repeats information that users already have. For example,
/// don't use the label "Play button" because a button already has a trait that identifies it as a button.
public func accessibilityLabel(_ label: Text) -> ModifiedContent<Content, Modifier>
/// Communicates to the user what happens after performing the view's
/// action.
///
/// Provide a hint in the form of a brief phrase, like "Purchases the item" or
/// "Downloads the attachment".
public func accessibilityHint(_ hint: Text) -> ModifiedContent<Content, Modifier>
/// Sets alternate input labels with which users identify a view.
///
/// If you don't specify any input labels, the user can still refer to the view using the accessibility
/// label that you add with the accessibilityLabel() modifier. Provide labels in descending order
/// of importance. Voice Control and Full Keyboard Access use the input labels.
public func accessibilityInputLabels(_ inputLabels: [Text]) -> ModifiedContent<Content, Modifier>
/// Uses the string you specify to identify the view.
///
/// Use this value for testing. It isn't visible to the user.
public func accessibilityIdentifier(_ identifier: String) -> ModifiedContent<Content, Modifier>
/// Specifies the point where activations occur in the view.
public func accessibilityActivationPoint(_ activationPoint: CGPoint) -> ModifiedContent<Content, Modifier>
/// Specifies the unit point where activations occur in the view.
public func accessibilityActivationPoint(_ activationPoint: UnitPoint) -> ModifiedContent<Content, Modifier>
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds a label to the view that describes its contents.
///
/// Use this method to provide an accessibility label for a view that doesn't display text, like an icon.
/// For example, you could use this method to label a button that plays music with the text "Play".
/// Don't include text in the label that repeats information that users already have. For example,
/// don't use the label "Play button" because a button already has a trait that identifies it as a button.
public func accessibilityLabel(_ labelKey: LocalizedStringKey) -> ModifiedContent<Content, Modifier>
/// Adds a label to the view that describes its contents.
///
/// Use this method to provide an accessibility label for a view that doesn't display text, like an icon.
/// For example, you could use this method to label a button that plays music with the text "Play".
/// Don't include text in the label that repeats information that users already have. For example,
/// don't use the label "Play button" because a button already has a trait that identifies it as a button.
public func accessibilityLabel<S>(_ label: S) -> ModifiedContent<Content, Modifier> where S : StringProtocol
/// Communicates to the user what happens after performing the view's
/// action.
///
/// Provide a hint in the form of a brief phrase, like "Purchases the item" or
/// "Downloads the attachment".
public func accessibilityHint(_ hintKey: LocalizedStringKey) -> ModifiedContent<Content, Modifier>
/// Communicates to the user what happens after performing the view's
/// action.
///
/// Provide a hint in the form of a brief phrase, like "Purchases the item" or
/// "Downloads the attachment".
public func accessibilityHint<S>(_ hint: S) -> ModifiedContent<Content, Modifier> where S : StringProtocol
/// Sets alternate input labels with which users identify a view.
///
/// Provide labels in descending order of importance. Voice Control
/// and Full Keyboard Access use the input labels.
///
/// > Note: If you don't specify any input labels, the user can still
/// refer to the view using the accessibility label that you add with the
/// `accessibilityLabel()` modifier.
public func accessibilityInputLabels(_ inputLabelKeys: [LocalizedStringKey]) -> ModifiedContent<Content, Modifier>
/// Sets alternate input labels with which users identify a view.
///
/// Provide labels in descending order of importance. Voice Control
/// and Full Keyboard Access use the input labels.
///
/// > Note: If you don't specify any input labels, the user can still
/// refer to the view using the accessibility label that you add with the
/// `accessibilityLabel()` modifier.
public func accessibilityInputLabels<S>(_ inputLabels: [S]) -> ModifiedContent<Content, Modifier> where S : StringProtocol
}
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Specifies whether to hide this view from system accessibility features.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityHidden(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityHidden(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityHidden(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityHidden(_:)")
public func accessibility(hidden: Bool) -> ModifiedContent<Content, Modifier>
/// Adds a label to the view that describes its contents.
///
/// Use this method to provide an accessibility label for a view that doesn't display text, like an icon.
/// For example, you could use this method to label a button that plays music with the text "Play".
/// Don't include text in the label that repeats information that users already have. For example,
/// don't use the label "Play button" because a button already has a trait that identifies it as a button.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityLabel(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityLabel(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityLabel(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityLabel(_:)")
public func accessibility(label: Text) -> ModifiedContent<Content, Modifier>
/// Communicates to the user what happens after performing the view's
/// action.
///
/// Provide a hint in the form of a brief phrase, like "Purchases the item" or
/// "Downloads the attachment".
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityHint(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityHint(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityHint(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityHint(_:)")
public func accessibility(hint: Text) -> ModifiedContent<Content, Modifier>
/// Sets alternate input labels with which users identify a view.
///
/// If you don't specify any input labels, the user can still refer to the view using the accessibility
/// label that you add with the accessibilityLabel() modifier. Provide labels in descending order
/// of importance. Voice Control and Full Keyboard Access use the input labels.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityInputLabels(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityInputLabels(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityInputLabels(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityInputLabels(_:)")
public func accessibility(inputLabels: [Text]) -> ModifiedContent<Content, Modifier>
/// Uses the specified string to identify the view.
///
/// Use this value for testing. It isn't visible to the user.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityIdentifier(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityIdentifier(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityIdentifier(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityIdentifier(_:)")
public func accessibility(identifier: String) -> ModifiedContent<Content, Modifier>
@available(iOS, deprecated, introduced: 13.0)
@available(macOS, deprecated, introduced: 10.15)
@available(tvOS, deprecated, introduced: 13.0)
@available(watchOS, deprecated, introduced: 6)
public func accessibility(selectionIdentifier: AnyHashable) -> ModifiedContent<Content, Modifier>
/// Sets the sort priority order for this view's accessibility
/// element, relative to other elements at the same level.
///
/// Higher numbers are sorted first. The default sort priority is zero.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilitySortPriority(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilitySortPriority(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilitySortPriority(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilitySortPriority(_:)")
public func accessibility(sortPriority: Double) -> ModifiedContent<Content, Modifier>
/// Specifies the point where activations occur in the view.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityActivationPoint(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityActivationPoint(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityActivationPoint(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityActivationPoint(_:)")
public func accessibility(activationPoint: CGPoint) -> ModifiedContent<Content, Modifier>
/// Specifies the unit point where activations occur in the view.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityActivationPoint(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityActivationPoint(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityActivationPoint(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityActivationPoint(_:)")
public func accessibility(activationPoint: UnitPoint) -> ModifiedContent<Content, Modifier>
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Sets the sort priority order for this view's accessibility
/// element, relative to other elements at the same level.
///
/// Higher numbers are sorted first. The default sort priority is zero.
public func accessibilitySortPriority(_ sortPriority: Double) -> ModifiedContent<Content, Modifier>
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds the given traits to the view.
public func accessibilityAddTraits(_ traits: AccessibilityTraits) -> ModifiedContent<Content, Modifier>
/// Removes the given traits from this view.
public func accessibilityRemoveTraits(_ traits: AccessibilityTraits) -> ModifiedContent<Content, Modifier>
}
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds the given traits to the view.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityAddTraits(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityAddTraits(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityAddTraits(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityAddTraits(_:)")
public func accessibility(addTraits traits: AccessibilityTraits) -> ModifiedContent<Content, Modifier>
/// Removes the given traits from this view.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityRemoveTraits(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityRemoveTraits(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityRemoveTraits(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityRemoveTraits(_:)")
public func accessibility(removeTraits traits: AccessibilityTraits) -> ModifiedContent<Content, Modifier>
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds an accessibility scroll action to the view. Actions allow
/// assistive technologies, such as the VoiceOver, to interact with the
/// view by invoking the action.
///
/// For example, this is how a scroll action to trigger
/// a refresh could be added to a view.
///
/// var body: some View {
/// ScrollView {
/// ContentView()
/// }
/// .accessibilityScrollAction { edge in
/// if edge == .top {
/// // Refresh content
/// }
/// }
/// }
///
public func accessibilityScrollAction(_ handler: @escaping (Edge) -> Void) -> ModifiedContent<Content, Modifier>
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds an accessibility adjustable action to the view. Actions allow
/// assistive technologies, such as the VoiceOver, to interact with the
/// view by invoking the action.
///
/// For example, this is how an adjustable action to navigate
/// through pages could be added to a view.
///
/// var body: some View {
/// PageControl()
/// .accessibilityAdjustableAction { direction in
/// switch direction {
/// case .increment:
/// // Go to next page
/// case .decrement:
/// // Go to previous page
/// }
/// }
/// }
///
public func accessibilityAdjustableAction(_ handler: @escaping (AccessibilityAdjustmentDirection) -> Void) -> ModifiedContent<Content, Modifier>
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Sets an accessibility text content type.
///
/// Use this modifier to set the content type of this accessibility
/// element. Assistive technologies can use this property to choose
/// an appropriate way to output the text. For example, when
/// encountering a source coding context, VoiceOver could
/// choose to speak all punctuation.
///
/// The default content type ``AccessibilityTextContentType/plain``.
///
/// - Parameter value: The accessibility content type from the available
/// ``AccessibilityTextContentType`` options.
public func accessibilityTextContentType(_ textContentType: AccessibilityTextContentType) -> ModifiedContent<Content, Modifier>
/// Set the level of this heading.
///
/// Use this modifier to set the level of this heading in relation to other headings. The system speaks
/// the level number of levels ``AccessibilityHeadingLevel/h1``
/// through ``AccessibilityHeadingLevel/h6`` alongside the text.
///
/// The default heading level if you don’t use this modifier
/// is ``AccessibilityHeadingLevel/unspecified``.
///
/// - Parameter level: The heading level to associate with this element
/// from the available ``AccessibilityHeadingLevel`` levels.
public func accessibilityHeading(_ level: AccessibilityHeadingLevel) -> ModifiedContent<Content, Modifier>
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds a textual description of the value that the view contains.
///
/// Use this method to describe the value represented by a view, but only if that's different than the
/// view's label. For example, for a slider that you label as "Volume" using accessibilityLabel(),
/// you can provide the current volume setting, like "60%", using accessibilityValue().
public func accessibilityValue(_ valueDescription: Text) -> ModifiedContent<Content, Modifier>
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds a textual description of the value that the view contains.
///
/// Use this method to describe the value represented by a view, but only if that's different than the
/// view's label. For example, for a slider that you label as "Volume" using accessibilityLabel(),
/// you can provide the current volume setting, like "60%", using accessibilityValue().
public func accessibilityValue(_ valueKey: LocalizedStringKey) -> ModifiedContent<Content, Modifier>
/// Adds a textual description of the value that the view contains.
///
/// Use this method to describe the value represented by a view, but only if that's different than the
/// view's label. For example, for a slider that you label as "Volume" using accessibilityLabel(),
/// you can provide the current volume setting, like "60%", using accessibilityValue().
public func accessibilityValue<S>(_ value: S) -> ModifiedContent<Content, Modifier> where S : StringProtocol
}
extension ModifiedContent where Modifier == AccessibilityAttachmentModifier {
/// Adds a textual description of the value that the view contains.
///
/// Use this method to describe the value represented by a view, but only if that's different than the
/// view's label. For example, for a slider that you label as "Volume" using accessibility(label:),
/// you can provide the current volume setting, like "60%", using accessibility(value:).
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityValue(_:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "accessibilityValue(_:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "accessibilityValue(_:)")
@available(watchOS, introduced: 6, deprecated: 100000.0, renamed: "accessibilityValue(_:)")
public func accessibility(value: Text) -> ModifiedContent<Content, Modifier>
}
/// A dynamic property type that allows access to a namespace defined
/// by the persistent identity of the object containing the property
/// (e.g. a view).
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@frozen @propertyWrapper public struct Namespace : DynamicProperty {
@inlinable public init()
public var wrappedValue: Namespace.ID { get }
/// A namespace defined by the persistent identity of an
/// `@Namespace` dynamic property.
@frozen public struct ID : 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: Never call `finalize()` on `hasher`. 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: Namespace.ID, b: Namespace.ID) -> 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.
public var hashValue: Int { get }
}
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Namespace : Sendable {
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Namespace.ID : Sendable {
}
/// A configuration for a navigation bar that represents a view at the top of a
/// navigation stack.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@available(macOS, unavailable)
public struct NavigationBarItem {
/// A style for displaying the title of a navigation bar.
public enum TitleDisplayMode {
/// Inherit the display mode from the previous navigation item.
case automatic
/// Display the title within the standard bounds of the navigation bar.
case inline
/// Display a large title within an expanded navigation bar.
@available(watchOS 8.0, *)
@available(tvOS, unavailable)
case large
/// 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: NavigationBarItem.TitleDisplayMode, b: NavigationBarItem.TitleDisplayMode) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@available(macOS, unavailable)
extension NavigationBarItem.TitleDisplayMode : Equatable {
}
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@available(macOS, unavailable)
extension NavigationBarItem.TitleDisplayMode : Hashable {
}
/// The navigation control group style.
///
/// Do not use this type directly. Instead, use
/// ``ControlGroupStyle/navigation``.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct NavigationControlGroupStyle : ControlGroupStyle {
/// Creates a navigation control group style.
@available(iOS, introduced: 15.0, deprecated: 15.0, message: "Use `.navigation` instead.")
@available(macOS, introduced: 12.0, deprecated: 12.0, message: "Use `.navigation` instead.")
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`.
public func makeBody(configuration: NavigationControlGroupStyle.Configuration) -> some View
/// A view representing the body of a control group.
public typealias Body = some View
}
/// A view that controls a navigation presentation.
///
/// Users click or tap a navigation link to present a view inside a
/// ``NavigationView``. You control the visual appearance of the link by
/// providing view content in the link's trailing closure. For
/// example, you can use a ``Label`` to display a link:
///
/// NavigationLink(destination: FolderList(id: workFolder.id)) {
/// Label("Work Folder", systemImage: "folder")
/// }
///
/// For a link composed only of text, you can use one of the convenience
/// initializers that takes a string and creates a ``Text`` view for you:
///
/// NavigationLink("Work Folder", destination: FolderList(id: workFolder.id))
///
/// Perform navigation by initializing a link with a destination view.
/// For example, consider a `ColorDetail` view that displays a color sample:
///
/// struct ColorDetail: View {
/// var color: Color
///
/// var body: some View {
/// color
/// .frame(width: 200, height: 200)
/// .navigationTitle(color.description.capitalized)
/// }
/// }
///
/// The following ``NavigationView`` presents three links to
/// color detail views:
///
/// NavigationView {
/// List {
/// NavigationLink("Purple", destination: ColorDetail(color: .purple))
/// NavigationLink("Pink", destination: ColorDetail(color: .pink))
/// NavigationLink("Orange", destination: ColorDetail(color: .orange))
/// }
/// .navigationTitle("Colors")
///
/// Text("Select a Color") // A placeholder to show before selection.
/// }
///
/// ![An iPad in landscape mode, showing a multicolumn navigation view. In
/// the left column, a list of three items, Purple, Pink, and Orange, with
/// the first selected. On the right, a detail view that shows a purple
/// square.](NavigationLink-1)
///
/// Optionally, you can use a navigation link to perform navigation
/// programmatically. You do so in one of two ways:
/// * Bind the link's `isActive` parameter to a Boolean value.
/// Setting the value to `true` performs the navigation.
/// * Bind the link's `selection` parameter to a value and provide a `tag` of
/// the variable’s type. Setting the value of `selection` to `tag` performs
/// the navigation.
///
/// For example, you can create a ``State`` variable that indicates when
/// the purple page in the previous example appears:
///
/// @State private var shouldShowPurple = false
///
/// Then you can modify the purple navigation link to bind to the state
/// variable:
///
/// NavigationLink(
/// "Purple",
/// destination: ColorDetail(color: .purple),
/// isActive: $shouldShowPurple)
///
/// If elsewhere in your code you set `shouldShowPurple` to `true`, the
/// navigation link activates.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct NavigationLink<Label, Destination> : View where Label : View, Destination : View {
/// Creates a navigation link that presents the destination view.
/// - Parameters:
/// - destination: A view for the navigation link to present.
/// - label: A view builder to produce a label describing the `destination`
/// to present.
public init(@ViewBuilder destination: () -> Destination, @ViewBuilder label: () -> Label)
/// Creates a navigation link that presents the destination view when active.
/// - Parameters:
/// - isActive: A binding to a Boolean value that indicates whether
/// `destination` is currently presented.
/// - destination: A view for the navigation link to present.
/// - label: A view builder to produce a label describing the `destination`
/// to present.
public init(isActive: Binding<Bool>, @ViewBuilder destination: () -> Destination, @ViewBuilder label: () -> Label)
/// Creates a navigation link that presents the destination view when
/// a bound selection variable equals a given tag value.
/// - Parameters:
/// - tag: The value of `selection` that causes the link to present
/// `destination`.
/// - selection: A bound variable that causes the link to present
/// `destination` when `selection` becomes equal to `tag`.
/// - destination: A view for the navigation link to present.
/// - label: A view builder to produce a label describing the
/// `destination` to present.
public init<V>(tag: V, selection: Binding<V?>, @ViewBuilder destination: () -> Destination, @ViewBuilder label: () -> Label) where V : Hashable
/// 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 primitive 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>.
public var body: some View { get }
/// Creates a navigation link that presents the destination view.
/// - Parameters:
/// - destination: A view for the navigation link to present.
/// - label: A view builder to produce a label describing the `destination`
/// to present.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Pass a closure as the destination")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Pass a closure as the destination")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Pass a closure as the destination")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Pass a closure as the destination")
public init(destination: Destination, @ViewBuilder label: () -> Label)
/// Creates a navigation link that presents the destination view when active.
/// - Parameters:
/// - destination: A view for the navigation link to present.
/// - isActive: A binding to a Boolean value that indicates whether
/// `destination` is currently presented.
/// - label: A view builder to produce a label describing the `destination`
/// to present.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(isActive:destination:label:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "NavigationLink(isActive:destination:label:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(isActive:destination:label:)")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "NavigationLink(isActive:destination:label:)")
public init(destination: Destination, isActive: Binding<Bool>, @ViewBuilder label: () -> Label)
/// Creates a navigation link that presents the destination view when
/// a bound selection variable equals a given tag value.
/// - Parameters:
/// - destination: A view for the navigation link to present.
/// - tag: The value of `selection` that causes the link to present
/// `destination`.
/// - selection: A bound variable that causes the link to present
/// `destination` when `selection` becomes equal to `tag`.
/// - label: A view builder to produce a label describing the
/// `destination` to present.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(tag:selection:destination:label:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "NavigationLink(tag:selection:destination:label:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(tag:selection:destination:label:)")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "NavigationLink(tag:selection:destination:label:)")
public init<V>(destination: Destination, tag: V, selection: Binding<V?>, @ViewBuilder label: () -> Label) where V : Hashable
/// 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 NavigationLink where Label == Text {
/// Creates a navigation link that presents a destination view, with a text label
/// that the link generates from a localized string key.
/// - Parameters:
/// - titleKey: A localized string key for creating a text label.
/// - destination: A view for the navigation link to present.
public init(_ titleKey: LocalizedStringKey, @ViewBuilder destination: () -> Destination)
/// Creates a navigation link that presents a destination view, with a text label
/// that the link generates from a title string.
/// - Parameters:
/// - title: A string for creating a text label.
/// - destination: A view for the navigation link to present.
public init<S>(_ title: S, @ViewBuilder destination: () -> Destination) where S : StringProtocol
/// Creates a navigation link that presents a destination view when active, with a
/// text label that the link generates from a localized string key.
/// - Parameters:
/// - titleKey: A localized string key for creating a text label.
/// - isActive: A binding to a Boolean value that indicates whether
/// `destination` is currently presented.
/// - destination: A view for the navigation link to present.
public init(_ titleKey: LocalizedStringKey, isActive: Binding<Bool>, @ViewBuilder destination: () -> Destination)
/// Creates a navigation link that presents a destination view when active, with a
/// text label that the link generates from a title string.
/// - Parameters:
/// - title: A string for creating a text label.
/// - isActive: A binding to a Boolean value that indicates whether
/// `destination` is currently presented.
/// - destination: A view for the navigation link to present.
public init<S>(_ title: S, isActive: Binding<Bool>, @ViewBuilder destination: () -> Destination) where S : StringProtocol
/// Creates a navigation link that presents a destination view when a bound
/// selection variable matches a value you provide, using a text label
/// that the link generates from a localized string key.
/// - Parameters:
/// - titleKey: A localized string key for creating a text label.
/// - tag: The value of `selection` that causes the link to present
/// `destination`.
/// - selection: A bound variable that causes the link to present
/// `destination` when `selection` becomes equal to `tag`.
/// - destination: A view for the navigation link to present.
public init<V>(_ titleKey: LocalizedStringKey, tag: V, selection: Binding<V?>, @ViewBuilder destination: () -> Destination) where V : Hashable
/// Creates a navigation link that presents a destination view when a bound
/// selection variable matches a value you provide, using a text label
/// that the link generates from a title string.
/// - Parameters:
/// - title: A string for creating a text label.
/// - tag: The value of `selection` that causes the link to present
/// `destination`.
/// - selection: A bound variable that causes the link to present
/// `destination` when `selection` becomes equal to `tag`.
/// - destination: A view for the navigation link to present.
public init<S, V>(_ title: S, tag: V, selection: Binding<V?>, @ViewBuilder destination: () -> Destination) where S : StringProtocol, V : Hashable
/// Creates a navigation link that presents a destination view, with a text
/// label that the link generates from a localized string key.
/// - Parameters:
/// - titleKey: A localized string key for creating a text label.
/// - destination: A view for the navigation link to present.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Pass a closure as the destination")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Pass a closure as the destination")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Pass a closure as the destination")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Pass a closure as the destination")
public init(_ titleKey: LocalizedStringKey, destination: Destination)
/// Creates a navigation link that presents a destination view, with a text
/// label that the link generates from a title string.
/// - Parameters:
/// - title: A string for creating a text label.
/// - destination: A view for the navigation link to present.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Pass a closure as the destination")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Pass a closure as the destination")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Pass a closure as the destination")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Pass a closure as the destination")
public init<S>(_ title: S, destination: Destination) where S : StringProtocol
/// Creates a navigation link that presents a destination view when active, with a
/// text label that the link generates from a localized string key.
/// - Parameters:
/// - titleKey: A localized string key for creating a text label.
/// - destination: A view for the navigation link to present.
/// - isActive: A binding to a Boolean value that indicates whether
/// `destination` is currently presented.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(_:isActive:destination:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "NavigationLink(_:isActive:destination:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(_:isActive:destination:)")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "NavigationLink(_:isActive:destination:)")
public init(_ titleKey: LocalizedStringKey, destination: Destination, isActive: Binding<Bool>)
/// Creates a navigation link that presents a destination view when active, with a
/// text label that the link generates from a title string.
/// - Parameters:
/// - title: A string for creating a text label.
/// - destination: A view for the navigation link to present.
/// - isActive: A binding to a Boolean value that indicates whether
/// `destination` is currently presented.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(_:isActive:destination:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "NavigationLink(_:isActive:destination:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(_:isActive:destination:)")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "NavigationLink(_:isActive:destination:)")
public init<S>(_ title: S, destination: Destination, isActive: Binding<Bool>) where S : StringProtocol
/// Creates a navigation link that presents a destination view when a bound
/// selection variable matches a value you provide, using a text label
/// that the link generates from a localized string key.
/// - Parameters:
/// - titleKey: A localized string key for creating a text label.
/// - destination: A view for the navigation link to present.
/// - tag: The value of `selection` that causes the link to present
/// `destination`.
/// - selection: A bound variable that causes the link to present
/// `destination` when `selection` becomes equal to `tag`.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(_:tag:selection:destination:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "NavigationLink(_:tag:selection:destination:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(_:tag:selection:destination:)")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "NavigationLink(_:tag:selection:destination:)")
public init<V>(_ titleKey: LocalizedStringKey, destination: Destination, tag: V, selection: Binding<V?>) where V : Hashable
/// Creates a navigation link that presents a destination view when a bound
/// selection variable matches a value you provide, using a text label
/// that the link generates from a title string.
/// - Parameters:
/// - title: A string for creating a text label.
/// - destination: A view for the navigation link to present.
/// - tag: The value of `selection` that causes the link to present
/// `destination`.
/// - selection: A bound variable that causes the link to present
/// `destination` when `selection` becomes equal to `tag`.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(_:tag:selection:destination:)")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "NavigationLink(_:tag:selection:destination:)")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "NavigationLink(_:tag:selection:destination:)")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "NavigationLink(_:tag:selection:destination:)")
public init<S, V>(_ title: S, destination: Destination, tag: V, selection: Binding<V?>) where S : StringProtocol, V : Hashable
}
@available(iOS 13.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension NavigationLink {
/// Sets the navigation link to present its destination as the detail
/// component of the containing navigation view.
///
/// This method sets the behavior when the navigation link is used in a
/// multi-column navigation view, such as
/// ``DoubleColumnNavigationViewStyle``. If `isDetailLink` is `true`,
/// performing the link in the primary column sets the contents of the
/// secondary (detail) column to be the link's destination view. If
/// `isDetailLink` is `false`, the link navigates to the destination view
/// within the primary column.
///
/// If you do not set the detail link behavior with this method, the
/// behavior defaults to `true`.
///
/// - Parameter isDetailLink: A Boolean value that specifies whether this
/// link presents its destination as the detail component when used in a
/// multi-column navigation view.
/// - Returns: A view that applies the specified detail link behavior.
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public func isDetailLink(_ isDetailLink: Bool) -> some View
}
/// A view for presenting a stack of views that represents a visible path in a
/// navigation hierarchy.
///
/// Use a `NavigationView` to create a navigation-based app in which the user
/// can traverse a collection of views. Users navigate to a destination view
/// by selecting a ``NavigationLink`` that you provide. On iPadOS and macOS, the
/// destination content appears in the next column. Other platforms push a new
/// view onto the stack, and enable removing items from the stack with
/// platform-specific controls, like a Back button or a swipe gesture.
///
/// ![A diagram showing a multicolumn navigation view on
/// macOS, and a stack of views on iOS.](NavigationView-1)
///
/// Use the ``init(content:)`` initializer to create a
/// navigation view that directly associates navigation links and their
/// destination views:
///
/// NavigationView {
/// List(model.notes) { note in
/// NavigationLink(note.title, destination: NoteEditor(id: note.id))
/// }
/// Text("Select a Note")
/// }
///
/// Style a navigation view by modifying it with the
/// ``View/navigationViewStyle(_:)`` view modifier. Use other modifiers, like
/// ``View/navigationTitle(_:)-avgj``, on views presented by the navigation
/// view to customize the navigation interface for the presented view.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
public struct NavigationView<Content> : View where Content : View {
/// Creates a destination-based navigation view.
///
/// Perform navigation by initializing a link with a destination view.
/// For example, consider a `ColorDetail` view that displays a color sample:
///
/// struct ColorDetail: View {
/// var color: Color
///
/// var body: some View {
/// color
/// .frame(width: 200, height: 200)
/// .navigationTitle(color.description.capitalized)
/// }
/// }
///
/// The following ``NavigationView`` presents three links to color detail
/// views:
///
/// NavigationView {
/// List {
/// NavigationLink("Purple", destination: ColorDetail(color: .purple))
/// NavigationLink("Pink", destination: ColorDetail(color: .pink))
/// NavigationLink("Orange", destination: ColorDetail(color: .orange))
/// }
/// .navigationTitle("Colors")
///
/// Text("Select a Color") // A placeholder to show before selection.
/// }
///
/// When the horizontal size class is ``UserInterfaceSizeClass/regular``,
/// like on an iPad in landscape mode, or on a Mac,
/// the navigation view presents itself as a multicolumn view,
/// using its second and later content views --- a single ``Text``
/// view in the example above --- as a placeholder for the corresponding
/// column:
///
/// ![A screenshot of a Mac window showing a multicolumn navigation view.
/// The left column lists the colors Purple, Pink, and Orange, with
/// none selected. The right column presents a placeholder view that says
/// Select a Color.](NavigationView-init-content-1)
///
/// When the user selects one of the navigation links from the
/// list, the linked destination view replaces the placeholder
/// text in the detail column:
///
/// ![A screenshot of a Mac window showing a multicolumn navigation view.
/// The left column lists the colors Purple, Pink, and Orange, with
/// Purple selected. The right column presents a detail view that shows a
/// purple square.](NavigationView-init-content-2)
///
/// When the size class is ``UserInterfaceSizeClass/compact``, like
/// on an iPhone in portrait orientation, the navigation view presents
/// itself as a single column that the user navigates as a stack. Tapping
/// one of the links replaces the list with the detail view, which
/// provides a back button to return to the list:
///
/// ![Two screenshots of an iPhone in portrait orientation connected by an
/// arrow. The first screenshot shows a single column consisting of a list
/// of colors with the names Purple, Pink, and Orange. The second
/// screenshot has the title Purple, and contains a purple square.
/// The arrow connects the Purple item in the list on the left to the
/// screenshot on the right.](NavigationView-init-content-3)
///
/// - Parameter content: A ``ViewBuilder`` that produces the content that
/// the navigation view wraps. Any views after the first act as
/// placeholders for corresponding columns in a multicolumn display.
public init(@ViewBuilder 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 specification for the appearance and interaction of a `NavigationView`.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
public protocol NavigationViewStyle {
}
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension NavigationViewStyle where Self == ColumnNavigationViewStyle {
/// A navigation view style represented by a series of views in columns.
public static var columns: ColumnNavigationViewStyle { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
extension NavigationViewStyle where Self == DefaultNavigationViewStyle {
/// The default navigation view style in the current context of the view
/// being styled.
public static var automatic: DefaultNavigationViewStyle { get }
}
@available(iOS 13.0, tvOS 13.0, watchOS 7.0, *)
@available(macOS, unavailable)
extension NavigationViewStyle where Self == StackNavigationViewStyle {
/// A navigation view style represented by a view stack that only shows a
/// single top view at a time.
public static var stack: StackNavigationViewStyle { get }
}
/// A property wrapper type that subscribes to an observable object and
/// invalidates a view whenever the observable object changes.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper @frozen public struct ObservedObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject {
/// A wrapper of the underlying observable 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 }
}
/// Creates an observed object with an initial value.
///
/// - Parameter initialValue: An initial value.
public init(initialValue: ObjectType)
/// Creates an observed object with an initial wrapped value.
///
/// You don't call this initializer directly. Instead, declare a property
/// with the `@ObservedObject` attribute, and provide an initial value.
///
/// - Parameter wrappedValue: An initial value.
public init(wrappedValue: ObjectType)
/// The underlying value referenced by the observed 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 `@ObservedObject` 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.
public var wrappedValue: ObjectType
/// A projection of the observed object that creates bindings to its
/// properties using dynamic member lookup.
///
/// Use the projected value to pass a binding value down a view hierarchy.
/// To get the `projectedValue`, prefix the property variable with `$`.
public var projectedValue: ObservedObject<ObjectType>.Wrapper { get }
}
/// A shape with a translation offset transform applied to it.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct OffsetShape<Content> : Shape where Content : Shape {
public var shape: Content
public var offset: CGSize
@inlinable public init(shape: Content, offset: CGSize)
/// 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
/// An indication of how to style a shape.
///
/// SwiftUI looks at a shape's role when deciding how to apply a
/// ``ShapeStyle`` at render time. The ``Shape`` protocol provides a
/// default implementation with a value of ``ShapeRole/fill``. If you
/// create a composite shape, you can provide an override of this property
/// to return another value, if appropriate.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public static var role: ShapeRole { get }
/// The type defining the data to animate.
public typealias AnimatableData = AnimatablePair<Content.AnimatableData, CGSize.AnimatableData>
/// The data to animate.
public var animatableData: OffsetShape<Content>.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
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension OffsetShape : InsettableShape where Content : InsettableShape {
/// Returns `self` inset by `amount`.
@inlinable public func inset(by amount: CGFloat) -> OffsetShape<Content.InsetShape>
/// The type of the inset shape.
public typealias InsetShape = OffsetShape<Content.InsetShape>
}
/// Provides functionality for opening a URL.
///
/// The `OpenURLAction` instance in the app's ``Environment`` offers
/// a handler that you can use to open a URL in response to some action.
/// Use the ``EnvironmentValues/openURL`` environment value to get the handler.
/// Then call the action's handler when you need to open a URL. For example,
/// you can open a support URL in response to when a user taps a button:
///
/// struct OpenUrlActionView: View {
/// @Environment(\.openURL) var openURL
///
/// var body: some View {
/// Button(action: contactSupport) {
/// Text("Email Support")
/// Image(systemName: "envelope.open")
/// }
/// }
///
/// func contactSupport() {
/// guard let url = URL(string: "https://www.example.com") else {
/// return
/// }
/// openURL(url)
/// }
/// }
///
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct OpenURLAction {
/// Opens a URL, following system conventions.
///
/// Use this method to attempt to open a URL. This function handles the
/// calling of the platform specific URL handler contained in the
/// `openURL` property stored the app's ``Environment``, and is used when
/// you call the function ``openURL(:_)``.
///
/// - Parameters:
/// - url: The URL to open.
public func callAsFunction(_ url: URL)
/// Asynchronously opens a URL, following system conventions.
///
/// Use this method when attempting to asynchronously open a URL; the
/// result indicates whether the system was able open the URL.
/// The completion runs after the system decides that it can open the URL,
/// but the full opening of the URL may not yet be complete when calling the
/// completion handler.
///
/// - Parameters:
/// - url: The URL to open.
/// - completion: A closure the method calls after determining if
/// it is possible to open the URL, although possibly before fully
/// opening the URL. The closure takes a Boolean that indicates whether
/// the URL can be opened.
@available(watchOS, unavailable)
public func callAsFunction(_ url: URL, completion: @escaping (_ accepted: Bool) -> Void)
}
/// A structure that computes views and disclosure groups on demand from an
/// underlying collection of tree-structured, identified data.
///
/// Use an outline group when you need a view that can represent a hierarchy
/// of data by using disclosure views. This allows the user to navigate the
/// tree structure by using the disclosure views to expand and collapse
/// branches.
///
/// In the following example, a tree structure of `FileItem` data offers a
/// simplified view of a file system. Passing the root of this tree and the
/// key path of its children allows you to quickly create a visual
/// representation of the file system.
///
/// struct FileItem: Hashable, Identifiable, CustomStringConvertible {
/// var id: Self { self }
/// var name: String
/// var children: [FileItem]? = nil
/// var description: String {
/// switch children {
/// case nil:
/// return "📄 \(name)"
/// case .some(let children):
/// return children.isEmpty ? "📂 \(name)" : "📁 \(name)"
/// }
/// }
/// }
///
/// let data =
/// FileItem(name: "users", children:
/// [FileItem(name: "user1234", children:
/// [FileItem(name: "Photos", children:
/// [FileItem(name: "photo001.jpg"),
/// FileItem(name: "photo002.jpg")]),
/// FileItem(name: "Movies", children:
/// [FileItem(name: "movie001.mp4")]),
/// FileItem(name: "Documents", children: [])
/// ]),
/// FileItem(name: "newuser", children:
/// [FileItem(name: "Documents", children: [])
/// ])
/// ])
///
/// OutlineGroup(data, children: \.children) { item in
/// Text("\(item.description)")
/// }
///
/// ### Type Parameters
///
/// Five generic type constraints define a specific `OutlineGroup` instance:
///
/// - `Data`: The type of a collection containing the children of an element in
/// the tree-shaped data.
/// - `ID`: The type of the identifier for an element.
/// - `Parent`: The type of the visual representation of an element whose
/// children property is non-`nil`
/// - `Leaf`: The type of the visual representation of an element whose
/// children property is `nil`.
/// - `Subgroup`: A type of a view that groups a parent view and a view
/// representing its children, typically with some mechanism for showing and
/// hiding the children
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct OutlineGroup<Data, ID, Parent, Leaf, Subgroup> where Data : RandomAccessCollection, ID : Hashable {
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension OutlineGroup where ID == Data.Element.ID, Parent : View, Parent == Leaf, Subgroup == DisclosureGroup<Parent, OutlineSubgroupChildren>, Data.Element : Identifiable {
/// Creates an outline group from a root data element and a key path to
/// its children.
///
/// This initializer creates an instance that uniquely identifies views
/// across updates based on the identity of the underlying data element.
///
/// All generated disclosure groups begin in the collapsed state.
///
/// Make sure that the identifier of a data element only changes if you
/// mean to replace that element with a new element, one with a new
/// identity. If the ID of an element changes, then the content view
/// generated from that element will lose any current state and animations.
///
/// - Parameters:
/// - root: The root of a collection of tree-structured, identified
/// data.
/// - children: A key path to a property whose non-`nil` value gives the
/// children of `data`. A non-`nil` but empty value denotes an element
/// capable of having children that's currently childless, such as an
/// empty directory in a file system. On the other hand, if the property
/// at the key path is `nil`, then the outline group treats `data` as a
/// leaf in the tree, like a regular file in a file system.
/// - content: A view builder that produces a content view based on an
/// element in `data`.
public init<DataElement>(_ root: DataElement, children: KeyPath<DataElement, Data?>, @ViewBuilder content: @escaping (DataElement) -> Leaf) where ID == DataElement.ID, DataElement : Identifiable, DataElement == Data.Element
/// Creates an outline group from a collection of root data elements and
/// a key path to its children.
///
/// This initializer creates an instance that uniquely identifies views
/// across updates based on the identity of the underlying data element.
///
/// All generated disclosure groups begin in the collapsed state.
///
/// Make sure that the identifier of a data element only changes if you
/// mean to replace that element with a new element, one with a new
/// identity. If the ID of an element changes, then the content view
/// generated from that element will lose any current state and animations.
///
/// - Parameters:
/// - data: A collection of tree-structured, identified data.
/// - children: A key path to a property whose non-`nil` value gives the
/// children of `data`. A non-`nil` but empty value denotes an element
/// capable of having children that's currently childless, such as an
/// empty directory in a file system. On the other hand, if the property
/// at the key path is `nil`, then the outline group treats `data` as a
/// leaf in the tree, like a regular file in a file system.
/// - content: A view builder that produces a content view based on an
/// element in `data`.
public init<DataElement>(_ data: Data, children: KeyPath<DataElement, Data?>, @ViewBuilder content: @escaping (DataElement) -> Leaf) where ID == DataElement.ID, DataElement : Identifiable, DataElement == Data.Element
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension OutlineGroup where Parent : View, Parent == Leaf, Subgroup == DisclosureGroup<Parent, OutlineSubgroupChildren> {
/// Creates an outline group from a root data element, the key path to its
/// identifier, and a key path to its children.
///
/// This initializer creates an instance that uniquely identifies views
/// across updates based on the identity of the underlying data element.
///
/// All generated disclosure groups begin in the collapsed state.
///
/// Make sure that the identifier of a data element only changes if you
/// mean to replace that element with a new element, one with a new
/// identity. If the ID of an element changes, then the content view
/// generated from that element will lose any current state and animations.
///
/// - Parameters:
/// - root: The root of a collection of tree-structured, identified
/// data.
/// - id: The key path to a data element's identifier.
/// - children: A key path to a property whose non-`nil` value gives the
/// children of `data`. A non-`nil` but empty value denotes an element
/// capable of having children that's currently childless, such as an
/// empty directory in a file system. On the other hand, if the property
/// at the key path is `nil`, then the outline group treats `data` as a
/// leaf in the tree, like a regular file in a file system.
/// - content: A view builder that produces a content view based on an
/// element in `data`.
public init<DataElement>(_ root: DataElement, id: KeyPath<DataElement, ID>, children: KeyPath<DataElement, Data?>, @ViewBuilder content: @escaping (DataElement) -> Leaf) where DataElement == Data.Element
/// Creates an outline group from a collection of root data elements, the
/// key path to a data element's identifier, and a key path to its children.
///
/// This initializer creates an instance that uniquely identifies views
/// across updates based on the identity of the underlying data element.
///
/// All generated disclosure groups begin in the collapsed state.
///
/// Make sure that the identifier of a data element only changes if you
/// mean to replace that element with a new element, one with a new
/// identity. If the ID of an element changes, then the content view
/// generated from that element will lose any current state and animations.
///
/// - Parameters:
/// - data: A collection of tree-structured, identified data.
/// - id: The key path to a data element's identifier.
/// - children: A key path to a property whose non-`nil` value gives the
/// children of `data`. A non-`nil` but empty value denotes an element
/// capable of having children that's currently childless, such as an
/// empty directory in a file system. On the other hand, if the property
/// at the key path is `nil`, then the outline group treats `data` as a
/// leaf in the tree, like a regular file in a file system.
/// - content: A view builder that produces a content view based on an
/// element in `data`.
public init<DataElement>(_ data: Data, id: KeyPath<DataElement, ID>, children: KeyPath<DataElement, Data?>, @ViewBuilder content: @escaping (DataElement) -> Leaf) where DataElement == Data.Element
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension OutlineGroup : View where Parent : View, Leaf : View, Subgroup : 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 primitive 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>.
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
}
/// A type-erased view representing the children in an outline subgroup.
///
/// ``OutlineGroup`` uses this type as a generic constraint for the `Content`
/// of the ``DisclosureGroup`` instances it creates.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct OutlineSubgroupChildren : 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 index view style that places a page index view over its content.
///
/// Do not use this type directly. Instead, use ``IndexViewStyle/page``.
@available(iOS 14.0, tvOS 14.0, watchOS 8.0, *)
@available(macOS, unavailable)
public struct PageIndexViewStyle : IndexViewStyle {
/// The background style for the page index view.
public struct BackgroundDisplayMode {
/// Background will use the default for the platform.
public static let automatic: PageIndexViewStyle.BackgroundDisplayMode
/// Background is only shown while the index view is interacted with.
@available(watchOS, unavailable)
public static let interactive: PageIndexViewStyle.BackgroundDisplayMode
/// Background is always displayed behind the page index view.
@available(watchOS, unavailable)
public static let always: PageIndexViewStyle.BackgroundDisplayMode
/// Background is never displayed behind the page index view.
public static let never: PageIndexViewStyle.BackgroundDisplayMode
}
/// Creates a page index view style.
///
/// - Parameter backgroundDisplayMode: The display mode of the background of any
/// page index views receiving this style
public init(backgroundDisplayMode: PageIndexViewStyle.BackgroundDisplayMode = .automatic)
}
/// A `TabViewStyle` that implements a paged scrolling `TabView`.
///
/// Do not use this type directly. Instead, use ``TabViewStyle/page``.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, *)
@available(macOS, unavailable)
public struct PageTabViewStyle : TabViewStyle {
/// A style for displaying the page index view
public struct IndexDisplayMode {
/// Displays an index view when there are more than one page
public static let automatic: PageTabViewStyle.IndexDisplayMode
/// Always display an index view regardless of page count
@available(watchOS 8.0, *)
public static let always: PageTabViewStyle.IndexDisplayMode
/// Never display an index view
@available(watchOS 8.0, *)
public static let never: PageTabViewStyle.IndexDisplayMode
}
/// Creates a new `PageTabViewStyle` with an index display mode
public init(indexDisplayMode: PageTabViewStyle.IndexDisplayMode = .automatic)
}
/// The outline of a 2D shape.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Path : Equatable, LosslessStringConvertible {
/// Creates an empty path.
public init()
/// Creates a path from an immutable shape path.
public init(_ path: CGPath)
/// Creates a path from a copy of a mutable shape path.
public init(_ path: CGMutablePath)
/// Creates a path as the given rectangle.
public init(_ rect: CGRect)
/// Creates a path as the given rounded rectangle.
public init(roundedRect rect: CGRect, cornerSize: CGSize, style: RoundedCornerStyle = .circular)
/// Creates a path as the given rounded rectangle.
public init(roundedRect rect: CGRect, cornerRadius: CGFloat, style: RoundedCornerStyle = .circular)
/// Creates a path as an ellipse inscribed within the given rectangle.
public init(ellipseIn rect: CGRect)
/// Creates an empty path, and then executes the closure to add the initial
/// elements.
public init(_ callback: (inout Path) -> ())
/// Initializes from the result of a previous call to
/// `Path.stringRepresentation`. Fails if the `string` does not
/// describe a valid path.
public init?(_ string: String)
/// A description of the path that may be used to recreate the path
/// via `init?(_:)`.
public var description: String { get }
/// An immutable path representing the elements in the path.
public var cgPath: CGPath { get }
/// A Boolean value indicating whether the path contains zero elements.
public var isEmpty: Bool { get }
/// A rectangle containing all path segments.
public var boundingRect: CGRect { get }
/// Returns true if the path contains a specified point.
///
/// If `eoFill` is true, this method uses the even-odd rule to define which
/// points are inside the path. Otherwise, it uses the non-zero rule.
public func contains(_ p: CGPoint, eoFill: Bool = false) -> Bool
/// An element of a path.
@frozen public enum Element : Equatable {
/// A path element that terminates the current subpath (without closing
/// it) and defines a new current point.
case move(to: CGPoint)
/// A line from the previous current point to the given point, which
/// becomes the new current point.
case line(to: CGPoint)
/// A quadratic Bézier curve from the previous current point to the
/// given end-point, using the single control point to define the curve.
///
/// The end-point of the curve becomes the new current point.
case quadCurve(to: CGPoint, control: CGPoint)
/// A cubic Bézier curve from the previous current point to the given
/// end-point, using the two control points to define the curve.
///
/// The end-point of the curve becomes the new current point.
case curve(to: CGPoint, control1: CGPoint, control2: CGPoint)
/// A line from the start point of the current subpath (if any) to the
/// current point, which terminates the subpath.
///
/// After closing the subpath, the current point becomes undefined.
case closeSubpath
/// 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: Path.Element, b: Path.Element) -> Bool
}
/// Calls `body` with each element in the path.
public func forEach(_ body: (Path.Element) -> Void)
/// Returns a stroked copy of the path using `style` to define how the
/// stroked outline is created.
public func strokedPath(_ style: StrokeStyle) -> Path
/// Returns a partial copy of the path.
///
/// The returned path contains the region between `from` and `to`, both of
/// which must be fractions between zero and one defining points
/// linearly-interpolated along the path.
public func trimmedPath(from: CGFloat, to: CGFloat) -> Path
/// 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: Path, b: Path) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Path : 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 _: 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 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Path {
/// Begins a new subpath at the specified point.
public mutating func move(to p: CGPoint)
/// Appends a straight line segment from the current point to the specified
/// point.
public mutating func addLine(to p: CGPoint)
/// Adds a quadratic Bézier curve to the path, with the specified end point
/// and control point.
public mutating func addQuadCurve(to p: CGPoint, control cp: CGPoint)
/// Adds a cubic Bézier curve to the path, with the specified end point and
/// control points.
public mutating func addCurve(to p: CGPoint, control1 cp1: CGPoint, control2 cp2: CGPoint)
/// Closes and completes the current subpath.
public mutating func closeSubpath()
/// Adds a rectangular subpath to the path.
public mutating func addRect(_ rect: CGRect, transform: CGAffineTransform = .identity)
/// Adds a rounded rectangle to the path.
public mutating func addRoundedRect(in rect: CGRect, cornerSize: CGSize, style: RoundedCornerStyle = .circular, transform: CGAffineTransform = .identity)
/// Adds an ellipse to the path.
public mutating func addEllipse(in rect: CGRect, transform: CGAffineTransform = .identity)
/// Adds a sequence of rectangular subpaths to the path.
public mutating func addRects(_ rects: [CGRect], transform: CGAffineTransform = .identity)
/// Adds a sequence of connected straight-line segments to the path.
public mutating func addLines(_ lines: [CGPoint])
/// Adds an arc of a circle to the path, specified with a radius and a
/// difference in angle.
public mutating func addRelativeArc(center: CGPoint, radius: CGFloat, startAngle: Angle, delta: Angle, transform: CGAffineTransform = .identity)
/// Adds an arc of a circle to the path, specified with a radius and angles.
public mutating func addArc(center: CGPoint, radius: CGFloat, startAngle: Angle, endAngle: Angle, clockwise: Bool, transform: CGAffineTransform = .identity)
/// Adds an arc of a circle to the path, specified with a radius and two
/// tangent lines.
public mutating func addArc(tangent1End p1: CGPoint, tangent2End p2: CGPoint, radius: CGFloat, transform: CGAffineTransform = .identity)
/// Appends a copy of the given path to this path.
public mutating func addPath(_ path: Path, transform: CGAffineTransform = .identity)
/// Returns the last point in the path, or nil if the path contains
/// no points.
public var currentPoint: CGPoint? { get }
/// Returns a path constructed by applying the transform to all points of
/// the path.
public func applying(_ transform: CGAffineTransform) -> Path
/// Returns a path constructed by translating `self` by `(dx, dy)`.
public func offsetBy(dx: CGFloat, dy: CGFloat) -> Path
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Path.Element : Sendable {
}
/// A schedule for updating a timeline view at regular intervals.
///
/// Do not use this type directly. Instead, use
/// ``TimelineSchedule/periodic(from:by:)``.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct PeriodicTimelineSchedule : TimelineSchedule {
/// The sequence of dates in periodic schedule.
///
/// The ``PeriodicTimelineSchedule/entries(from:mode:)`` method returns
/// a value of this type, which is a
/// <doc://com.apple.documentation/documentation/Swift/Sequence>
/// of periodic dates 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 {
/// 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 = PeriodicTimelineSchedule.Entries
}
/// Creates a periodic update schedule.
///
/// Use the ``PeriodicTimelineSchedule/entries(from:mode:)`` method
/// to get the sequence of dates.
///
/// - Parameters:
/// - startDate: The date on which to start the sequence.
/// - interval: The time interval between successive sequence entries.
@available(iOS, introduced: 15.0, deprecated: 15.0, message: "Use `.periodic(from:by:)` instead.")
@available(macOS, introduced: 12.0, deprecated: 12.0, message: "Use `.periodic(from:by:)` instead.")
@available(tvOS, introduced: 15.0, deprecated: 15.0, message: "Use `.periodic(from:by:)` instead.")
@available(watchOS, introduced: 8.0, deprecated: 8.0, message: "Use `.periodic(from:by:)` instead.")
public init(from startDate: Date, by interval: TimeInterval)
/// Provides a sequence of periodic dates starting from around a given date.
///
/// A ``TimelineView`` that you create with a schedule calls this method
/// to ask the schedule when to update its content. The method returns
/// a sequence of equally spaced dates in increasing order that represent
/// points in time when the timeline view should update.
///
/// The schedule defines its periodicity and phase aligment based on the
/// parameters you pass to its ``init(from:by:)`` initializer.
/// For example, for a `startDate` and `interval` of `10:09:30` and
/// `60` seconds, the schedule prepares to issue dates half past each
/// minute. The `startDate` that you pass to the `entries(from:mode:)`
/// method then dictates the first date of the sequence as the beginning of
/// the interval that the start date overlaps. Continuing the example above,
/// a start date of `10:34:45` causes the first sequence entry to be
/// `10:34:30`, because that's the start of the interval in which the
/// start date appears.
public func entries(from startDate: Date, mode: TimelineScheduleMode) -> PeriodicTimelineSchedule.Entries
}
/// A control for selecting from a set of mutually exclusive values.
///
/// You create a picker by providing a selection binding, a label, and the
/// content for the picker to display. Set the `selection` parameter to a bound
/// property that provides the value to display as the current selection. Set
/// the label to a view that visually describes the purpose of selecting content
/// in the picker, and then provide the content for the picker to display.
///
/// For example, consider the following enumeration of ice cream flavors:
///
/// enum Flavor: String, CaseIterable, Identifiable {
/// case chocolate
/// case vanilla
/// case strawberry
///
/// var id: String { self.rawValue }
/// }
///
/// You can create a picker to select among these values by providing ``Text``
/// views in the picker initializer's content. You can optionally provide a
/// string as the first parameter; if you do, the picker creates a ``Text``
/// label using this string:
///
/// @State private var selectedFlavor = Flavor.chocolate
///
/// Picker("Flavor", selection: $selectedFlavor) {
/// Text("Chocolate").tag(Flavor.chocolate)
/// Text("Vanilla").tag(Flavor.vanilla)
/// Text("Strawberry").tag(Flavor.strawberry)
/// }
/// Text("Selected flavor: \(selectedFlavor.rawValue)")
///
/// You append a tag to each text view so that the type of each selection
/// matches the type of the bound state variable.
///
/// ### Iterating Over a Picker’s Options
///
/// To provide selection values for the `Picker` without explicitly listing
/// each option, you can create the picker with a ``ForEach`` construct, like
/// this:
///
/// Picker("Flavor", selection: $selectedFlavor) {
/// ForEach(Flavor.allCases) { flavor in
/// Text(flavor.rawValue.capitalized)
/// }
/// }
///
/// In this case, ``ForEach`` automatically assigns a tag to the selection
/// views, using each option's `id`, which it can do because `Flavor` conforms
/// to the <doc://com.apple.documentation/documentation/Swift/Identifiable>
/// protocol.
///
/// On the other hand, if the selection type doesn't match the input to the
/// ``ForEach``, you need to provide an explicit tag. The following example
/// shows a picker that's bound to a `Topping` type, even though the options
/// are all `Flavor` instances. Each option uses ``View/tag(_:)`` to associate
/// a topping with the flavor it displays.
///
/// enum Topping: String, CaseIterable, Identifiable {
/// case nuts
/// case cookies
/// case blueberries
///
/// var id: String { self.rawValue }
/// }
/// extension Flavor {
/// var suggestedTopping: Topping {
/// switch self {
/// case .chocolate: return .nuts
/// case .vanilla: return .cookies
/// case .strawberry: return .blueberries
/// }
/// }
/// }
/// @State var suggestedTopping: Topping = .cookies
///
/// Picker("Suggest a topping for:", selection: $suggestedTopping) {
/// ForEach(Flavor.allCases) { flavor in
/// Text(flavor.rawValue.capitalized)
/// .tag(flavor.suggestedTopping)
/// }
/// }
/// Text("suggestedTopping: \(suggestedTopping.rawValue)")
///
/// ### Styling Pickers
///
/// You can customize the appearance and interaction of pickers by creating
/// styles that conform to the ``PickerStyle`` protocol. You create your own style
/// or use one of the styles provided by SwiftUI, like ``PickerStyle/segmented``
/// or ``PickerStyle/menu``.
///
/// To set a specific style for all picker instances within a view, use the
/// ``View/pickerStyle(_:)`` modifier. The following example adds a second binding
/// type, `Topping`, and applies the ``PickerStyle/segmented`` style to two pickers:
///
/// @State private var selectedFlavor = Flavor.chocolate
/// @State private var selectedTopping = Topping.nuts
///
/// VStack {
/// Picker("Flavor", selection: $selectedFlavor) {
/// ForEach(Flavor.allCases) { flavor in
/// Text(flavor.rawValue.capitalized)
/// }
/// }
/// Picker("Topping", selection: $selectedTopping) {
/// ForEach(Topping.allCases) { flavor in
/// Text(flavor.rawValue.capitalized)
/// }
/// }
///
/// Text("Selected flavor: \(selectedFlavor.rawValue)")
/// Text("Selected topping: \(selectedTopping.rawValue)")
/// }
/// .pickerStyle(.segmented)
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct Picker<Label, SelectionValue, Content> : View where Label : View, SelectionValue : Hashable, 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 primitive 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>.
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 Picker {
/// Creates a picker that displays a custom label.
///
/// - Parameters:
/// - selection: A binding to a property that determines the
/// currently-selected option.
/// - content: A view that contains the set of options.
/// - label: A view that describes the purpose of selecting an option.
public init(selection: Binding<SelectionValue>, @ViewBuilder content: () -> Content, @ViewBuilder label: () -> Label)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Picker where Label == Text {
/// Creates a picker that generates its label from a localized string key.
///
/// - Parameters:
/// - titleKey: A localized string key that describes the purpose of
/// selecting an option.
/// - selection: A binding to a property that determines the
/// currently-selected option.
/// - content: A view that contains the set of options.
///
/// 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 picker with a string variable, use
/// ``init(_:selection:content:)-5njtq`` instead.
public init(_ titleKey: LocalizedStringKey, selection: Binding<SelectionValue>, @ViewBuilder content: () -> Content)
/// Creates a picker that generates its label from a string.
///
/// - Parameters:
/// - title: A string that describes the purpose of selecting an option.
/// - selection: A binding to a property that determines the
/// currently-selected option.
/// - content: A view that contains the set of options.
///
/// 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 picker with a localized string key, use
/// ``init(_:selection:content:)-6lwfn`` instead.
public init<S>(_ title: S, selection: Binding<SelectionValue>, @ViewBuilder content: () -> Content) where S : StringProtocol
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Picker {
/// Creates a picker that displays a custom label.
///
/// - Parameters:
/// - selection: A binding to a property that determines the
/// currently-selected option.
/// - label: A view that describes the purpose of selecting an option.
/// - content: A view that contains the set of options.
@available(iOS, deprecated: 100000.0, renamed: "Picker(selection:content:label:)")
@available(macOS, deprecated: 100000.0, renamed: "Picker(selection:content:label:)")
@available(tvOS, deprecated: 100000.0, renamed: "Picker(selection:content:label:)")
@available(watchOS, deprecated: 100000.0, renamed: "Picker(selection:content:label:)")
public init(selection: Binding<SelectionValue>, label: Label, @ViewBuilder content: () -> Content)
}
/// A type that specifies the appearance and interaction of all pickers within
/// a view hierarchy.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol PickerStyle {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
@available(watchOS, unavailable)
extension PickerStyle where Self == SegmentedPickerStyle {
/// A picker style that presents the options as a group of radio buttons.
///
/// Use this style when there are two to five options. Consider using
/// ``PickerStyle/menu`` when there are more than five options.
///
/// For each option's label, use sentence-style capitalization without
/// ending punctuation, like a period or colon.
///
/// To apply this style to a picker, or to a view that contains pickers, use
/// the ``View/pickerStyle(_:)`` modifier.
public static var segmented: SegmentedPickerStyle { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension PickerStyle where Self == InlinePickerStyle {
/// A `PickerStyle` where each option is displayed inline with other views
/// in the current container.
public static var inline: InlinePickerStyle { get }
}
@available(iOS 13.0, watchOS 6.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
extension PickerStyle where Self == WheelPickerStyle {
/// A picker style that presents the options in a scrollable wheel that
/// shows the selected option and a few neighboring options.
///
/// Because most options aren't visible, organize them in a predictable
/// order, such as alphabetically.
///
/// To apply this style to a picker, or to a view that contains pickers, use
/// the ``View/pickerStyle(_:)`` modifier.
public static var wheel: WheelPickerStyle { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension PickerStyle where Self == DefaultPickerStyle {
/// The default picker style, based on the picker's context.
///
/// How a picker using the default picker style appears largely depends on
/// the platform and the view type in which it appears. For example, in a
/// standard view, the default picker styles by platform are:
///
/// * On iOS and watchOS the default is a wheel.
/// * On macOS, the default is a pop-up button.
/// * On tvOS, the default is a segmented control.
///
/// The default picker style may also take into account other factors — like
/// whether the picker appears in a container view — when setting the
/// appearance of a picker.
///
/// You can override a picker’s style. To apply the default style to a
/// picker, or to a view that contains pickers, use the
/// ``View/pickerStyle(_:)`` modifier.
public static var automatic: DefaultPickerStyle { get }
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension PickerStyle where Self == MenuPickerStyle {
/// A picker style that presents the options as a menu when the user presses a
/// button, or as a submenu when nested within a larger menu.
///
/// Use this style when there are more than five options. Consider using
/// ``PickerStyle/inline`` when there are fewer than five options.
///
/// The button itself indicates the selected option. You can include additional
/// controls in the set of options, such as a button to customize the list of
/// options.
///
/// To apply this style to a picker, or to a view that contains pickers, use the
/// ``View/pickerStyle(_:)`` modifier.
public static var menu: MenuPickerStyle { get }
}
/// A set of view types that may be pinned to the bounds of a scroll view.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct PinnedScrollableViews : 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)
/// The header view of each `Section` will be pinned.
public static let sectionHeaders: PinnedScrollableViews
/// The footer view of each `Section` will be pinned.
public static let sectionFooters: PinnedScrollableViews
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = PinnedScrollableViews
/// 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 = PinnedScrollableViews
/// 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
}
/// A button style that doesn't style or decorate its content while idle, but
/// may apply a visual effect to indicate the pressed, focused, or enabled state
/// of the button.
///
/// Do not use this type directly. Instead, use ``PrimitiveButtonStyle/plain``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct PlainButtonStyle : PrimitiveButtonStyle {
/// Creates a plain 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: PlainButtonStyle.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 plain list.
///
/// Do not use this type directly. Instead, use ``ListStyle/plain``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct PlainListStyle : ListStyle {
/// Creates a plain list style.
public init()
}
/// A text field style with no decoration.
///
/// Do not use this type directly. Instead, use ``TextFieldStyle/plain``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct PlainTextFieldStyle : TextFieldStyle {
public init()
}
/// An attachment anchor for a popover.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum PopoverAttachmentAnchor {
/// The anchor point for the popover relative to the source's frame.
case rect(Anchor<CGRect>.Source)
/// The anchor point for the popover expressed as a unit point that
/// describes possible alignments relative to a SwiftUI view.
case point(UnitPoint)
}
/// A named value produced by a view.
///
/// A view with multiple children automatically combines its values for a given
/// preference into a single value visible to its ancestors.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol PreferenceKey {
/// The type of value produced by this preference.
associatedtype Value
/// The default value of the preference.
///
/// Views that have no explicit value for the key produce this default
/// value. Combining child views may remove an implicit value produced by
/// using the default. This means that `reduce(value: &x, nextValue:
/// {defaultValue})` shouldn't change the meaning of `x`.
static var defaultValue: Self.Value { get }
/// Combines a sequence of values by modifying the previously-accumulated
/// value with the result of a closure that provides the next value.
///
/// This method receives its values in view-tree order. Conceptually, this
/// combines the preference value from one tree with that of its next
/// sibling.
///
/// - Parameters:
/// - value: The value accumulated through previous calls to this method.
/// The implementation should modify this value.
/// - nextValue: A closure that returns the next value in the sequence.
static func reduce(value: inout Self.Value, nextValue: () -> Self.Value)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension PreferenceKey where Self.Value : ExpressibleByNilLiteral {
/// Let nil-expressible values default-initialize to nil.
public static var defaultValue: Self.Value { get }
}
/// A key for specifying the preferred color scheme.
@available(iOS 13.0, macOS 11.0, tvOS 13.0, watchOS 6.0, *)
public struct PreferredColorSchemeKey : PreferenceKey {
/// The type of value produced by this preference.
public typealias Value = ColorScheme?
/// Combines a sequence of values by modifying the previously-accumulated
/// value with the result of a closure that provides the next value.
///
/// This method receives its values in view-tree order. Conceptually, this
/// combines the preference value from one tree with that of its next
/// sibling.
///
/// - Parameters:
/// - value: The value accumulated through previous calls to this method.
/// The implementation should modify this value.
/// - nextValue: A closure that returns the next value in the sequence.
public static func reduce(value: inout PreferredColorSchemeKey.Value, nextValue: () -> PreferredColorSchemeKey.Value)
}
/// An indication whether a view is currently presented by another view.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Use EnvironmentValues.isPresented or EnvironmentValues.dismiss")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use EnvironmentValues.isPresented or EnvironmentValues.dismiss")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Use EnvironmentValues.isPresented or EnvironmentValues.dismiss")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Use EnvironmentValues.isPresented or EnvironmentValues.dismiss")
public struct PresentationMode {
/// Indicates whether a view is currently presented.
public var isPresented: Bool { get }
/// Dismisses the view if it is currently presented.
///
/// If `isPresented` is false, `dismiss()` is a no-op.
public mutating func dismiss()
}
/// A context type for use with a preview.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public protocol PreviewContext {
/// Returns the context's value for a key, or a the key's default value
/// if the context doesn't define a value for the key.
subscript<Key>(key: Key.Type) -> Key.Value where Key : PreviewContextKey { get }
}
/// A key type for a preview context.
///
/// The default value is `nil`.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public protocol PreviewContextKey {
/// The type of the value returned by the key.
associatedtype Value
/// The default value of the key.
static var defaultValue: Self.Value { get }
}
/// A simulator device that runs a preview.
///
/// Create a preview device by name, like "iPhone X", or by model number,
/// like "iPad8,1". Use the device in a call to the ``View/previewDevice(_:)``
/// modifier to set a preview device that doesn't change when you change the
/// run destination in Xcode:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// CircleImage()
/// .previewDevice(PreviewDevice(rawValue: "iPad Pro (11-inch)"))
/// }
/// }
///
/// You can get a list of supported preview device names by using the
/// `xcrun` command in the Terminal app:
///
/// % xcrun simctl list devicetypes
///
/// Additionally, you can use the following values for macOS platform
/// development:
/// - "Mac"
/// - "Mac Catalyst"
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct PreviewDevice : RawRepresentable, ExpressibleByStringLiteral {
/// 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: String
/// 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: String)
/// Creates an instance initialized to the given string value.
///
/// - Parameter value: The value of the new instance.
public init(stringLiteral: String)
/// A type that represents an extended grapheme cluster literal.
///
/// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,
/// `String`, and `StaticString`.
public typealias ExtendedGraphemeClusterLiteralType = String
/// 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 = String
/// A type that represents a string literal.
///
/// Valid types for `StringLiteralType` are `String` and `StaticString`.
public typealias StringLiteralType = String
/// A type that represents a Unicode scalar literal.
///
/// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,
/// `Character`, `String`, and `StaticString`.
public typealias UnicodeScalarLiteralType = String
}
/// A size constraint for a preview.
///
/// Customize the layout of a preview by providing one of these values to
/// the ``View/previewLayout(_:)`` modifier. For example, you can tell the
/// preview to take up only the amount of space that the view requires
/// with ``PreviewLayout/sizeThatFits``:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// CircleImage()
/// .previewLayout(.sizeThatFits)
/// }
/// }
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum PreviewLayout {
/// Center the preview in a container the size of the device on which the
/// preview is running.
case device
/// Fit the container to the size of the preview when offered the size of
/// the device that the preview is running on.
case sizeThatFits
/// Center the preview in a fixed size container with the given dimensions.
///
/// - Parameters:
/// - width: The width of the container.
/// - height: The height of the container.
case fixed(width: CGFloat, height: CGFloat)
}
/// Platforms that can run the preview.
///
/// Xcode infers the platform for a preview based on the currently
/// selected target. If you have a multiplatform target and want to
/// suggest a particular target for a preview, implement the
/// ``PreviewProvider/platform-75xu4`` computed property as a hint,
/// and specify one of the preview platforms:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// CircleImage()
/// }
///
/// static var platform: PreviewPlatform? {
/// PreviewPlatform.tvOS
/// }
/// }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum PreviewPlatform {
/// Specifies iOS as the preview platform.
case iOS
/// Specifies macOS as the preview platform.
case macOS
/// Specifies tvOS as the preview platform.
case tvOS
/// Specifies watchOS as the preview platform.
case watchOS
/// 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: PreviewPlatform, b: PreviewPlatform) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension PreviewPlatform : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension PreviewPlatform : Hashable {
}
/// A type that produces view previews in Xcode.
///
/// Create an Xcode preview by declaring a structure that conforms to the
/// `PreviewProvider` protocol. Implement the required
/// ``PreviewProvider/previews-swift.type.property`` computed property,
/// and return the view to display:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// CircleImage()
/// }
/// }
///
/// Xcode statically discovers preview providers in your project and generates
/// previews for any providers currently open in the source editor.
/// Xcode generates the preview using the current run destination as a hint
/// for which device to display. For example, Xcode shows the following preview
/// if you've selected an iOS target to run on the iPhone 12 Pro Max simulator:
///
/// ![A screenshot of the Xcode canvas previewing a circular image on an
/// iPhone in the portrait orientation.](PreviewProvider-1)
///
/// When you create a new file (File > New > File)
/// and choose the SwiftUI view template, Xcode automatically inserts a
/// preview structure at the bottom of the file that you can configure.
/// You can also create new preview structures in an existing SwiftUI
/// view file by choosing Editor > Create Preview.
///
/// Customize the preview's appearance by adding view modifiers, just like you
/// do when building a custom ``View``. This includes preview-specific
/// modifiers that let you control aspects of the preview, like the device
/// orientation:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// CircleImage()
/// .previewInterfaceOrientation(.landscapeLeft)
/// }
/// }
///
/// ![A screenshot of the Xcode canvas previewing a circular image on an
/// iPhone in the landscape left orientation.](PreviewProvider-2)
///
/// For the complete list of preview customizations,
/// see <doc:Previews-in-Xcode>.
///
/// Xcode creates different previews for each view in your preview,
/// so you can see variations side by side. For example, you
/// might want to see a view's light and dark appearances simultaneously:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// CircleImage()
/// CircleImage()
/// .preferredColorScheme(.dark)
/// }
/// }
///
/// Use a ``Group`` when you want to maintain different previews, but apply a
/// single modifier to all of them:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// Group {
/// CircleImage()
/// CircleImage()
/// .preferredColorScheme(.dark)
/// }
/// .previewLayout(.sizeThatFits)
/// }
/// }
///
/// ![A screenshot of the Xcode canvas previewing a circular image twice,
/// once with a light appearance and once with a dark appearance. Both
/// previews take up only as much room as they need to fit the circular
/// image.](PreviewProvider-3)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol PreviewProvider : _PreviewProvider {
/// The type to preview.
///
/// When you create a preview, Swift infers this type from your
/// implementation of the required
/// ``PreviewProvider/previews-swift.type.property`` property.
associatedtype Previews : View
/// A collection of views to preview.
///
/// Implement a computed `previews` property to indicate the content to
/// preview. Xcode generates a preview for each view that you list. You
/// can apply ``View`` modifiers to the views, like you do
/// when creating a custom view. For a preview, you can also use
/// various preview-specific modifiers that customize the preview.
/// For example, you can choose a specific device for the preview
/// by adding the ``View/previewDevice(_:)`` modifier:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// CircleImage()
/// .previewDevice(PreviewDevice(rawValue: "iPad Pro (11-inch)"))
/// }
/// }
///
/// For the full list of preview-specific modifiers,
/// see <doc:Previews-in-Xcode>.
@ViewBuilder static var previews: Self.Previews { get }
/// The platform on which to run the provider.
///
/// Xcode infers the platform for a preview based on the currently
/// selected target. If you have a multiplatform target and want to
/// suggest a particular target for a preview, implement the
/// `platform` computed property to provide a hint,
/// and specify one of the ``PreviewPlatform`` values:
///
/// struct CircleImage_Previews: PreviewProvider {
/// static var previews: some View {
/// CircleImage()
/// }
///
/// static var platform: PreviewPlatform? {
/// PreviewPlatform.tvOS
/// }
/// }
///
/// Xcode ignores this value unless you have a multiplatform target.
static var platform: PreviewPlatform? { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension PreviewProvider {
/// The platform to run the provider on.
///
/// This default implementation of the ``PreviewProvider/platform-75xu4``
/// computed property returns `nil`. Rely on this implementation unless
/// you have a multiplatform target and want to suggest a particular
/// platform for a preview.
public static var platform: PreviewPlatform? { get }
}
/// A type that applies custom 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(_:)-66fbx`` modifier. Specify a style that conforms to
/// `PrimitiveButtonStyle` to create a button with custom interaction
/// behavior. To create a button with the standard button interaction behavior
/// defined for each platform, use ``ButtonStyle`` instead.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol PrimitiveButtonStyle {
/// 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 = PrimitiveButtonStyleConfiguration
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension PrimitiveButtonStyle where Self == BorderedProminentButtonStyle {
/// A button style that applies standard border prominent artwork based on
/// the button's context.
///
/// To apply this style to a button, or to a view that contains buttons, use
/// the ``View/buttonStyle(_:)-66fbx`` modifier.
public static var borderedProminent: BorderedProminentButtonStyle { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension PrimitiveButtonStyle where Self == PlainButtonStyle {
/// A button style that doesn't style or decorate its content while idle,
/// but may apply a visual effect to indicate the pressed, focused, or
/// enabled state of the button.
///
/// To apply this style to a button, or to a view that contains buttons, use
/// the ``View/buttonStyle(_:)-66fbx`` modifier.
public static var plain: PlainButtonStyle { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension PrimitiveButtonStyle where Self == DefaultButtonStyle {
/// The default button style, based on the button's context.
///
/// If you create a button directly on a blank canvas, the style varies by
/// platform. iOS uses the borderless button style by default, whereas macOS,
/// tvOS, and watchOS use the bordered button style.
///
/// If you create a button inside a container, like a ``List``, the style
/// resolves to the recommended style for buttons inside that container for
/// that specific platform.
///
/// You can override a button's style. To apply the default style to a
/// button, or to a view that contains buttons, use the
/// ``View/buttonStyle(_:)-66fbx`` modifier.
public static var automatic: DefaultButtonStyle { get }
}
@available(iOS 13.0, macOS 10.15, watchOS 8.0, *)
@available(tvOS, unavailable)
extension PrimitiveButtonStyle where Self == BorderlessButtonStyle {
/// A button style that doesn't apply a border.
///
/// To apply this style to a button, or to a view that contains buttons, use
/// the ``View/buttonStyle(_:)-66fbx`` modifier.
public static var borderless: BorderlessButtonStyle { get }
}
@available(iOS 15.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
extension PrimitiveButtonStyle where Self == BorderedButtonStyle {
/// A button style that applies standard border artwork based on the
/// button's context.
///
/// To apply this style to a button, or to a view that contains buttons, use
/// the ``View/buttonStyle(_:)-66fbx`` modifier.
public static var bordered: BorderedButtonStyle { get }
}
/// The properties of a button.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct PrimitiveButtonStyleConfiguration {
/// 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 describing the button's purpose.
///
/// A value of `nil` means that the Button has no 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: PrimitiveButtonStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// configuration.label
/// .onTapGesture {
/// configuration.trigger()
/// }
/// .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.](PrimitiveButtonStyleConfiguration-role-1)
public let role: ButtonRole?
/// A view that describes the effect of calling the button's action.
public let label: PrimitiveButtonStyleConfiguration.Label
/// Performs the button's action.
public func trigger()
}
/// A view that shows the progress towards completion of a task.
///
/// Use a progress view to show that a task is making progress towards
/// completion. A progress view can show both determinate (percentage complete)
/// and indeterminate (progressing or not) types of progress.
///
/// Create a determinate progress view by initializing a `ProgressView` with
/// a binding to a numeric value that indicates the progress, and a `total`
/// value that represents completion of the task. By default, the progress is
/// `0.0` and the total is `1.0`.
///
/// The example below uses the state property `progress` to show progress in
/// a determinate `ProgressView`. The progress view uses its default total of
/// `1.0`, and because `progress` starts with an initial value of `0.5`,
/// the progress view begins half-complete. A "More" button below the progress
/// view allows the user to increment the progress in 5% increments:
///
/// @State private var progress = 0.5
///
/// VStack {
/// ProgressView(value: progress)
/// Button("More", action: { progress += 0.05 })
/// }
///
/// To create an indeterminate progress view, use an initializer that doesn't
/// take a progress value:
///
/// var body: some View {
/// ProgressView()
/// }
///
/// ### Styling Progress Views
///
/// You can customize the appearance and interaction of progress views by
/// creating styles that conform to the ``ProgressViewStyle`` protocol. To set a
/// specific style for all progress view instances within a view, use the
/// ``View/progressViewStyle(_:)`` modifier. In the following example, a custom
/// style adds a dark blue shadow to all progress views within the enclosing
/// ``VStack``:
///
/// struct ShadowedProgressViews: View {
/// var body: some View {
/// VStack {
/// ProgressView(value: 0.25)
/// ProgressView(value: 0.75)
/// }
/// .progressViewStyle(DarkBlueShadowProgressViewStyle())
/// }
/// }
///
/// struct DarkBlueShadowProgressViewStyle: ProgressViewStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// ProgressView(configuration)
/// .shadow(color: Color(red: 0, green: 0, blue: 0.6),
/// radius: 4.0, x: 1.0, y: 2.0)
/// }
/// }
///
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct ProgressView<Label, CurrentValueLabel> : View where Label : View, CurrentValueLabel : 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 primitive 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>.
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, tvOS 14.0, watchOS 7.0, *)
extension ProgressView where CurrentValueLabel == EmptyView {
/// Creates a progress view for showing indeterminate progress, without a
/// label.
public init() where Label == EmptyView
/// Creates a progress view for showing indeterminate progress that displays
/// a custom label.
///
/// - Parameters:
/// - label: A view builder that creates a view that describes the task
/// in progress.
public init(@ViewBuilder label: () -> Label)
/// Creates a progress view for showing indeterminate progress that
/// generates its label from a localized string.
///
/// 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
/// indeterminate progress view with a string variable, use
/// the corresponding initializer that takes a `StringProtocol` instance.
///
/// - Parameters:
/// - titleKey: The key for the progress view's localized title that
/// describes the task in progress.
public init(_ titleKey: LocalizedStringKey) where Label == Text
/// Creates a progress view for showing indeterminate progress that
/// generates its label from a string.
///
/// - Parameters:
/// - title: A string that describes the task in progress.
///
/// This initializer creates a ``Text`` view on your behalf, and treats the
/// title similar to ``Text/init(verbatim:)``. See ``Text`` for more
/// information about localizing strings. To initialize a progress view with
/// a localized string key, use the corresponding initializer that takes a
/// `LocalizedStringKey` instance.
public init<S>(_ title: S) where Label == Text, S : StringProtocol
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ProgressView {
/// Creates a progress view for showing determinate progress.
///
/// If the value is non-`nil`, but outside the range of `0.0` through
/// `total`, the progress view pins the value to those limits, rounding to
/// the nearest possible bound. A value of `nil` represents indeterminate
/// progress, in which case the progress view ignores `total`.
///
/// - Parameters:
/// - value: The completed amount of the task to this point, in a range
/// of `0.0` to `total`, or `nil` if the progress is indeterminate.
/// - total: The full amount representing the complete scope of the
/// task, meaning the task is complete if `value` equals `total`. The
/// default value is `1.0`.
public init<V>(value: V?, total: V = 1.0) where Label == EmptyView, CurrentValueLabel == EmptyView, V : BinaryFloatingPoint
/// Creates a progress view for showing determinate progress, with a
/// custom label.
///
/// If the value is non-`nil`, but outside the range of `0.0` through
/// `total`, the progress view pins the value to those limits, rounding to
/// the nearest possible bound. A value of `nil` represents indeterminate
/// progress, in which case the progress view ignores `total`.
///
/// - Parameters:
/// - value: The completed amount of the task to this point, in a range
/// of `0.0` to `total`, or `nil` if the progress is indeterminate.
/// - total: The full amount representing the complete scope of the
/// task, meaning the task is complete if `value` equals `total`. The
/// default value is `1.0`.
/// - label: A view builder that creates a view that describes the task
/// in progress.
public init<V>(value: V?, total: V = 1.0, @ViewBuilder label: () -> Label) where CurrentValueLabel == EmptyView, V : BinaryFloatingPoint
/// Creates a progress view for showing determinate progress, with a
/// custom label.
///
/// If the value is non-`nil`, but outside the range of `0.0` through
/// `total`, the progress view pins the value to those limits, rounding to
/// the nearest possible bound. A value of `nil` represents indeterminate
/// progress, in which case the progress view ignores `total`.
///
/// - Parameters:
/// - value: The completed amount of the task to this point, in a range
/// of `0.0` to `total`, or `nil` if the progress is indeterminate.
/// - total: The full amount representing the complete scope of the
/// task, meaning the task is complete if `value` equals `total`. The
/// default value is `1.0`.
/// - label: A view builder that creates a view that describes the task
/// in progress.
/// - currentValueLabel: A view builder that creates a view that
/// describes the level of completed progress of the task.
public init<V>(value: V?, total: V = 1.0, @ViewBuilder label: () -> Label, @ViewBuilder currentValueLabel: () -> CurrentValueLabel) where V : BinaryFloatingPoint
/// Creates a progress view for showing determinate progress that generates
/// its label from a localized string.
///
/// If the value is non-`nil`, but outside the range of `0.0` through
/// `total`, the progress view pins the value to those limits, rounding to
/// the nearest possible bound. A value of `nil` represents indeterminate
/// progress, in which case the progress view ignores `total`.
///
/// 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
/// determinate progress view with a string variable, use
/// the corresponding initializer that takes a `StringProtocol` instance.
///
/// - Parameters:
/// - titleKey: The key for the progress view's localized title that
/// describes the task in progress.
/// - value: The completed amount of the task to this point, in a range
/// of `0.0` to `total`, or `nil` if the progress is
/// indeterminate.
/// - total: The full amount representing the complete scope of the
/// task, meaning the task is complete if `value` equals `total`. The
/// default value is `1.0`.
public init<V>(_ titleKey: LocalizedStringKey, value: V?, total: V = 1.0) where Label == Text, CurrentValueLabel == EmptyView, V : BinaryFloatingPoint
/// Creates a progress view for showing determinate progress that generates
/// its label from a string.
///
/// If the value is non-`nil`, but outside the range of `0.0` through
/// `total`, the progress view pins the value to those limits, rounding to
/// the nearest possible bound. A value of `nil` represents indeterminate
/// progress, in which case the progress view ignores `total`.
///
/// This initializer creates a ``Text`` view on your behalf, and treats the
/// title similar to ``Text/init(verbatim:)``. See ``Text`` for more
/// information about localizing strings. To initialize a determinate
/// progress view with a localized string key, use the corresponding
/// initializer that takes a `LocalizedStringKey` instance.
///
/// - Parameters:
/// - title: The string that describes the task in progress.
/// - value: The completed amount of the task to this point, in a range
/// of `0.0` to `total`, or `nil` if the progress is
/// indeterminate.
/// - total: The full amount representing the complete scope of the
/// task, meaning the task is complete if `value` equals `total`. The
/// default value is `1.0`.
public init<S, V>(_ title: S, value: V?, total: V = 1.0) where Label == Text, CurrentValueLabel == EmptyView, S : StringProtocol, V : BinaryFloatingPoint
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ProgressView {
/// Creates a progress view for visualizing the given progress instance.
///
/// The progress view synthesizes a default label using the
/// `localizedDescription` of the given progress instance.
public init(_ progress: Progress) where Label == EmptyView, CurrentValueLabel == EmptyView
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ProgressView {
/// Creates a progress view based on a style configuration.
///
/// You can use this initializer within the
/// ``ProgressViewStyle/makeBody(configuration:)`` method of a
/// ``ProgressViewStyle`` to create an instance of the styled progress view.
/// This is useful for custom progress view styles that only modify the
/// current progress view style, as opposed to implementing a brand new
/// style.
///
/// For example, the following style adds a dark blue shadow to the progress
/// view, but otherwise preserves the progress view's current style:
///
/// struct DarkBlueShadowProgressViewStyle: ProgressViewStyle {
/// func makeBody(configuration: Configuration) -> some View {
/// ProgressView(configuration)
/// .shadow(color: Color(red: 0, green: 0, blue: 0.6),
/// radius: 4.0, x: 1.0, y: 2.0)
/// }
/// }
///
public init(_ configuration: ProgressViewStyleConfiguration) where Label == ProgressViewStyleConfiguration.Label, CurrentValueLabel == ProgressViewStyleConfiguration.CurrentValueLabel
}
/// A type that applies standard interaction behavior to all progress views
/// within a view hierarchy.
///
/// To configure the current progress view style for a view hierarchy, use the
/// ``View/progressViewStyle(_:)`` modifier.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public protocol ProgressViewStyle {
/// A view representing the body of a progress view.
associatedtype Body : View
/// 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.
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
/// A type alias for the properties of a progress view instance.
typealias Configuration = ProgressViewStyleConfiguration
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ProgressViewStyle where Self == DefaultProgressViewStyle {
/// The default progress view style in the current context of the view being
/// styled.
///
/// The default style represents the recommended style based on the original
/// initialization parameters of the progress view, and the progress view's
/// context within the view hierarchy.
public static var automatic: DefaultProgressViewStyle { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ProgressViewStyle where Self == CircularProgressViewStyle {
/// A progress view that visually indicates its progress using a circular
/// gauge.
public static var circular: CircularProgressViewStyle { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ProgressViewStyle where Self == LinearProgressViewStyle {
/// A progress view that visually indicates its progress using a horizontal
/// bar.
public static var linear: LinearProgressViewStyle { get }
}
/// The properties of a progress view instance.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct ProgressViewStyleConfiguration {
/// A type-erased label describing the task represented by the progress
/// view.
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 label that describes the current value of a progress view.
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
}
/// The completed fraction of the task represented by the progress view,
/// from `0.0` (not yet started) to `1.0` (fully complete), or `nil` if the
/// progress is indeterminate.
public let fractionCompleted: Double?
/// A view that describes the task represented by the progress view.
///
/// If `nil`, then the task is self-evident from the surrounding context,
/// and the style does not need to provide any additional description.
///
/// If the progress view is defined using a `Progress` instance, then this
/// label is equivalent to its `localizedDescription`.
public var label: ProgressViewStyleConfiguration.Label?
/// A view that describes the current value of a progress view.
///
/// If `nil`, then the value of the progress view is either self-evident
/// from the surrounding context or unknown, and the style does not need to
/// provide any additional description.
///
/// If the progress view is defined using a `Progress` instance, then this
/// label is equivalent to its `localizedAdditionalDescription`.
public var currentValueLabel: ProgressViewStyleConfiguration.CurrentValueLabel?
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct ProjectionTransform {
public var m11: CGFloat
public var m12: CGFloat
public var m13: CGFloat
public var m21: CGFloat
public var m22: CGFloat
public var m23: CGFloat
public var m31: CGFloat
public var m32: CGFloat
public var m33: CGFloat
@inlinable public init()
@inlinable public init(_ m: CGAffineTransform)
@inlinable public init(_ m: CATransform3D)
@inlinable public var isIdentity: Bool { get }
@inlinable public var isAffine: Bool { get }
public mutating func invert() -> Bool
public func inverted() -> ProjectionTransform
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ProjectionTransform : 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: ProjectionTransform, b: ProjectionTransform) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ProjectionTransform {
@inlinable public func concatenating(_ rhs: ProjectionTransform) -> ProjectionTransform
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ProjectionTransform : Sendable {
}
/// A type indicating the prominence of a view hierarchy.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public enum Prominence {
/// The standard prominence.
case standard
/// An increased prominence.
///
/// - Note: Not all views will react to increased prominence.
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: Prominence, b: Prominence) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Prominence : Equatable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Prominence : Hashable {
}
/// A radial gradient.
///
/// The gradient applies the color function as the distance from a center
/// point, scaled to fit within the defined start and end radii. The
/// gradient maps the unit space center point into the bounding rectangle of
/// each shape filled with the gradient.
///
/// When using a radial gradient as a shape style, you can also use
/// ``ShapeStyle/radialGradient(_:center:startRadius:endRadius:)``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct RadialGradient : ShapeStyle, View {
/// Creates a radial gradient from a base gradient.
public init(gradient: Gradient, center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat)
/// Creates a radial gradient from a collection of colors.
public init(colors: [Color], center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat)
/// Creates a radial gradient from a collection of color stops.
public init(stops: [Gradient.Stop], center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat)
/// 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 rectangular shape 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 Rectangle : 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 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Rectangle : 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
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Rectangle : Sendable {
}
/// The reasons to apply a redaction to data displayed on screen.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct RedactionReasons : 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
/// reasons for redaction.
public init(rawValue: Int)
/// Displayed data should appear as generic placeholders.
///
/// Text and images will be automatically masked to appear as
/// generic placeholders, though maintaining their original size and shape.
/// Use this to create a placeholder UI without directly exposing
/// placeholder data to users.
public static let placeholder: RedactionReasons
/// Displayed data should be obscured to protect private information.
///
/// Views marked with `privacySensitive` will be automatically redacted
/// using a standard styling. To apply a custom treatment the redaction
/// reason can be read out of the environment.
///
/// struct BankingContentView: View {
/// @Environment(\.redactionReasons) var redactionReasons
///
/// var body: some View {
/// if redactionReasons.contains(.privacy) {
/// FullAppCover()
/// } else {
/// AppContent()
/// }
/// }
/// }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public static let privacy: RedactionReasons
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = RedactionReasons
/// 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 = RedactionReasons
/// 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 document model definition used to serialize reference type documents to
/// and from file contents.
///
/// Conformance to `ReferenceFileDocument` is expected to be thread-safe, and
/// deserialization and serialization will be done on a background thread.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public protocol ReferenceFileDocument : ObservableObject {
/// A type of the document snapshot that can be used for serialization
/// in parallel to the main document being editable.
///
/// - See Also: `snapshot(contentType:)`
associatedtype Snapshot
/// The types the document is able to open.
static var readableContentTypes: [UTType] { get }
/// The types the document is able to save or export to.
///
/// Defaults to `readableContentTypes`.
static var writableContentTypes: [UTType] { get }
/// Initialize self by reading from the contents of a given `ReadConfiguration`.
init(configuration: Self.ReadConfiguration) throws
/// The configuration for reading document contents.
typealias ReadConfiguration = FileDocumentReadConfiguration
/// Create a snapshot of the current state of the document, which will be
/// used for serialization while `self` becomes editable by the user.
///
/// When saving a `ReferenceFileDocument`, edits to the document are blocked
/// until snapshot with a copy of any mutable references can be created.
/// Once the snapshot is created, the document becomes editable in parallel
/// to the snapshot being serialized using `write(snapshot:to:contentType:)`.
///
/// - Parameter contentType: The content type being written, for which the
/// snapshot should be created.
func snapshot(contentType: UTType) throws -> Self.Snapshot
/// Serialize the snapshot to file contents for a specified `type`.
///
/// - Parameters:
/// - snapshot: The snapshot of the document containing the state required
/// to be saved.
/// - configuration: The configuration for the current document contents.
///
/// - Returns: The destination to serialize the document contents to. The
/// value can be a newly created `FileWrapper` or an updated `FileWrapper`
/// of the one provided in `configuration`.
func fileWrapper(snapshot: Self.Snapshot, configuration: Self.WriteConfiguration) throws -> FileWrapper
/// The configurations for serializing document contents.
typealias WriteConfiguration = FileDocumentWriteConfiguration
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ReferenceFileDocument {
/// The types the document is able to save or export to.
///
/// Defaults to `readableContentTypes`.
public static var writableContentTypes: [UTType] { get }
}
/// The properties of an open reference file document.
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct ReferenceFileDocumentConfiguration<Document> where Document : ReferenceFileDocument {
/// The current document model.
///
/// Changes to the document are observed and on change dirty the document
/// state for resaving. Undo actions are not automatically registered and
/// need to be done explicitly.
public var document: Document
public var $document: ObservedObject<Document>.Wrapper { get }
/// The url of the open file document.
public var fileURL: URL?
/// Whether the document is able to be edited.
///
/// This can return `false` if the document is in viewing mode or if the
/// file is unable to be written to.
public var isEditable: Bool
}
/// An action that users can initiate to refresh model data.
///
/// The `RefreshAction` instance in an app's ``Environment`` contains
/// a handler that you can set to customize how a view
/// refreshes its data model.
/// Use the ``View/refreshable(action:)`` modifier to set this action.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct RefreshAction {
/// Trigger a refresh action.
///
/// This async function is stored in the environment
/// ``EnvironmentValues/refresh`` and can be set with the modifier
/// ``View/refreshable(action:)``. Call this function to initiate a refresh action.
public func callAsFunction() async
}
/// A shape with a rotation transform applied to it.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct RotatedShape<Content> : Shape where Content : Shape {
public var shape: Content
public var angle: Angle
public var anchor: UnitPoint
@inlinable public init(shape: Content, angle: Angle, anchor: UnitPoint = .center)
/// 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
/// An indication of how to style a shape.
///
/// SwiftUI looks at a shape's role when deciding how to apply a
/// ``ShapeStyle`` at render time. The ``Shape`` protocol provides a
/// default implementation with a value of ``ShapeRole/fill``. If you
/// create a composite shape, you can provide an override of this property
/// to return another value, if appropriate.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public static var role: ShapeRole { get }
/// The type defining the data to animate.
public typealias AnimatableData = AnimatablePair<Content.AnimatableData, AnimatablePair<Angle.AnimatableData, UnitPoint.AnimatableData>>
/// The data to animate.
public var animatableData: RotatedShape<Content>.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
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension RotatedShape : InsettableShape where Content : InsettableShape {
/// Returns `self` inset by `amount`.
@inlinable public func inset(by amount: CGFloat) -> RotatedShape<Content.InsetShape>
/// The type of the inset shape.
public typealias InsetShape = RotatedShape<Content.InsetShape>
}
/// A gesture that recognizes a rotation motion and tracks the angle of the
/// rotation.
///
/// A rotation gesture tracks how a rotation event sequence changes. To
/// recognize a rotation gesture on a view, create and configure the gesture,
/// and then add it to the view using the ``View/gesture(_:including:)``
/// modifier.
///
/// Add a rotation gesture to a ``Rectangle`` and apply a rotation effect:
///
/// struct RotationGestureView: View {
/// @State var angle = Angle(degrees: 0.0)
///
/// var rotation: some Gesture {
/// RotationGesture()
/// .onChanged { angle in
/// self.angle = angle
/// }
/// }
///
/// var body: some View {
/// Rectangle()
/// .frame(width: 200, height: 200, alignment: .center)
/// .rotationEffect(self.angle)
/// .gesture(rotation)
/// }
/// }
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct RotationGesture : Gesture {
/// The minimum delta required before the gesture succeeds.
public var minimumAngleDelta: Angle
/// Creates a rotation gesture with a minimum delta for the gesture to
/// start.
///
/// - Parameter minimumAngleDelta: The minimum delta required before the
/// gesture starts. The default value is a one-degree angle.
public init(minimumAngleDelta: Angle = .degrees(1))
/// The type of gesture representing the body of `Self`.
public typealias Body = Never
/// The type representing the gesture's value.
public typealias Value = Angle
}
/// A text field style with a system-defined rounded border.
///
/// Do not use this type directly. Instead, use ``TextFieldStyle/roundedBorder``.
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct RoundedBorderTextFieldStyle : TextFieldStyle {
public init()
}
/// Defines the shape of a rounded rectangle's corners.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum RoundedCornerStyle {
/// Quarter-circle rounded rect corners.
case circular
/// Continuous curvature rounded rect corners.
case continuous
/// 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: RoundedCornerStyle, b: RoundedCornerStyle) -> 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: Never call `finalize()` on `hasher`. 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.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension RoundedCornerStyle : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension RoundedCornerStyle : Hashable {
}
/// A rectangular shape with rounded corners, 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 RoundedRectangle : Shape {
public var cornerSize: CGSize
public var style: RoundedCornerStyle
@inlinable public init(cornerSize: CGSize, style: RoundedCornerStyle = .circular)
@inlinable public init(cornerRadius: CGFloat, style: RoundedCornerStyle = .circular)
/// 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 data to animate.
public var animatableData: CGSize.AnimatableData
/// The type defining the data to animate.
public typealias AnimatableData = CGSize.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
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension RoundedRectangle : 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 set of symbolic safe area regions.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@frozen public struct SafeAreaRegions : 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: 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.
@inlinable public init(rawValue: UInt)
/// The safe area defined by the device and containers within the
/// user interface, including elements such as top and bottom bars.
public static let container: SafeAreaRegions
/// The safe area matching the current extent of any software
/// keyboard displayed over the view content.
public static let keyboard: SafeAreaRegions
/// All safe area regions.
public static let all: SafeAreaRegions
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = SafeAreaRegions
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment