Skip to content

Instantly share code, notes, and snippets.

@navanchauhan
Created June 17, 2024 07:35
Show Gist options
  • Save navanchauhan/69c69b4d7dda76f8475318285bf3c90b to your computer and use it in GitHub Desktop.
Save navanchauhan/69c69b4d7dda76f8475318285bf3c90b to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
import Accessibility
import Combine
import CoreFoundation
import CoreGraphics
import CoreText
import CoreTransferable
import Darwin
import DeveloperToolsSupport
import Foundation
import Observation
import QuartzCore
import Symbols
import TargetConditionals
import UniformTypeIdentifiers
import _Concurrency
import _StringProcessing
import _SwiftConcurrencyShims
import os
import os.log
import os.signpost
import simd
/// A type to generate an `AXChartDescriptor` object that you use to provide
/// information about a chart and its data for an accessible experience
/// in VoiceOver or other assistive technologies.
///
/// Note that you may use the `@Environment` property wrapper inside the
/// implementation of your `AXChartDescriptorRepresentable`, in which case you
/// should implement `updateChartDescriptor`, which will be called when the
/// `Environment` changes.
///
/// For example, to provide accessibility for a view that represents a chart,
/// you would first declare your chart descriptor representable type:
///
/// struct MyChartDescriptorRepresentable: AXChartDescriptorRepresentable {
/// func makeChartDescriptor() -> AXChartDescriptor {
/// // Build and return your `AXChartDescriptor` here.
/// }
///
/// func updateChartDescriptor(_ descriptor: AXChartDescriptor) {
/// // Update your chart descriptor with any new values.
/// }
/// }
///
/// Then, provide an instance of your `AXChartDescriptorRepresentable` type to
/// your view using the `accessibilityChartDescriptor` modifier:
///
/// var body: some View {
/// MyChartView()
/// .accessibilityChartDescriptor(MyChartDescriptorRepresentable())
/// }
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public protocol AXChartDescriptorRepresentable {
/// Create the `AXChartDescriptor` for this view, and return it.
///
/// This will be called once per identity of your `View`. It will not be run
/// again unless the identity of your `View` changes. If you need to
/// update the `AXChartDescriptor` based on changes in your `View`, or in
/// the `Environment`, implement `updateChartDescriptor`.
/// This method will only be called if / when accessibility needs the
/// `AXChartDescriptor` of your view, for VoiceOver.
func makeChartDescriptor() -> AXChartDescriptor
/// Update the existing `AXChartDescriptor` for your view, based on changes
/// in your view or in the `Environment`.
///
/// This will be called as needed, when accessibility needs your
/// `AXChartDescriptor` for VoiceOver. It will only be called if the inputs
/// to your views, or a relevant part of the `Environment`, have changed.
func updateChartDescriptor(_ descriptor: AXChartDescriptor)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AXChartDescriptorRepresentable {
/// Update the existing `AXChartDescriptor` for your view, based on changes
/// in your view or in the `Environment`.
///
/// This will be called as needed, when accessibility needs your
/// `AXChartDescriptor` for VoiceOver. It will only be called if the inputs
/// to your views, or a relevant part of the `Environment`, have changed.
public func updateChartDescriptor(_ descriptor: AXChartDescriptor)
}
/// Key used to specify the identifier and label associated with
/// an entry of additional accessibility information.
///
/// Use `AccessibilityCustomContentKey` and the associated modifiers taking
/// this value as a parameter in order to simplify clearing or replacing
/// entries of additional information that are manipulated from multiple places
/// in your code.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AccessibilityCustomContentKey {
/// Create an `AccessibilityCustomContentKey` with the specified label and
/// identifier.
///
/// - Parameter label: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation".
/// - Parameter id: String used to identify the additional information entry
/// to SwiftUI. Adding an entry will replace any previous value with the
/// same identifier.
public init(_ label: Text, id: String)
/// Create an `AccessibilityCustomContentKey` with the specified label and
/// identifier.
///
/// - Parameter labelKey: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation".
/// - Parameter id: String used to identify the additional
/// information entry to SwiftUI. Adding an entry will replace any previous
/// value with the same identifier.
public init(_ labelKey: LocalizedStringKey, id: String)
/// Create an `AccessibilityCustomContentKey` with the specified label.
///
/// - Parameter labelKey: Localized text describing to the user what
/// is contained in this additional information entry. For example:
/// "orientation". This will also be used as the identifier.
public init(_ labelKey: LocalizedStringKey)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AccessibilityCustomContentKey : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AccessibilityCustomContentKey, b: AccessibilityCustomContentKey) -> Bool
}
/// 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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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 {
}
/// Textual context that assistive technologies can use to improve the
/// presentation of spoken text.
///
/// Use an `AccessibilityTextContentType` value when setting the accessibility text content
/// type of a view using the ``View/accessibilityTextContentType(_:)`` modifier.
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct AccessibilityTextContentType : Sendable {
/// A type that represents generic text that has no specific type.
public static let plain: AccessibilityTextContentType
/// A type that represents text used for input, like in the Terminal app.
public static let console: AccessibilityTextContentType
/// A type that represents text used by a file browser, like in the Finder app in macOS.
public static let fileSystem: AccessibilityTextContentType
/// A type that represents text used in a message, like in the Messages app.
public static let messaging: AccessibilityTextContentType
/// A type that represents text used in a story or poem, like in the Books app.
public static let narrative: AccessibilityTextContentType
/// A type that represents text used in source code, like in Swift Playgrounds.
public static let sourceCode: AccessibilityTextContentType
/// A type that represents text used in a grid of data, like in the Numbers app.
public static let spreadsheet: AccessibilityTextContentType
/// A type that represents text used in a document, like in the Pages app.
public static let wordProcessing: AccessibilityTextContentType
}
/// A set of accessibility traits that describe how an element behaves.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct AccessibilityTraits : SetAlgebra, Sendable {
/// The accessibility element is a button.
public static let isButton: AccessibilityTraits
/// The accessibility element is a header that divides content into
/// sections, like the title of a navigation bar.
public static let isHeader: AccessibilityTraits
/// The accessibility element is currently selected.
public static let isSelected: AccessibilityTraits
/// The accessibility element is a link.
public static let isLink: AccessibilityTraits
/// The accessibility element is a search field.
public static let isSearchField: AccessibilityTraits
/// The accessibility element is an image.
public static let isImage: AccessibilityTraits
/// The accessibility element plays its own sound when activated.
public static let playsSound: AccessibilityTraits
/// The accessibility element behaves as a keyboard key.
public static let isKeyboardKey: AccessibilityTraits
/// The accessibility element is a static text that cannot be
/// modified by the user.
public static let isStaticText: AccessibilityTraits
/// The accessibility element provides summary information when the
/// application starts.
///
/// Use this trait to characterize an accessibility element that provides
/// a summary of current conditions, settings, or state, like the
/// temperature in the Weather app.
public static let isSummaryElement: AccessibilityTraits
/// The accessibility element frequently updates its label or value.
///
/// Use this trait when you want an assistive technology to poll for
/// changes when it needs updated information. For example, you might use
/// this trait to characterize the readout of a stopwatch.
public static let updatesFrequently: AccessibilityTraits
/// The accessibility element starts a media session when it is activated.
///
/// Use this trait to silence the audio output of an assistive technology,
/// such as VoiceOver, during a media session that should not be interrupted.
/// For example, you might use this trait to silence VoiceOver speech while
/// the user is recording audio.
public static let startsMediaSession: AccessibilityTraits
/// The accessibility element allows direct touch interaction for
/// VoiceOver users.
public static let allowsDirectInteraction: AccessibilityTraits
/// The accessibility element causes an automatic page turn when VoiceOver
/// finishes reading the text within it.
public static let causesPageTurn: AccessibilityTraits
/// The accessibility element is modal.
///
/// Use this trait to restrict which accessibility elements an assistive
/// technology can navigate. When a modal accessibility element is visible,
/// sibling accessibility elements that are not modal are ignored.
public static let isModal: AccessibilityTraits
/// The accessibility element is a toggle.
@available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *)
public static let isToggle: AccessibilityTraits
/// The accessibility element is a tab bar
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public static let isTabBar: 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias ArrayLiteralElement = AccessibilityTraits
/// A type for which the conforming type provides a containment test.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Element = AccessibilityTraits
}
/// An alignment in both axes.
///
/// An `Alignment` contains a ``HorizontalAlignment`` guide and a
/// ``VerticalAlignment`` guide. Specify an alignment to direct the behavior of
/// certain layout containers and modifiers, like when you place views in a
/// ``ZStack``, or layer a view in front of or behind another view using
/// ``View/overlay(alignment:content:)`` or
/// ``View/background(alignment:content:)``, respectively. During layout,
/// SwiftUI brings the specified guides of the affected views together,
/// aligning the views.
///
/// SwiftUI provides a set of built-in alignments that represent common
/// combinations of the built-in horizontal and vertical alignment guides.
/// The blue boxes in the following diagram demonstrate the alignment named
/// by each box's label, relative to the background view:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A variety of blue
/// boxes are overlaid atop the square. Each contains the name of a built-in
/// alignment, and is aligned with the square in a way that matches the
/// alignment name. For example, the box lableled center appears at the
/// center of the square.](Alignment-1-iOS)
///
/// The following code generates the diagram above, where each blue box appears
/// in an overlay that's configured with a different alignment:
///
/// struct AlignmentGallery: View {
/// var body: some View {
/// BackgroundView()
/// .overlay(alignment: .topLeading) { box(".topLeading") }
/// .overlay(alignment: .top) { box(".top") }
/// .overlay(alignment: .topTrailing) { box(".topTrailing") }
/// .overlay(alignment: .leading) { box(".leading") }
/// .overlay(alignment: .center) { box(".center") }
/// .overlay(alignment: .trailing) { box(".trailing") }
/// .overlay(alignment: .bottomLeading) { box(".bottomLeading") }
/// .overlay(alignment: .bottom) { box(".bottom") }
/// .overlay(alignment: .bottomTrailing) { box(".bottomTrailing") }
/// .overlay(alignment: .leadingLastTextBaseline) { box(".leadingLastTextBaseline") }
/// .overlay(alignment: .trailingFirstTextBaseline) { box(".trailingFirstTextBaseline") }
/// }
///
/// private func box(_ name: String) -> some View {
/// Text(name)
/// .font(.system(.caption, design: .monospaced))
/// .padding(2)
/// .foregroundColor(.white)
/// .background(.blue.opacity(0.8), in: Rectangle())
/// }
/// }
///
/// private struct BackgroundView: View {
/// var body: some View {
/// Grid(horizontalSpacing: 0, verticalSpacing: 0) {
/// GridRow {
/// Text("Some text in an upper quadrant")
/// Color.gray.opacity(0.3)
/// }
/// GridRow {
/// Color.gray.opacity(0.3)
/// Text("More text in a lower quadrant")
/// }
/// }
/// .aspectRatio(1, contentMode: .fit)
/// .foregroundColor(.secondary)
/// .border(.gray)
/// }
/// }
///
/// To avoid crowding, the alignment diagram shows only two of the available
/// text baseline alignments. The others align as their names imply. Notice that
/// the first text baseline alignment aligns with the top-most line of text in
/// the background view, while the last text baseline aligns with the
/// bottom-most line. For more information about text baseline alignment, see
/// ``VerticalAlignment``.
///
/// In a left-to-right language like English, the leading and trailing
/// alignments appear on the left and right edges, respectively. SwiftUI
/// reverses these in right-to-left language environments. For more
/// information, see ``HorizontalAlignment``.
///
/// ### Custom alignment
///
/// You can create custom alignments --- which you typically do to make use
/// of custom horizontal or vertical guides --- by using the
/// ``init(horizontal:vertical:)`` initializer. For example, you can combine
/// a custom vertical guide called `firstThird` with the built-in horizontal
/// ``HorizontalAlignment/center`` guide, and use it to configure a ``ZStack``:
///
/// ZStack(alignment: Alignment(horizontal: .center, vertical: .firstThird)) {
/// // ...
/// }
///
/// For more information about creating custom guides, including the code
/// that creates the custom `firstThird` alignment in the example above,
/// see ``AlignmentID``.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Alignment : Equatable {
/// The alignment on the horizontal axis.
///
/// Set this value when you initialize an alignment using the
/// ``init(horizontal:vertical:)`` method. Use one of the built-in
/// ``HorizontalAlignment`` guides, like ``HorizontalAlignment/center``,
/// or a custom guide that you create.
///
/// For information about creating custom guides, see ``AlignmentID``.
public var horizontal: HorizontalAlignment
/// The alignment on the vertical axis.
///
/// Set this value when you initialize an alignment using the
/// ``init(horizontal:vertical:)`` method. Use one of the built-in
/// ``VerticalAlignment`` guides, like ``VerticalAlignment/center``,
/// or a custom guide that you create.
///
/// For information about creating custom guides, see ``AlignmentID``.
public var vertical: VerticalAlignment
/// Creates a custom alignment value with the specified horizontal
/// and vertical alignment guides.
///
/// SwiftUI provides a variety of built-in alignments that combine built-in
/// ``HorizontalAlignment`` and ``VerticalAlignment`` guides. Use this
/// initializer to create a custom alignment that makes use
/// of a custom horizontal or vertical guide, or both.
///
/// For example, you can combine a custom vertical guide called
/// `firstThird` with the built-in ``HorizontalAlignment/center``
/// guide, and use it to configure a ``ZStack``:
///
/// ZStack(alignment: Alignment(horizontal: .center, vertical: .firstThird)) {
/// // ...
/// }
///
/// For more information about creating custom guides, including the code
/// that creates the custom `firstThird` alignment in the example above,
/// see ``AlignmentID``.
///
/// - Parameters:
/// - horizontal: The alignment on the horizontal axis.
/// - vertical: The alignment on the vertical axis.
@inlinable public init(horizontal: HorizontalAlignment, vertical: VerticalAlignment)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Alignment, b: Alignment) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Alignment {
/// A guide that marks the center of the view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/center``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Center, appears at the center of the
/// square.](Alignment-center-1-iOS)
public static let center: Alignment
/// A guide that marks the leading edge of the view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/center``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Leading, appears on the left edge of the
/// square, centered vertically.](Alignment-leading-1-iOS)
public static let leading: Alignment
/// A guide that marks the trailing edge of the view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/center``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Trailing, appears on the right edge of the
/// square, centered vertically.](Alignment-trailing-1-iOS)
public static let trailing: Alignment
/// A guide that marks the top edge of the view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/top``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Top, appears on the top edge of the
/// square, centered horizontally.](Alignment-top-1-iOS)
public static let top: Alignment
/// A guide that marks the bottom edge of the view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/bottom``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, Bottom, appears on the bottom edge of the
/// square, centered horizontally.](Alignment-bottom-1-iOS)
public static let bottom: Alignment
/// A guide that marks the top and leading edges of the view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/top``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, topLeading, appears in the upper-left corner of
/// the square.](Alignment-topLeading-1-iOS)
public static let topLeading: Alignment
/// A guide that marks the top and trailing edges of the view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/top``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, topTrailing, appears in the upper-right corner of
/// the square.](Alignment-topTrailing-1-iOS)
public static let topTrailing: Alignment
/// A guide that marks the bottom and leading edges of the view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/bottom``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, bottomLeading, appears in the lower-left corner of
/// the square.](Alignment-bottomLeading-1-iOS)
public static let bottomLeading: Alignment
/// A guide that marks the bottom and trailing edges of the view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/bottom``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, bottomTrailing, appears in the lower-right corner of
/// the square.](Alignment-bottomTrailing-1-iOS)
public static let bottomTrailing: Alignment
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Alignment {
/// A guide that marks the top-most text baseline in a view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/firstTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, centerFirstTextBaseline, appears aligned with, and
/// partially overlapping, the first line of the text in the upper quadrant,
/// centered horizontally.](Alignment-centerFirstTextBaseline-1-iOS)
public static var centerFirstTextBaseline: Alignment { get }
/// A guide that marks the bottom-most text baseline in a view.
///
/// This alignment combines the ``HorizontalAlignment/center``
/// horizontal guide and the ``VerticalAlignment/lastTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, centerLastTextBaseline, appears aligned with, and
/// partially overlapping, the last line of the text in the lower quadrant,
/// centered horizontally.](Alignment-centerLastTextBaseline-1-iOS)
public static var centerLastTextBaseline: Alignment { get }
/// A guide that marks the leading edge and top-most text baseline in a
/// view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/firstTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, leadingFirstTextBaseline, appears aligned with, and
/// partially overlapping, the first line of the text in the upper quadrant.
/// The box aligns with the left edge of the
/// square.](Alignment-leadingFirstTextBaseline-1-iOS)
public static var leadingFirstTextBaseline: Alignment { get }
/// A guide that marks the leading edge and bottom-most text baseline
/// in a view.
///
/// This alignment combines the ``HorizontalAlignment/leading``
/// horizontal guide and the ``VerticalAlignment/lastTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, leadingLastTextBaseline, appears aligned with the
/// last line of the text in the lower quadrant. The box aligns with the
/// left edge of the square.](Alignment-leadingLastTextBaseline-1-iOS)
public static var leadingLastTextBaseline: Alignment { get }
/// A guide that marks the trailing edge and top-most text baseline in
/// a view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/firstTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, trailingFirstTextBaseline, appears aligned with the
/// first line of the text in the upper quadrant. The box aligns with the
/// right edge of the square.](Alignment-trailingFirstTextBaseline-1-iOS)
public static var trailingFirstTextBaseline: Alignment { get }
/// A guide that marks the trailing edge and bottom-most text baseline
/// in a view.
///
/// This alignment combines the ``HorizontalAlignment/trailing``
/// horizontal guide and the ``VerticalAlignment/lastTextBaseline``
/// vertical guide:
///
/// ![A square that's divided into four equal quadrants. The upper-
/// left quadrant contains the text, Some text in an upper quadrant. The
/// lower-right quadrant contains the text, More text in a lower quadrant.
/// In both cases, the text is split over two lines. A blue box that
/// contains the text, trailingLastTextBaseline, appears aligned with the
/// last line of the text in the lower quadrant. The box aligns with the
/// right edge of the square.](Alignment-trailingLastTextBaseline-1-iOS)
public static var trailingLastTextBaseline: Alignment { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Alignment : Sendable {
}
/// A type that you use to create custom alignment guides.
///
/// Every built-in alignment guide that ``VerticalAlignment`` or
/// ``HorizontalAlignment`` defines as a static property, like
/// ``VerticalAlignment/top`` or ``HorizontalAlignment/leading``, has a
/// unique alignment identifier type that produces the default offset for
/// that guide. To create a custom alignment guide, define your own alignment
/// identifier as a type that conforms to the `AlignmentID` protocol, and
/// implement the required ``AlignmentID/defaultValue(in:)`` method:
///
/// private struct FirstThirdAlignment: AlignmentID {
/// static func defaultValue(in context: ViewDimensions) -> CGFloat {
/// context.height / 3
/// }
/// }
///
/// When implementing the method, calculate the guide's default offset
/// from the view's origin. If it's helpful, you can use information from the
/// ``ViewDimensions`` input in the calculation. This parameter provides context
/// about the specific view that's using the guide. The above example creates an
/// identifier called `FirstThirdAlignment` and calculates a default value
/// that's one-third of the height of the aligned view.
///
/// Use the identifier's type to create a static property in an extension of
/// one of the alignment guide types, like ``VerticalAlignment``:
///
/// extension VerticalAlignment {
/// static let firstThird = VerticalAlignment(FirstThirdAlignment.self)
/// }
///
/// You can apply your custom guide like any of the built-in guides. For
/// example, you can use an ``HStack`` to align its views at one-third
/// of their height using the guide defined above:
///
/// struct StripesGroup: View {
/// var body: some View {
/// HStack(alignment: .firstThird, spacing: 1) {
/// HorizontalStripes().frame(height: 60)
/// HorizontalStripes().frame(height: 120)
/// HorizontalStripes().frame(height: 90)
/// }
/// }
/// }
///
/// struct HorizontalStripes: View {
/// var body: some View {
/// VStack(spacing: 1) {
/// ForEach(0..<3) { _ in Color.blue }
/// }
/// }
/// }
///
/// Because each set of stripes has three equal, vertically stacked
/// rectangles, they align at the bottom edge of the top rectangle. This
/// corresponds in each case to a third of the overall height, as
/// measured from the origin at the top of each set of stripes:
///
/// ![Three vertical stacks of rectangles, arranged in a row.
/// The rectangles in each stack have the same height as each other, but
/// different heights than the rectangles in the other stacks. The bottom edges
/// of the top-most rectangle in each stack are aligned with each
/// other.](AlignmentId-1-iOS)
///
/// You can also use the ``View/alignmentGuide(_:computeValue:)`` view
/// modifier to alter the behavior of your custom guide for a view, as you
/// might alter a built-in guide. For example, you can change
/// one of the stacks of stripes from the previous example to align its
/// `firstThird` guide at two thirds of the height instead:
///
/// struct StripesGroupModified: View {
/// var body: some View {
/// HStack(alignment: .firstThird, spacing: 1) {
/// HorizontalStripes().frame(height: 60)
/// HorizontalStripes().frame(height: 120)
/// HorizontalStripes().frame(height: 90)
/// .alignmentGuide(.firstThird) { context in
/// 2 * context.height / 3
/// }
/// }
/// }
/// }
///
/// The modified guide calculation causes the affected view to place the
/// bottom edge of its middle rectangle on the `firstThird` guide, which aligns
/// with the bottom edge of the top rectangle in the other two groups:
///
/// ![Three vertical stacks of rectangles, arranged in a row.
/// The rectangles in each stack have the same height as each other, but
/// different heights than the rectangles in the other stacks. The bottom edges
/// of the top-most rectangle in the first two stacks are aligned with each
/// other, and with the bottom edge of the middle rectangle in the third
/// stack.](AlignmentId-2-iOS)
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol AlignmentID {
/// Calculates a default value for the corresponding guide in the specified
/// context.
///
/// Implement this method when you create a type that conforms to the
/// ``AlignmentID`` protocol. Use the method to calculate the default
/// offset of the corresponding alignment guide. SwiftUI interprets the
/// value that you return as an offset in the coordinate space of the
/// view that's being laid out. For example, you can use the context to
/// return a value that's one-third of the height of the view:
///
/// private struct FirstThirdAlignment: AlignmentID {
/// static func defaultValue(in context: ViewDimensions) -> CGFloat {
/// context.height / 3
/// }
/// }
///
/// You can override the default value that this method returns for a
/// particular guide by adding the
/// ``View/alignmentGuide(_:computeValue:)`` view modifier to a
/// particular view.
///
/// - Parameter context: The context of the view that you apply
/// the alignment guide to. The context gives you the view's dimensions,
/// as well as the values of other alignment guides that apply to the
/// view, including both built-in and custom guides. You can use any of
/// these values, if helpful, to calculate the value for your custom
/// guide.
///
/// - Returns: The offset of the guide from the origin in the
/// view's coordinate space.
static func defaultValue(in context: ViewDimensions) -> CGFloat
}
/// A single sort key type for alignment guides in both axes.
///
/// You don't use this type directly.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AlignmentKey : 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.
public static func < (lhs: AlignmentKey, rhs: AlignmentKey) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AlignmentKey, b: AlignmentKey) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AlignmentKey : Sendable {
}
/// An opaque value derived from an anchor source and a particular view.
///
/// You can convert the anchor to a `Value` in the coordinate space of a target
/// view by using a ``GeometryProxy`` to specify the target view.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Anchor<Value> {
/// A type-erased geometry value that produces an anchored value of a given
/// type.
///
/// SwiftUI passes anchored geometry values around the view tree via
/// preference keys. It then converts them back into the local coordinate
/// space using a ``GeometryProxy`` value.
@frozen public struct Source {
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor : Sendable where Value : Sendable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Anchor : Equatable where Value : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Anchor<Value>, rhs: Anchor<Value>) -> Bool
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Anchor : Hashable where Value : Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor.Source : Sendable where Value : Sendable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor.Source {
public init<T>(_ array: [Anchor<T>.Source]) where Value == [T]
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor.Source {
public init<T>(_ anchor: Anchor<T>.Source?) where Value == T?
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Anchor.Source where Value == CGPoint {
public static func point(_ p: CGPoint) -> Anchor<Value>.Source
public static func unitPoint(_ p: UnitPoint) -> Anchor<Value>.Source
public static var topLeading: Anchor<CGPoint>.Source { get }
public static var top: Anchor<CGPoint>.Source { get }
public static var topTrailing: Anchor<CGPoint>.Source { get }
public static var leading: Anchor<CGPoint>.Source { get }
public static var center: Anchor<CGPoint>.Source { get }
public static var trailing: Anchor<CGPoint>.Source { get }
public static var bottomLeading: Anchor<CGPoint>.Source { get }
public static var bottom: Anchor<CGPoint>.Source { get }
public static var bottomTrailing: Anchor<CGPoint>.Source { get }
}
/// A geometric angle whose value you access in either radians or degrees.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Angle {
public var radians: Double
@inlinable public var degrees: Double
@inlinable public init()
@inlinable public init(radians: Double)
@inlinable public init(degrees: Double)
@inlinable public static func radians(_ radians: Double) -> Angle
@inlinable public static func degrees(_ degrees: Double) -> Angle
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Angle : Hashable, Comparable {
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
@inlinable public static func < (lhs: Angle, rhs: Angle) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Angle, b: Angle) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Angle : Animatable {
/// The data to animate.
public var animatableData: Double
@inlinable public static var zero: Angle { get }
/// The type defining the data to animate.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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, *)
@MainActor @frozen @preconcurrency public struct AngularGradient : ShapeStyle, View, Sendable {
/// Creates an angular gradient.
nonisolated public init(gradient: Gradient, center: UnitPoint, startAngle: Angle = .zero, endAngle: Angle = .zero)
/// Creates an angular gradient from a collection of colors.
nonisolated public init(colors: [Color], center: UnitPoint, startAngle: Angle, endAngle: Angle)
/// Creates an angular gradient from a collection of color stops.
nonisolated public init(stops: [Gradient.Stop], center: UnitPoint, startAngle: Angle, endAngle: Angle)
/// Creates a conic gradient that completes a full turn.
nonisolated public init(gradient: Gradient, center: UnitPoint, angle: Angle = .zero)
/// Creates a conic gradient from a collection of colors that completes
/// a full turn.
nonisolated public init(colors: [Color], center: UnitPoint, angle: Angle = .zero)
/// Creates a conic gradient from a collection of color stops that
/// completes a full turn.
nonisolated 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
/// A type that describes how to animate a property of a view.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol Animatable {
/// The type defining the data to animate.
associatedtype AnimatableData : VectorArithmetic
/// The data to animate.
var animatableData: Self.AnimatableData { get set }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animatable where Self : VectorArithmetic {
/// The data to animate.
public var animatableData: Self
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animatable where Self.AnimatableData == EmptyAnimatableData {
/// The data to animate.
public var animatableData: EmptyAnimatableData
}
/// A pair of animatable values, which is itself animatable.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AnimatablePair<First, Second> : VectorArithmetic where First : VectorArithmetic, Second : VectorArithmetic {
/// The first value.
public var first: First
/// The second value.
public var second: Second
/// Creates an animated pair with the provided values.
@inlinable public init(_ first: First, _ second: Second)
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
public static var zero: AnimatablePair<First, Second> { get }
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
public static func += (lhs: inout AnimatablePair<First, Second>, rhs: AnimatablePair<First, Second>)
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
public static func -= (lhs: inout AnimatablePair<First, Second>, rhs: AnimatablePair<First, Second>)
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
public static func + (lhs: AnimatablePair<First, Second>, rhs: AnimatablePair<First, Second>) -> AnimatablePair<First, Second>
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
public static func - (lhs: AnimatablePair<First, Second>, rhs: AnimatablePair<First, Second>) -> AnimatablePair<First, Second>
/// Multiplies each component of this value by the given value.
public mutating func scale(by rhs: Double)
/// The dot-product of this animated pair with itself.
public var magnitudeSquared: Double { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: AnimatablePair<First, Second>, b: AnimatablePair<First, Second>) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnimatablePair : Sendable where First : Sendable, Second : Sendable {
}
/// The way a view changes over time to create a smooth visual transition from
/// one state to another.
///
/// An `Animation` provides a visual transition of a view when a state value
/// changes from one value to another. The characteristics of this transition
/// vary according to the animation type. For instance, a ``linear`` animation
/// provides a mechanical feel to the animation because its speed is consistent
/// from start to finish. In contrast, an animation that uses easing, like
/// ``easeOut``, offers a more natural feel by varying the acceleration
/// of the animation.
///
/// To apply an animation to a view, add the ``View/animation(_:value:)``
/// modifier, and specify both an animation type and the value to animate. For
/// instance, the ``Circle`` view in the following code performs an
/// ``easeIn`` animation each time the state variable `scale` changes:
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scaleEffect(scale)
/// .animation(.easeIn, value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// .padding()
/// }
///
/// @Video(source: "animation-01-overview-easein.mp4", poster: "animation-01-overview-easein.png", alt: "A video that shows a circle enlarging then shrinking to its original size using an ease-in animation.")
///
/// When the value of `scale` changes, the modifier
/// ``View/scaleEffect(_:anchor:)`` resizes ``Circle`` according to the
/// new value. SwiftUI can animate the transition between sizes because
/// ``Circle`` conforms to the ``Shape`` protocol. Shapes in SwiftUI conform to
/// the ``Animatable`` protocol, which describes how to animate a property of a
/// view.
///
/// In addition to adding an animation to a view, you can also configure the
/// animation by applying animation modifiers to the animation type. For
/// example, you can:
///
/// - Delay the start of the animation by using the ``delay(_:)`` modifier.
/// - Repeat the animation by using the ``repeatCount(_:autoreverses:)`` or
/// ``repeatForever(autoreverses:)`` modifiers.
/// - Change the speed of the animation by using the ``speed(_:)`` modifier.
///
/// For example, the ``Circle`` view in the following code repeats
/// the ``easeIn`` animation three times by using the
/// ``repeatCount(_:autoreverses:)`` modifier:
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scaleEffect(scale)
/// .animation(.easeIn.repeatCount(3), value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// .padding()
/// }
/// }
///
/// @Video(source: "animation-02-overview-easein-repeat.mp4", poster: "animation-02-overview-easein-repeat.png", alt: "A video that shows a circle that repeats the ease-in animation three times: enlarging, then shrinking, then enlarging again. The animation reverses causing the circle to shrink, then enlarge, then shrink to its original size.")
///
/// A view can also perform an animation when a binding value changes. To
/// specify the animation type on a binding, call its ``Binding/animation(_:)``
/// method. For example, the view in the following code performs a
/// ``linear`` animation, moving the box truck between the leading and trailing
/// edges of the view. The truck moves each time a person clicks the ``Toggle``
/// control, which changes the value of the `$isTrailing` binding.
///
/// struct ContentView: View {
/// @State private var isTrailing = false
///
/// var body: some View {
/// VStack(alignment: isTrailing ? .trailing : .leading) {
/// Image(systemName: "box.truck")
/// .font(.system(size: 64))
///
/// Toggle("Move to trailing edge",
/// isOn: $isTrailing.animation(.linear))
/// }
/// }
/// }
///
/// @Video(source: "animation-03-overview-binding.mp4", poster: "animation-03-overview-binding.png", alt: "A video that shows a box truck that moves from the leading edge of a view to the trailing edge. The box truck then returns to the view's leading edge.")
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Animation : Equatable, Sendable {
/// Create an `Animation` that contains the specified custom animation.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public init<A>(_ base: A) where A : CustomAnimation
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Animation, rhs: Animation) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// A default animation instance.
///
/// The `default` animation is ``spring(response:dampingFraction:blendDuration:)``
/// with:
///
/// - `response` equal to `0.55`
/// - `dampingFraction` equal to `1.0`
/// - `blendDuration` equal to `0.0`
///
/// Prior to iOS 17, macOS 14, tvOS 17, and watchOS 10, the `default`
/// animation is ``easeInOut``.
///
/// The global function
/// ``withAnimation(_:_:)`` uses the default animation if you don't
/// provide one. For instance, the following code listing shows
/// an example of using the `default` animation to flip the text "Hello"
/// each time someone clicks the Animate button.
///
/// struct ContentView: View {
/// @State private var degrees = Double.zero
///
/// var body: some View {
/// VStack {
/// Spacer()
/// Text("Hello")
/// .font(.largeTitle)
/// .rotation3DEffect(.degrees(degrees), axis: (x: 0, y: 1, z: 0))
///
/// Spacer()
/// Button("Animate") {
/// withAnimation {
/// degrees = (degrees == .zero) ? 180 : .zero
/// }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-04-default-flip.mp4", poster: "animation-04-default-flip.png", alt: "A video that shows the word Hello flip horizontally so that its letters appear backwards. Then it flips in reverse so that the word Hello appears correctly.")
///
/// To use the `default` animation when adding the ``View/animation(_:value:)``
/// view modifier, specify it explicitly as the animation type. For
/// instance, the following code shows an example of the `default`
/// animation to spin the text "Hello" each time someone clicks the Animate
/// button.
///
/// struct ContentView: View {
/// @State private var degrees = Double.zero
///
/// var body: some View {
/// VStack {
/// Spacer()
/// Text("Hello")
/// .font(.largeTitle)
/// .rotationEffect(.degrees(degrees))
/// .animation(.default, value: degrees)
///
/// Spacer()
/// Button("Animate") {
/// degrees = (degrees == .zero) ? 360 : .zero
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-05-default-spin.mp4", poster: "animation-05-default-spin.png", alt: "A video that shows the word Hello spinning clockwise for one full rotation, that is, 360 degrees. Then Hello spins counterclockwise for one full rotation.")
///
/// A `default` animation instance is only equal to other `default`
/// animation instances (using `==`), and not equal to other animation
/// instances even when the animations are identical. For example, if you
/// create an animation using the ``spring(response:dampingFraction:blendDuration:)``
/// modifier with the same parameter values that `default` uses, the
/// animation isn't equal to `default`. This behavior lets you
/// differentiate between animations that you intentionally choose and
/// those that use the `default` animation.
public static let `default`: Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// Changes the duration of an animation by adjusting its speed.
///
/// Setting the speed of an animation changes the duration of the animation
/// by a factor of `speed`. A higher speed value causes a faster animation
/// sequence due to a shorter duration. For example, a one-second animation
/// with a speed of `2.0` completes in half the time (half a second).
///
/// struct ContentView: View {
/// @State private var adjustBy = 100.0
///
/// private var oneSecondAnimation: Animation {
/// .easeInOut(duration: 1.0)
/// }
///
/// var body: some View {
/// VStack(spacing: 40) {
/// HStack(alignment: .bottom) {
/// Capsule()
/// .frame(width: 50, height: 175 - adjustBy)
/// Capsule()
/// .frame(width: 50, height: 175 + adjustBy)
/// }
/// .animation(oneSecondAnimation.speed(2.0), value: adjustBy)
///
/// Button("Animate") {
/// adjustBy *= -1
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-18-speed.mp4", poster: "animation-18-speed.png", alt: "A video that shows two capsules side by side that animate using the ease-in ease-out animation. The capsule on the left is short, while the capsule on the right is tall. They animate for half a second with the short capsule growing upwards to match the height of the tall capsule. Then the tall capsule shrinks to match the original height of the short capsule. For another half second, the capsule on the left shrinks to its original height, followed by the capsule on the right growing to its original height.")
///
/// Setting `speed` to a lower number slows the animation, extending its
/// duration. For example, a one-second animation with a speed of `0.25`
/// takes four seconds to complete.
///
/// struct ContentView: View {
/// @State private var adjustBy = 100.0
///
/// private var oneSecondAnimation: Animation {
/// .easeInOut(duration: 1.0)
/// }
///
/// var body: some View {
/// VStack(spacing: 40) {
/// HStack(alignment: .bottom) {
/// Capsule()
/// .frame(width: 50, height: 175 - adjustBy)
/// Capsule()
/// .frame(width: 50, height: 175 + adjustBy)
/// }
/// .animation(oneSecondAnimation.speed(0.25), value: adjustBy)
///
/// Button("Animate") {
/// adjustBy *= -1
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-19-speed-slow.mp4", poster: "animation-19-speed-slow.png", alt: "A video that shows two capsules side by side that animate using the ease-in ease-out animation. The capsule on the left is short, while the right-side capsule is tall. They animate for four seconds with the short capsule growing upwards to match the height of the tall capsule. Then the tall capsule shrinks to match the original height of the short capsule. For another four seconds, the capsule on the left shrinks to its original height, followed by the capsule on the right growing to its original height.")
///
/// - Parameter speed: The speed at which SwiftUI performs the animation.
/// - Returns: An animation with the adjusted speed.
public func speed(_ speed: Double) -> Animation
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Animation {
/// A persistent spring animation.
///
/// When mixed with other `spring()`
/// or `interactiveSpring()` animations on the same property, each
/// animation will be replaced by their successor, preserving
/// velocity from one animation to the next. Optionally blends the
/// duration values between springs over a time period.
public static func spring(_ spring: Spring, blendDuration: TimeInterval = 0.0) -> Animation
/// An interpolating spring animation that uses a damped spring
/// model to produce values in the range of one to zero.
///
/// These vales are used to interpolate within the `[from, to]` range
/// of the animated
/// property. Preserves velocity across overlapping animations by
/// adding the effects of each animation.
public static func interpolatingSpring(_ spring: Spring, initialVelocity: Double = 0.0) -> Animation
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Animation {
/// Causes the animation to report logical completion after the specified
/// duration, if it has not already logically completed.
///
/// Note that the indicated duration will not cause the animation to
/// continue running after the base animation has fully completed.
///
/// If the animation is removed before the given duration is reached,
/// logical completion will be reported immediately.
///
/// - Parameters:
/// - duration: The duration after which the animation should report
/// that it is logically complete.
/// - Returns: An animation that reports logical completion after the
/// given duration.
public func logicallyComplete(after duration: TimeInterval) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// An interpolating spring animation that uses a damped spring
/// model to produce values in the range [0, 1] that are then used
/// to interpolate within the [from, to] range of the animated
/// property. Preserves velocity across overlapping animations by
/// adding the effects of each animation.
///
/// - Parameters:
/// - mass: The mass of the object attached to the spring.
/// - stiffness: The stiffness of the spring.
/// - damping: The spring damping value.
/// - initialVelocity: the initial velocity of the spring, as
/// a value in the range [0, 1] representing the magnitude of
/// the value being animated.
/// - Returns: a spring animation.
public static func interpolatingSpring(mass: Double = 1.0, stiffness: Double, damping: Double, initialVelocity: Double = 0.0) -> Animation
/// An interpolating spring animation that uses a damped spring
/// model to produce values in the range [0, 1] that are then used
/// to interpolate within the [from, to] range of the animated
/// property. Preserves velocity across overlapping animations by
/// adding the effects of each animation.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - bounce: How bouncy the spring should be. A value of 0 indicates
/// no bounces (a critically damped spring), positive values indicate
/// increasing amounts of bounciness up to a maximum of 1.0
/// (corresponding to undamped oscillation), and negative values
/// indicate overdamped springs with a minimum value of -1.0.
/// - initialVelocity: the initial velocity of the spring, as
/// a value in the range [0, 1] representing the magnitude of
/// the value being animated.
/// - Returns: a spring animation.
public static func interpolatingSpring(duration: TimeInterval = 0.5, bounce: Double = 0.0, initialVelocity: Double = 0.0) -> Animation
/// An interpolating spring animation that uses a damped spring
/// model to produce values in the range [0, 1] that are then used
/// to interpolate within the [from, to] range of the animated
/// property. Preserves velocity across overlapping animations by
/// adding the effects of each animation.
///
/// This uses the default parameter values.
public static var interpolatingSpring: Animation { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// Delays the start of the animation by the specified number of seconds.
///
/// Use this method to delay the start of an animation. For example, the
/// following code animates the height change of two capsules.
/// Animation of the first ``Capsule`` begins immediately. However,
/// animation of the second one doesn't begin until a half second later.
///
/// struct ContentView: View {
/// @State private var adjustBy = 100.0
///
/// var body: some View {
/// VStack(spacing: 40) {
/// HStack(alignment: .bottom) {
/// Capsule()
/// .frame(width: 50, height: 175 - adjustBy)
/// .animation(.easeInOut, value: adjustBy)
/// Capsule()
/// .frame(width: 50, height: 175 + adjustBy)
/// .animation(.easeInOut.delay(0.5), value: adjustBy)
/// }
///
/// Button("Animate") {
/// adjustBy *= -1
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-15-delay.mp4", poster: "animation-15-delay.png", alt: "A video that shows two capsules side by side that animate using the ease-in ease-out animation. The capsule on the left is short, while the capsule on the right is tall. As they animate, the short capsule grows upwards to match the height of the tall capsule. Then the tall capsule shrinks to match the original height of the short capsule. Then the capsule on the left shrinks to its original height, followed by the capsule on the right growing to its original height.")
///
/// - Parameter delay: The number of seconds to delay the start of the
/// animation.
/// - Returns: An animation with a delayed start.
public func delay(_ delay: TimeInterval) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// A persistent spring animation. When mixed with other `spring()`
/// or `interactiveSpring()` animations on the same property, each
/// animation will be replaced by their successor, preserving
/// velocity from one animation to the next. Optionally blends the
/// duration values between springs over a time period.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - bounce: How bouncy the spring should be. A value of 0 indicates
/// no bounces (a critically damped spring), positive values indicate
/// increasing amounts of bounciness up to a maximum of 1.0
/// (corresponding to undamped oscillation), and negative values
/// indicate overdamped springs with a minimum value of -1.0.
/// - blendDuration: The duration in seconds over which to
/// interpolate changes to the duration.
/// - Returns: a spring animation.
public static func spring(duration: TimeInterval = 0.5, bounce: Double = 0.0, blendDuration: Double = 0) -> Animation
/// A persistent spring animation. When mixed with other `spring()`
/// or `interactiveSpring()` animations on the same property, each
/// animation will be replaced by their successor, preserving
/// velocity from one animation to the next. Optionally blends the
/// response values between springs over a time period.
///
/// - Parameters:
/// - response: The stiffness of the spring, defined as an
/// approximate duration in seconds. A value of zero requests
/// an infinitely-stiff spring, suitable for driving
/// interactive animations.
/// - dampingFraction: The amount of drag applied to the value
/// being animated, as a fraction of an estimate of amount
/// needed to produce critical damping.
/// - blendDuration: The duration in seconds over which to
/// interpolate changes to the response value of the spring.
/// - Returns: a spring animation.
public static func spring(response: Double = 0.5, dampingFraction: Double = 0.825, blendDuration: TimeInterval = 0) -> Animation
/// A persistent spring animation. When mixed with other `spring()`
/// or `interactiveSpring()` animations on the same property, each
/// animation will be replaced by their successor, preserving
/// velocity from one animation to the next. Optionally blends the
/// response values between springs over a time period.
///
/// This uses the default parameter values.
public static var spring: Animation { get }
/// A convenience for a `spring` animation with a lower
/// `response` value, intended for driving interactive animations.
public static func interactiveSpring(response: Double = 0.15, dampingFraction: Double = 0.86, blendDuration: TimeInterval = 0.25) -> Animation
/// A convenience for a `spring` animation with a lower
/// `duration` value, intended for driving interactive animations.
///
/// This uses the default parameter values.
public static var interactiveSpring: Animation { get }
/// A convenience for a `spring` animation with a lower
/// `response` value, intended for driving interactive animations.
public static func interactiveSpring(duration: TimeInterval = 0.15, extraBounce: Double = 0.0, blendDuration: TimeInterval = 0.25) -> Animation
/// A smooth spring animation with a predefined duration and no bounce.
public static var smooth: Animation { get }
/// A smooth spring animation with a predefined duration and no bounce
/// that can be tuned.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - extraBounce: How much additional bounce should be added to the base
/// bounce of 0.
/// - blendDuration: The duration in seconds over which to interpolate
/// changes to the duration.
public static func smooth(duration: TimeInterval = 0.5, extraBounce: Double = 0.0) -> Animation
/// A spring animation with a predefined duration and small amount of
/// bounce that feels more snappy.
public static var snappy: Animation { get }
/// A spring animation with a predefined duration and small amount of
/// bounce that feels more snappy and can be tuned.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - extraBounce: How much additional bounce should be added to the base
/// bounce of 0.15.
/// - blendDuration: The duration in seconds over which to interpolate
/// changes to the duration.
public static func snappy(duration: TimeInterval = 0.5, extraBounce: Double = 0.0) -> Animation
/// A spring animation with a predefined duration and higher amount of
/// bounce.
public static var bouncy: Animation { get }
/// A spring animation with a predefined duration and higher amount of
/// bounce that can be tuned.
///
/// - Parameters:
/// - duration: The perceptual duration, which defines the pace of the
/// spring. This is approximately equal to the settling duration, but
/// for very bouncy springs, will be the duration of the period of
/// oscillation for the spring.
/// - extraBounce: How much additional bounce should be added to the base
/// bounce of 0.3.
/// - blendDuration: The duration in seconds over which to interpolate
/// changes to the duration.
public static func bouncy(duration: TimeInterval = 0.5, extraBounce: Double = 0.0) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// An animation with a specified duration that combines the behaviors of
/// in and out easing animations.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. An ease in and out animation
/// starts slowly, increasing its speed towards the halfway point, and
/// finally decreasing the speed towards the end of the animation.
///
/// Use `easeInOut(duration:)` when you want to specify the time it takes
/// for the animation to complete. Otherwise, use ``easeInOut`` to perform
/// the animation for a default length of time.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using an ease in and out animation with a duration of
/// one second.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeInOut(duration: 1.0), value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-13-easeineaseout-duration.mp4", poster: "animation-13-easeineaseout-duration.png", alt: "A video that shows a circle enlarging for one second, then shrinking for another second to its original size using an ease-in ease-out animation.")
///
/// - Parameter duration: The length of time, expressed in seconds, that
/// the animation takes to complete.
///
/// - Returns: An ease-in ease-out animation with a specified duration.
public static func easeInOut(duration: TimeInterval) -> Animation
/// An animation that combines the behaviors of in and out easing
/// animations.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. An ease in and out animation
/// starts slowly, increasing its speed towards the halfway point, and
/// finally decreasing the speed towards the end of the animation.
///
/// The `easeInOut` animation has a default duration of 0.35 seconds. To
/// specify the duration, use the ``easeInOut(duration:)`` method.
///
/// The following code shows an example of animating the size changes of a
/// ``Circle`` using an ease in and out animation.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeInOut, value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-12-easeineaseout.mp4", poster: "animation-12-easeineaseout.png", alt: "A video that shows a circle enlarging, then shrinking to its original size using an ease-in ease-out animation.")
///
/// - Returns: An ease-in ease-out animation with the default duration.
public static var easeInOut: Animation { get }
/// An animation with a specified duration that starts slowly and then
/// increases speed towards the end of the movement.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. With an ease in animation, the
/// motion starts slowly and increases its speed towards the end.
///
/// Use `easeIn(duration:)` when you want to specify the time it takes
/// for the animation to complete. Otherwise, use ``easeIn`` to perform the
/// animation for a default length of time.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using an ease in animation with a duration of one
/// second.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeIn(duration: 1.0), value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-09-easein-duration.mp4", poster: "animation-09-easein-duration.png", alt: "A video that shows a circle enlarging for one second, then shrinking for another second to its original size using an ease-in animation.")
///
/// - Parameter duration: The length of time, expressed in seconds, that
/// the animation takes to complete.
///
/// - Returns: An ease-in animation with a specified duration.
public static func easeIn(duration: TimeInterval) -> Animation
/// An animation that starts slowly and then increases speed towards the
/// end of the movement.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. With an ease in animation, the
/// motion starts slowly and increases its speed towards the end.
///
/// The `easeIn` animation has a default duration of 0.35 seconds. To
/// specify a different duration, use ``easeIn(duration:)``.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using the ease in animation.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeIn, value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-08-easein.mp4", poster: "animation-08-easein.png", alt: "A video that shows a circle enlarging, then shrinking to its original size using an ease-in animation.")
///
/// - Returns: An ease-in animation with the default duration.
public static var easeIn: Animation { get }
/// An animation with a specified duration that starts quickly and then
/// slows towards the end of the movement.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. With an ease out animation, the
/// motion starts quickly and decreases its speed towards the end.
///
/// Use `easeOut(duration:)` when you want to specify the time it takes
/// for the animation to complete. Otherwise, use ``easeOut`` to perform
/// the animation for a default length of time.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using an ease out animation with a duration of one
/// second.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeOut(duration: 1.0), value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-09-easein-duration.mp4", poster: "animation-09-easein-duration.png", alt: "A video that shows a circle enlarging for one second, then shrinking for another second to its original size using an ease-in animation.")
///
/// - Parameter duration: The length of time, expressed in seconds, that
/// the animation takes to complete.
///
/// - Returns: An ease-out animation with a specified duration.
public static func easeOut(duration: TimeInterval) -> Animation
/// An animation that starts quickly and then slows towards the end of the
/// movement.
///
/// An easing animation provides motion with a natural feel by varying
/// the acceleration and deceleration of the animation, which matches
/// how things tend to move in reality. With an ease out animation, the
/// motion starts quickly and decreases its speed towards the end.
///
/// The `easeOut` animation has a default duration of 0.35 seconds. To
/// specify a different duration, use ``easeOut(duration:)``.
///
/// The following code shows an example of animating the size changes of
/// a ``Circle`` using an ease out animation.
///
/// struct ContentView: View {
/// @State private var scale = 0.5
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scale(scale)
/// .animation(.easeOut, value: scale)
/// HStack {
/// Button("+") { scale += 0.1 }
/// Button("-") { scale -= 0.1 }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-10-easeout.mp4", poster: "animation-10-easeout.png", alt: "A video that shows a circle enlarging, then shrinking to its original size using an ease-out animation.")
///
/// - Returns: An ease-out animation with the default duration.
public static var easeOut: Animation { get }
/// An animation that moves at a constant speed during a specified
/// duration.
///
/// A linear animation provides a mechanical feel to the motion because its
/// speed is consistent from start to finish of the animation. This
/// constant speed makes a linear animation ideal for animating the
/// movement of objects where changes in the speed might feel awkward, such
/// as with an activity indicator.
///
/// Use `linear(duration:)` when you want to specify the time it takes
/// for the animation to complete. Otherwise, use ``linear`` to perform the
/// animation for a default length of time.
///
/// The following code shows an example of using linear animation with a
/// duration of two seconds to animate the movement of a circle as it moves
/// between the leading and trailing edges of the view. The color of the
/// circle also animates from red to blue as it moves across the view.
///
/// struct ContentView: View {
/// @State private var isActive = false
///
/// var body: some View {
/// VStack(alignment: isActive ? .trailing : .leading) {
/// Circle()
/// .fill(isActive ? Color.red : Color.blue)
/// .frame(width: 50, height: 50)
///
/// Button("Animate") {
/// withAnimation(.linear(duration: 2.0)) {
/// isActive.toggle()
/// }
/// }
/// .frame(maxWidth: .infinity)
/// }
/// }
/// }
///
/// @Video(source: "animation-07-linear-duration.mp4", poster: "animation-07-linear-duration.png", alt: "A video that shows a circle moving from the leading edge of the view to the trailing edge. The color of the circle also changes from red to blue as it moves across the view. Then the circle moves from the trailing edge back to the leading edge while also changing colors from blue to red.")
///
/// - Parameter duration: The length of time, expressed in seconds, that
/// the animation takes to complete.
///
/// - Returns: A linear animation with a specified duration.
public static func linear(duration: TimeInterval) -> Animation
/// An animation that moves at a constant speed.
///
/// A linear animation provides a mechanical feel to the motion because its
/// speed is consistent from start to finish of the animation. This
/// constant speed makes a linear animation ideal for animating the
/// movement of objects where changes in the speed might feel awkward, such
/// as with an activity indicator.
///
/// The following code shows an example of using linear animation to
/// animate the movement of a circle as it moves between the leading and
/// trailing edges of the view. The circle also animates its color change
/// as it moves across the view.
///
/// struct ContentView: View {
/// @State private var isActive = false
///
/// var body: some View {
/// VStack(alignment: isActive ? .trailing : .leading) {
/// Circle()
/// .fill(isActive ? Color.red : Color.blue)
/// .frame(width: 50, height: 50)
///
/// Button("Animate") {
/// withAnimation(.linear) {
/// isActive.toggle()
/// }
/// }
/// .frame(maxWidth: .infinity)
/// }
/// }
/// }
///
/// @Video(source: "animation-06-linear.mp4", poster: "animation-06-linear.png", alt: "A video that shows a circle moving from the leading edge of the view to the trailing edge. The color of the circle also changes from red to blue as it moves across the view. Then the circle moves from the trailing edge back to the leading edge while also changing colors from blue to red.")
///
/// The `linear` animation has a default duration of 0.35 seconds. To
/// specify a different duration, use ``linear(duration:)``.
///
/// - Returns: A linear animation with the default duration.
public static var linear: Animation { get }
/// An animation created from a cubic Bézier timing curve.
///
/// Use this method to create a timing curve based on the control points of
/// a cubic Bézier curve. A cubic Bézier timing curve consists of a line
/// whose starting point is `(0, 0)` and whose end point is `(1, 1)`. Two
/// additional control points, `(p1x, p1y)` and `(p2x, p2y)`, define the
/// shape of the curve.
///
/// The slope of the line defines the speed of the animation at that point
/// in time. A steep slopes causes the animation to appear to run faster,
/// while a shallower slope appears to run slower. The following
/// illustration shows a timing curve where the animation starts and
/// finishes fast, but appears slower through the middle section of the
/// animation.
///
/// ![An illustration of an XY graph that shows the path of a Bézier timing curve that an animation frame follows over time. The horizontal x-axis has a label with the text Time, and a label with the text Frame appears along the vertical y-axis. The path begins at the graph's origin, labeled as (0.0, 0.0). The path moves upwards, forming a concave down shape. At the point of inflection, the path continues upwards, forming a concave up shape. A label with the text First control point (p1x, p1y) appears above the path. Extending from the label is a dotted line pointing to the position (0.1, 0.75) on the graph. Another label with the text Second control point (p2x, p2y) appears below the path. A dotted line extends from the label to the (0.85, 0.35) position on the graph.](Animation-timingCurve-1)
///
/// The following code uses the timing curve from the previous
/// illustration to animate a ``Circle`` as its size changes.
///
/// struct ContentView: View {
/// @State private var scale = 1.0
///
/// var body: some View {
/// VStack {
/// Circle()
/// .scaleEffect(scale)
/// .animation(
/// .timingCurve(0.1, 0.75, 0.85, 0.35, duration: 2.0),
/// value: scale)
///
/// Button("Animate") {
/// if scale == 1.0 {
/// scale = 0.25
/// } else {
/// scale = 1.0
/// }
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-14-timing-curve.mp4", poster: "animation-14-timing-curve.png", alt: "A video that shows a circle shrinking then growing to its original size using a timing curve animation. The first control point of the time curve is (0.1, 0.75) and the second is (0.85, 0.35).")
///
/// - Parameters:
/// - p1x: The x-coordinate of the first control point of the cubic
/// Bézier curve.
/// - p1y: The y-coordinate of the first control point of the cubic
/// Bézier curve.
/// - p2x: The x-coordinate of the second control point of the cubic
/// Bézier curve.
/// - p2y: The y-coordinate of the second control point of the cubic
/// Bézier curve.
/// - duration: The length of time, expressed in seconds, the animation
/// takes to complete.
/// - Returns: A cubic Bézier timing curve animation.
public static func timingCurve(_ p1x: Double, _ p1y: Double, _ p2x: Double, _ p2y: Double, duration: TimeInterval = 0.35) -> Animation
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation {
/// Repeats the animation for a specific number of times.
///
/// Use this method to repeat the animation a specific number of times. For
/// example, in the following code, the animation moves a truck from one
/// edge of the view to the other edge. It repeats this animation three
/// times.
///
/// struct ContentView: View {
/// @State private var driveForward = true
///
/// private var driveAnimation: Animation {
/// .easeInOut
/// .repeatCount(3, autoreverses: true)
/// .speed(0.5)
/// }
///
/// var body: some View {
/// VStack(alignment: driveForward ? .leading : .trailing, spacing: 40) {
/// Image(systemName: "box.truck")
/// .font(.system(size: 48))
/// .animation(driveAnimation, value: driveForward)
///
/// HStack {
/// Spacer()
/// Button("Animate") {
/// driveForward.toggle()
/// }
/// Spacer()
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-16-repeat-count.mp4", poster: "animation-16-repeat-count.png", alt: "A video that shows a box truck moving from the leading edge of a view to the trailing edge, and back again before looping in the opposite direction.")
///
/// The first time the animation runs, the truck moves from the leading
/// edge to the trailing edge of the view. The second time the animation
/// runs, the truck moves from the trailing edge to the leading edge
/// because `autoreverse` is `true`. If `autoreverse` were `false`, the
/// truck would jump back to leading edge before moving to the trailing
/// edge. The third time the animation runs, the truck moves from the
/// leading to the trailing edge of the view.
///
/// - Parameters:
/// - repeatCount: The number of times that the animation repeats. Each
/// repeated sequence starts at the beginning when `autoreverse` is
/// `false`.
/// - autoreverses: A Boolean value that indicates whether the animation
/// sequence plays in reverse after playing forward. Autoreverse counts
/// towards the `repeatCount`. For instance, a `repeatCount` of one plays
/// the animation forward once, but it doesn’t play in reverse even if
/// `autoreverse` is `true`. When `autoreverse` is `true` and
/// `repeatCount` is `2`, the animation moves forward, then reverses, then
/// stops.
/// - Returns: An animation that repeats for specific number of times.
public func repeatCount(_ repeatCount: Int, autoreverses: Bool = true) -> Animation
/// Repeats the animation for the lifespan of the view containing the
/// animation.
///
/// Use this method to repeat the animation until the instance of the view
/// no longer exists, or the view’s explicit or structural identity
/// changes. For example, the following code continuously rotates a
/// gear symbol for the lifespan of the view.
///
/// struct ContentView: View {
/// @State private var rotationDegrees = 0.0
///
/// private var animation: Animation {
/// .linear
/// .speed(0.1)
/// .repeatForever(autoreverses: false)
/// }
///
/// var body: some View {
/// Image(systemName: "gear")
/// .font(.system(size: 86))
/// .rotationEffect(.degrees(rotationDegrees))
/// .onAppear {
/// withAnimation(animation) {
/// rotationDegrees = 360.0
/// }
/// }
/// }
/// }
///
/// @Video(source: "animation-17-repeat-forever.mp4", poster: "animation-17-repeat-forever.png", alt: "A video that shows a gear that continuously rotates clockwise.")
///
/// - Parameter autoreverses: A Boolean value that indicates whether the
/// animation sequence plays in reverse after playing forward.
/// - Returns: An animation that continuously repeats.
public func repeatForever(autoreverses: Bool = true) -> Animation
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Animation : Hashable {
/// Calculates the current value of the animation.
///
/// - Returns: The current value of the animation, or `nil` if the animation has finished.
public func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic
/// Calculates the current velocity of the animation.
///
/// - Returns: The current velocity of the animation, or `nil` if the the velocity isn't available.
public func velocity<V>(value: V, time: TimeInterval, context: AnimationContext<V>) -> V? where V : VectorArithmetic
/// Returns a Boolean value that indicates whether the current animation
/// should merge with a previous animation.
public func shouldMerge<V>(previous: Animation, value: V, time: TimeInterval, context: inout AnimationContext<V>) -> Bool where V : VectorArithmetic
public var base: any CustomAnimation { get }
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Animation : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
/// A textual representation of this instance.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(describing:)`
/// initializer. This initializer works with any type, and uses the custom
/// `description` property for types that conform to
/// `CustomStringConvertible`:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String { get }
/// A textual representation of this instance, suitable for debugging.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(reflecting:)`
/// initializer. This initializer works with any type, and uses the custom
/// `debugDescription` property for types that conform to
/// `CustomDebugStringConvertible`:
///
/// struct Point: CustomDebugStringConvertible {
/// let x: Int, y: Int
///
/// var debugDescription: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(reflecting: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `debugDescription` property.
public var debugDescription: String { get }
/// The custom mirror for this instance.
///
/// If this type has value semantics, the mirror should be unaffected by
/// subsequent mutations of the instance.
public var customMirror: Mirror { get }
}
/// Contextual values that a custom animation can use to manage state and
/// access a view's environment.
///
/// The system provides an `AnimationContext` to a ``CustomAnimation`` instance
/// so that the animation can store and retrieve values in an instance of
/// ``AnimationState``. To access these values, use the context's
/// ``AnimationContext/state`` property.
///
/// For more convenient access to state, create an ``AnimationStateKey`` and
/// extend `AnimationContext` to include a computed property that gets and
/// sets the ``AnimationState`` value. Then use this property instead of
/// ``AnimationContext/state`` to retrieve the state of a custom animation. For
/// example, the following code creates an animation state key named
/// `PausableState`. Then the code extends `AnimationContext` to include the
/// `pausableState` property:
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// To access the pausable state, the custom animation `PausableAnimation` uses
/// the `pausableState` property instead of the ``AnimationContext/state``
/// property:
///
/// struct PausableAnimation: CustomAnimation {
/// let base: Animation
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
///
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// if pausableState.paused != paused {
/// pauseTime = time - pauseTime
/// context.pausableState = PausableState(paused: paused, pauseTime: pauseTime)
/// }
///
/// let effectiveTime = paused ? pauseTime : time - pauseTime
/// let result = base.animate(value: value, time: effectiveTime, context: &context)
/// return result
/// }
/// }
///
/// The animation can also retrieve environment values of the view that created
/// the animation. To retrieve a view's environment value, use the context's
/// ``AnimationContext/environment`` property. For instance, the following code
/// creates a custom ``EnvironmentValues`` property named `animationPaused`, and the
/// view `PausableAnimationView` uses the property to store the paused state:
///
/// extension EnvironmentValues {
/// @Entry var animationPaused: Bool = false
/// }
///
/// struct PausableAnimationView: View {
/// @State private var paused = false
///
/// var body: some View {
/// VStack {
/// ...
/// }
/// .environment(\.animationPaused, paused)
/// }
/// }
///
/// Then the custom animation `PausableAnimation` retrieves the paused state
/// from the view's environment using the ``AnimationContext/environment``
/// property:
///
/// struct PausableAnimation: CustomAnimation {
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
/// ...
/// }
/// }
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct AnimationContext<Value> where Value : VectorArithmetic {
/// The current state of a custom animation.
///
/// An instance of ``CustomAnimation`` uses this property to read and
/// write state values as the animation runs.
///
/// An alternative to using the `state` property in a custom animation is
/// to create an ``AnimationStateKey`` type and extend ``AnimationContext``
/// with a custom property that returns the state as a custom type. For
/// example, the following code creates a state key named `PausableState`.
/// It's convenient to store state values in the key type, so the
/// `PausableState` structure includes properties for the stored state
/// values `paused` and `pauseTime`.
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// To provide access the pausable state, the following code extends
/// `AnimationContext` to include the `pausableState` property. This
/// property returns an instance of the custom `PausableState` structure
/// stored in ``AnimationContext/state``, and it can also store a new
/// `PausableState` instance in `state`.
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// Now a custom animation can use the `pausableState` property instead of
/// the ``AnimationContext/state`` property as a convenient way to read and
/// write state values as the animation runs.
///
/// struct PausableAnimation: CustomAnimation {
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// ...
/// }
/// }
///
public var state: AnimationState<Value>
/// Set this to `true` to indicate that an animation is logically complete.
///
/// This controls when AnimationCompletionCriteria.logicallyComplete
/// completion callbacks are fired. This should be set to `true` at most
/// once in the life of an animation, changing back to `false` later will be
/// ignored. If this is never set to `true`, the behavior is equivalent to
/// if this had been set to `true` just as the animation finished (by
/// returning `nil`).
public var isLogicallyComplete: Bool
/// The current environment of the view that created the custom animation.
///
/// An instance of ``CustomAnimation`` uses this property to read
/// environment values from the view that created the animation. To learn
/// more about environment values including how to define custom
/// environment values, see ``EnvironmentValues``.
public var environment: EnvironmentValues { get }
/// Creates a new context from another one with a state that you provide.
///
/// Use this method to create a new context that contains the state that
/// you provide and view environment values from the original context.
///
/// - Parameter state: The initial state for the new context.
/// - Returns: A new context that contains the specified state.
public func withState<T>(_ state: AnimationState<T>) -> AnimationContext<T> where T : VectorArithmetic
}
/// A container that stores the state for a custom animation.
///
/// An ``AnimationContext`` uses this type to store state for a
/// ``CustomAnimation``. To retrieve the stored state of a context, you can
/// use the ``AnimationContext/state`` property. However, a more convenient
/// way to access the animation state is to define an ``AnimationStateKey``
/// and extend ``AnimationContext`` with a computed property that gets
/// and sets the animation state, as shown in the following code:
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// static var defaultValue: Self { .init() }
/// }
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// When creating an ``AnimationStateKey``, it's convenient to define the
/// state values that your custom animation needs. For example, the following
/// code adds the properties `paused` and `pauseTime` to the `PausableState`
/// animation state key:
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// To access the pausable state in a `PausableAnimation`, the follow code
/// calls `pausableState` instead of using the context's
/// ``AnimationContext/state`` property. And because the animation state key
/// `PausableState` defines properties for state values, the custom animation
/// can read and write those values.
///
/// struct PausableAnimation: CustomAnimation {
/// let base: Animation
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
///
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// if pausableState.paused != paused {
/// pauseTime = time - pauseTime
/// context.pausableState = PausableState(paused: paused, pauseTime: pauseTime)
/// }
///
/// let effectiveTime = paused ? pauseTime : time - pauseTime
/// let result = base.animate(value: value, time: effectiveTime, context: &context)
/// return result
/// }
/// }
///
/// ### Storing state for secondary animations
///
/// A custom animation can also use `AnimationState` to store the state of a
/// secondary animation. For example, the following code creates an
/// ``AnimationStateKey`` that includes the property `secondaryState`, which a
/// custom animation can use to store other state:
///
/// private struct TargetState<Value: VectorArithmetic>: AnimationStateKey {
/// var timeDelta = 0.0
/// var valueDelta = Value.zero
/// var secondaryState: AnimationState<Value>? = .init()
///
/// static var defaultValue: Self { .init() }
/// }
///
/// extension AnimationContext {
/// fileprivate var targetState: TargetState<Value> {
/// get { state[TargetState<Value>.self] }
/// set { state[TargetState<Value>.self] = newValue }
/// }
/// }
///
/// The custom animation `TargetAnimation` uses `TargetState` to store state
/// data in `secondaryState` for another animation that runs as part of the
/// target animation.
///
/// struct TargetAnimation: CustomAnimation {
/// var base: Animation
/// var secondary: Animation
///
/// func animate<V: VectorArithmetic>(value: V, time: Double, context: inout AnimationContext<V>) -> V? {
/// var targetValue = value
/// if let secondaryState = context.targetState.secondaryState {
/// var secondaryContext = context
/// secondaryContext.state = secondaryState
/// let secondaryValue = value - context.targetState.valueDelta
/// let result = secondary.animate(
/// value: secondaryValue, time: time - context.targetState.timeDelta,
/// context: &secondaryContext)
/// if let result = result {
/// context.targetState.secondaryState = secondaryContext.state
/// targetValue = result + context.targetState.valueDelta
/// } else {
/// context.targetState.secondaryState = nil
/// }
/// }
/// let result = base.animate(value: targetValue, time: time, context: &context)
/// if let result = result {
/// targetValue = result
/// } else if context.targetState.secondaryState == nil {
/// return nil
/// }
/// return targetValue
/// }
///
/// func shouldMerge<V: VectorArithmetic>(previous: Animation, value: V, time: Double, context: inout AnimationContext<V>) -> Bool {
/// guard let previous = previous.base as? Self else { return false }
/// var secondaryContext = context
/// if let secondaryState = context.targetState.secondaryState {
/// secondaryContext.state = secondaryState
/// context.targetState.valueDelta = secondary.animate(
/// value: value, time: time - context.targetState.timeDelta,
/// context: &secondaryContext) ?? value
/// } else {
/// context.targetState.valueDelta = value
/// }
/// // Reset the target each time a merge occurs.
/// context.targetState.secondaryState = .init()
/// context.targetState.timeDelta = time
/// return base.shouldMerge(
/// previous: previous.base, value: value, time: time,
/// context: &context)
/// }
/// }
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct AnimationState<Value> where Value : VectorArithmetic {
/// Create an empty state container.
///
/// You don't typically create an instance of ``AnimationState`` directly.
/// Instead, the ``AnimationContext`` provides the animation state to an
/// instance of ``CustomAnimation``.
public init()
/// Accesses the state for a custom key.
///
/// Create a custom animation state value by defining a key that conforms
/// to the ``AnimationStateKey`` protocol and provide the
/// ``AnimationStateKey/defaultValue`` for the key. Also include properties
/// to read and write state values that your ``CustomAnimation`` uses. For
/// example, the following code defines a key named `PausableState` that
/// has two state values, `paused` and `pauseTime`:
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// Use that key with the subscript operator of the ``AnimationState``
/// structure to get and set a value for the key. For more convenient
/// access to the key value, extend ``AnimationContext`` with a computed
/// property that gets and sets the key's value.
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// To access the state values in a ``CustomAnimation``, call the custom
/// computed property, then read and write the state values that the
/// custom ``AnimationStateKey`` provides.
///
/// struct PausableAnimation: CustomAnimation {
/// let base: Animation
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
///
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// if pausableState.paused != paused {
/// pauseTime = time - pauseTime
/// context.pausableState = PausableState(paused: paused, pauseTime: pauseTime)
/// }
///
/// let effectiveTime = paused ? pauseTime : time - pauseTime
/// let result = base.animate(value: value, time: effectiveTime, context: &context)
/// return result
/// }
/// }
public subscript<K>(key: K.Type) -> K.Value where K : AnimationStateKey
}
/// A key for accessing animation state values.
///
/// To access animation state from an ``AnimationContext`` in a custom
/// animation, create an `AnimationStateKey`. For example, the following
/// code creates an animation state key named `PausableState` and sets the
/// value for the required ``defaultValue`` property. The code also defines
/// properties for state values that the custom animation needs when
/// calculating animation values. Keeping the state values in the animation
/// state key makes it more convenient to read and write those values in the
/// implementation of a ``CustomAnimation``.
///
/// private struct PausableState<Value: VectorArithmetic>: AnimationStateKey {
/// var paused = false
/// var pauseTime: TimeInterval = 0.0
///
/// static var defaultValue: Self { .init() }
/// }
///
/// To make accessing the value of the animation state key more convenient,
/// define a property for it by extending ``AnimationContext``:
///
/// extension AnimationContext {
/// fileprivate var pausableState: PausableState<Value> {
/// get { state[PausableState<Value>.self] }
/// set { state[PausableState<Value>.self] = newValue }
/// }
/// }
///
/// Then, you can read and write your state in an instance of `CustomAnimation`
/// using the ``AnimationContext``:
///
/// struct PausableAnimation: CustomAnimation {
/// let base: Animation
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// let paused = context.environment.animationPaused
///
/// let pausableState = context.pausableState
/// var pauseTime = pausableState.pauseTime
/// if pausableState.paused != paused {
/// pauseTime = time - pauseTime
/// context.pausableState = PausableState(paused: paused, pauseTime: pauseTime)
/// }
///
/// let effectiveTime = paused ? pauseTime : time - pauseTime
/// let result = base.animate(value: value, time: effectiveTime, context: &context)
/// return result
/// }
/// }
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public protocol AnimationStateKey {
/// The associated type representing the type of the animation state key's
/// value.
associatedtype Value
/// The default value for the animation state key.
static var defaultValue: Self.Value { get }
}
/// A 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`.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body = Never
}
/// A color gradient.
///
/// When used as a ``ShapeStyle``, this type draws a linear gradient
/// with start-point [0.5, 0] and end-point [0.5, 1].
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@frozen public struct AnyGradient : Hashable, ShapeStyle, Sendable {
/// Creates a new instance from the specified gradient.
public init(_ gradient: Gradient)
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: AnyGradient, rhs: AnyGradient) -> Bool
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension AnyGradient {
/// Returns a version of the gradient that will use a specified
/// color space for interpolating between its colors.
///
/// Rectangle().fill(.linearGradient(
/// colors: [.white, .blue]).colorSpace(.perceptual))
///
/// - Parameters:
/// - space: The color space the new gradient will use to
/// interpolate its constituent colors.
///
/// - Returns: A new gradient that interpolates its colors in the
/// specified color space.
///
public func colorSpace(_ space: Gradient.ColorSpace) -> AnyGradient
}
/// A type-erased instance of the layout protocol.
///
/// Use an `AnyLayout` instance to enable dynamically changing the
/// type of a layout container without destroying the state of the subviews.
/// For example, you can create a layout that changes between horizontal and
/// vertical layouts based on the current Dynamic Type setting:
///
/// struct DynamicLayoutExample: View {
/// @Environment(\.dynamicTypeSize) var dynamicTypeSize
///
/// var body: some View {
/// let layout = dynamicTypeSize <= .medium ?
/// AnyLayout(HStackLayout()) : AnyLayout(VStackLayout())
///
/// layout {
/// Text("First label")
/// Text("Second label")
/// }
/// }
/// }
///
/// The types that you use with `AnyLayout` must conform to the ``Layout``
/// protocol. The above example chooses between the ``HStackLayout`` and
/// ``VStackLayout`` types, which are versions of the built-in ``HStack``
/// and ``VStack`` containers that conform to the protocol. You can also
/// use custom layout types that you define.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@frozen public struct AnyLayout : Layout {
/// Creates a type-erased value that wraps the specified layout.
///
/// You can switch between type-erased layouts without losing the state
/// of the subviews.
public init<L>(_ layout: L) where L : Layout
/// Cached values associated with the layout instance.
///
/// If you create a cache for your custom layout, you can use
/// a type alias to define this type as your data storage type.
/// Alternatively, you can refer to the data storage type directly in all
/// the places where you work with the cache.
///
/// See ``makeCache(subviews:)`` for more information.
public struct Cache {
}
/// The type defining the data to animate.
public typealias AnimatableData
/// Creates and initializes a cache for a layout instance.
///
/// You can optionally use a cache to preserve calculated values across
/// calls to a layout container's methods. Many layout types don't need
/// a cache, because SwiftUI automatically reuses both the results of
/// calls into the layout and the values that the layout reads from its
/// subviews. Rely on the protocol's default implementation of this method
/// if you don't need a cache.
///
/// However you might find a cache useful when:
///
/// - The layout container repeats complex, intermediate calculations
/// across calls like ``sizeThatFits(proposal:subviews:cache:)``,
/// ``placeSubviews(in:proposal:subviews:cache:)``, and
/// ``explicitAlignment(of:in:proposal:subviews:cache:)``.
/// You might be able to improve performance by calculating values
/// once and storing them in a cache.
/// - The layout container reads many ``LayoutValueKey`` values from
/// subviews. It might be more efficient to do that once and store the
/// results in the cache, rather than rereading the subviews' values before
/// each layout call.
/// - You want to maintain working storage, like temporary Swift arrays,
/// across calls into the layout, to minimize the number of allocation
/// events.
///
/// Only implement a cache if profiling shows that it improves performance.
///
/// ### Initialize a cache
///
/// Implement the `makeCache(subviews:)` method to create a cache.
/// You can add computed values to the cache right away, using information
/// from the `subviews` input parameter, or you can do that later. The
/// methods of the ``Layout`` protocol that can access the cache
/// take the cache as an in-out parameter, which enables you to modify
/// the cache anywhere that you can read it.
///
/// You can use any storage type that makes sense for your layout
/// algorithm, but be sure that you only store data that you derive
/// from the layout and its subviews (lazily, if possible). For this to
/// work correctly, SwiftUI needs to be able to call this method to
/// recreate the cache without changing the layout result.
///
/// When you return a cache from this method, you implicitly define a type
/// for your cache. Be sure to either make the type of the `cache`
/// parameters on your other ``Layout`` protocol methods match, or use
/// a type alias to define the ``Cache`` associated type.
///
/// ### Update the cache
///
/// If the layout container or any of its subviews change, SwiftUI
/// calls the ``updateCache(_:subviews:)`` method so you can
/// modify or invalidate the contents of the
/// cache. The default implementation of that method calls the
/// `makeCache(subviews:)` method to recreate the cache, but you can
/// provide your own implementation of the update method to take an
/// incremental approach, if appropriate.
///
/// - Parameters:
/// - subviews: A collection of proxy instances that represent the
/// views that the container arranges. You can use the proxies in the
/// collection to get information about the subviews as you
/// calculate values to store in the cache.
///
/// - Returns: Storage for calculated data that you share among
/// the methods of your custom layout container.
public func makeCache(subviews: AnyLayout.Subviews) -> AnyLayout.Cache
/// Updates the layout's cache when something changes.
///
/// If your custom layout container creates a cache by implementing the
/// ``makeCache(subviews:)`` method, SwiftUI calls the update method
/// when your layout or its subviews change, giving you an opportunity
/// to modify or invalidate the contents of the cache.
/// The method's default implementation recreates the
/// cache by calling the ``makeCache(subviews:)`` method,
/// but you can provide your own implementation to take an
/// incremental approach, if appropriate.
///
/// - Parameters:
/// - cache: Storage for calculated data that you share among
/// the methods of your custom layout container.
/// - subviews: A collection of proxy instances that represent the
/// views arranged by the container. You can use the proxies in the
/// collection to get information about the subviews as you
/// calculate values to store in the cache.
public func updateCache(_ cache: inout AnyLayout.Cache, subviews: AnyLayout.Subviews)
/// Returns the preferred spacing values of the composite view.
///
/// Implement this method to provide custom spacing preferences
/// for a layout container. The value you return affects
/// the spacing around the container, but it doesn't affect how the
/// container arranges subviews relative to one another inside the
/// container.
///
/// Create a custom ``ViewSpacing`` instance for your container by
/// initializing one with default values, and then merging that with
/// spacing instances of certain subviews. For example, if you define
/// a basic vertical stack that places subviews in a column, you could
/// use the spacing preferences of the subview edges that make
/// contact with the container's edges:
///
/// extension BasicVStack {
/// func spacing(subviews: Subviews, cache: inout ()) -> ViewSpacing {
/// var spacing = ViewSpacing()
///
/// for index in subviews.indices {
/// var edges: Edge.Set = [.leading, .trailing]
/// if index == 0 { edges.formUnion(.top) }
/// if index == subviews.count - 1 { edges.formUnion(.bottom) }
/// spacing.formUnion(subviews[index].spacing, edges: edges)
/// }
///
/// return spacing
/// }
/// }
///
/// In the above example, the first and last subviews contribute to the
/// spacing above and below the container, respectively, while all subviews
/// affect the spacing on the leading and trailing edges.
///
/// If you don't implement this method, the protocol provides a default
/// implementation that merges the spacing preferences across all subviews on all edges.
///
/// - Parameters:
/// - subviews: A collection of proxy instances that represent the
/// views that the container arranges. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// how much spacing the container prefers around it.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
///
/// - Returns: A ``ViewSpacing`` instance that describes the preferred
/// spacing around the container view.
public func spacing(subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache) -> ViewSpacing
/// Returns the size of the composite view, given a proposed size
/// and the view's subviews.
///
/// Implement this method to tell your custom layout container's parent
/// view how much space the container needs for a set of subviews, given
/// a size proposal. The parent might call this method more than once
/// during a layout pass with different proposed sizes to test the
/// flexibility of the container, using proposals like:
///
/// * The ``ProposedViewSize/zero`` proposal; respond with the
/// layout's minimum size.
/// * The ``ProposedViewSize/infinity`` proposal; respond with the
/// layout's maximum size.
/// * The ``ProposedViewSize/unspecified`` proposal; respond with the
/// layout's ideal size.
///
/// The parent might also choose to test flexibility in one dimension at a
/// time. For example, a horizontal stack might propose a fixed height and
/// an infinite width, and then the same height with a zero width.
///
/// The following example calculates the size for a basic vertical stack
/// that places views in a column, with no spacing between the views:
///
/// private struct BasicVStack: Layout {
/// func sizeThatFits(
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGSize {
/// subviews.reduce(CGSize.zero) { result, subview in
/// let size = subview.sizeThatFits(.unspecified)
/// return CGSize(
/// width: max(result.width, size.width),
/// height: result.height + size.height)
/// }
/// }
///
/// // This layout also needs a placeSubviews() implementation.
/// }
///
/// The implementation asks each subview for its ideal size by calling the
/// ``LayoutSubview/sizeThatFits(_:)`` method with an
/// ``ProposedViewSize/unspecified`` proposed size.
/// It then reduces these values into a single size that represents
/// the maximum subview width and the sum of subview heights.
/// Because this example isn't flexible, it ignores its size proposal
/// input and always returns the same value for a given set of subviews.
///
/// SwiftUI views choose their own size, so the layout engine always
/// uses a value that you return from this method as the actual size of the
/// composite view. That size factors into the construction of the `bounds`
/// input to the ``placeSubviews(in:proposal:subviews:cache:)`` method.
///
/// - Parameters:
/// - proposal: A size proposal for the container. The container's parent
/// view that calls this method might call the method more than once
/// with different proposals to learn more about the container's
/// flexibility before deciding which proposal to use for placement.
/// - subviews: A collection of proxies that represent the
/// views that the container arranges. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// how much space the container needs to display them.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
///
/// - Returns: A size that indicates how much space the container
/// needs to arrange its subviews.
public func sizeThatFits(proposal: ProposedViewSize, subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache) -> CGSize
/// Assigns positions to each of the layout's subviews.
///
/// SwiftUI calls your implementation of this method to tell your
/// custom layout container to place its subviews. From this method, call
/// the ``LayoutSubview/place(at:anchor:proposal:)`` method on each
/// element in `subviews` to tell the subviews where to appear in the
/// user interface.
///
/// For example, you can create a basic vertical stack that places views
/// in a column, with views horizontally aligned on their leading edge:
///
/// struct BasicVStack: Layout {
/// func placeSubviews(
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) {
/// var point = bounds.origin
/// for subview in subviews {
/// subview.place(at: point, anchor: .topLeading, proposal: .unspecified)
/// point.y += subview.dimensions(in: .unspecified).height
/// }
/// }
///
/// // This layout also needs a sizeThatFits() implementation.
/// }
///
/// The example creates a placement point that starts at the origin of the
/// specified `bounds` input and uses that to place the first subview. It
/// then moves the point in the y dimension by the subview's height,
/// which it reads using the ``LayoutSubview/dimensions(in:)`` method.
/// This prepares the point for the next iteration of the loop. All
/// subview operations use an ``ProposedViewSize/unspecified`` size
/// proposal to indicate that subviews should use and report their ideal
/// size.
///
/// A more complex layout container might add space between subviews
/// according to their ``LayoutSubview/spacing`` preferences, or a
/// fixed space based on input configuration. For example, you can extend
/// the basic vertical stack's placement method to calculate the
/// preferred distances between adjacent subviews and store the results in
/// an array:
///
/// let spacing: [CGFloat] = subviews.indices.dropLast().map { index in
/// subviews[index].spacing.distance(
/// to: subviews[index + 1].spacing,
/// along: .vertical)
/// }
///
/// The spacing's ``ViewSpacing/distance(to:along:)`` method considers the
/// preferences of adjacent views on the edge where they meet. It returns
/// the smallest distance that satisfies both views' preferences for the
/// given edge. For example, if one view prefers at least `2` points on its
/// bottom edge, and the next view prefers at least `8` points on its top
/// edge, the distance method returns `8`, because that's the smallest
/// value that satisfies both preferences.
///
/// Update the placement calculations to use the spacing values:
///
/// var point = bounds.origin
/// for (index, subview) in subviews.enumerated() {
/// if index > 0 { point.y += spacing[index - 1] } // Add spacing.
/// subview.place(at: point, anchor: .topLeading, proposal: .unspecified)
/// point.y += subview.dimensions(in: .unspecified).height
/// }
///
/// Be sure that you use computations during placement that are consistent
/// with those in your implementation of other protocol methods for a given
/// set of inputs. For example, if you add spacing during placement,
/// make sure your implementation of
/// ``sizeThatFits(proposal:subviews:cache:)`` accounts for the extra space.
/// Similarly, if the sizing method returns different values for different
/// size proposals, make sure the placement method responds to its
/// `proposal` input in the same way.
///
/// - Parameters:
/// - bounds: The region that the container view's parent allocates to the
/// container view, specified in the parent's coordinate space.
/// Place all the container's subviews within the region.
/// The size of this region matches a size that your container
/// previously returned from a call to the
/// ``sizeThatFits(proposal:subviews:cache:)`` method.
/// - proposal: The size proposal from which the container generated the
/// size that the parent used to create the `bounds` parameter.
/// The parent might propose more than one size before calling the
/// placement method, but it always uses one of the proposals and the
/// corresponding returned size when placing the container.
/// - subviews: A collection of proxies that represent the
/// views that the container arranges. Use the proxies in the collection
/// to get information about the subviews and to tell the subviews
/// where to appear.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
public func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache)
/// Returns the position of the specified horizontal alignment guide along
/// the x axis.
///
/// Implement this method to return a value for the specified alignment
/// guide of a custom layout container. The value you return affects
/// the placement of the container as a whole, but it doesn't affect how the
/// container arranges subviews relative to one another.
///
/// You can use this method to put an alignment guide in a nonstandard
/// position. For example, you can indent the container's leading edge
/// alignment guide by 10 points:
///
/// extension BasicVStack {
/// func explicitAlignment(
/// of guide: HorizontalAlignment,
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGFloat? {
/// if guide == .leading {
/// return bounds.minX + 10
/// }
/// return nil
/// }
/// }
///
/// The above example returns `nil` for other guides to indicate that they
/// don't have an explicit value. A guide without an explicit value behaves
/// as it would for any other view. If you don't implement the
/// method, the protocol's default implementation merges the
/// subviews' guides.
///
/// - Parameters:
/// - guide: The ``HorizontalAlignment`` guide that the method calculates
/// the position of.
/// - bounds: The region that the container view's parent allocates to the
/// container view, specified in the parent's coordinate space.
/// - proposal: A proposed size for the container.
/// - subviews: A collection of proxy instances that represent the
/// views arranged by the container. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// where to place the guide.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
///
/// - Returns: The guide's position relative to the `bounds`.
/// Return `nil` to indicate that the guide doesn't have an explicit
/// value.
public func explicitAlignment(of guide: HorizontalAlignment, in bounds: CGRect, proposal: ProposedViewSize, subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache) -> CGFloat?
/// Returns the position of the specified vertical alignment guide along
/// the y axis.
///
/// Implement this method to return a value for the specified alignment
/// guide of a custom layout container. The value you return affects
/// the placement of the container as a whole, but it doesn't affect how the
/// container arranges subviews relative to one another.
///
/// You can use this method to put an alignment guide in a nonstandard
/// position. For example, you can raise the container's bottom edge
/// alignment guide by 10 points:
///
/// extension BasicVStack {
/// func explicitAlignment(
/// of guide: VerticalAlignment,
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGFloat? {
/// if guide == .bottom {
/// return bounds.minY - 10
/// }
/// return nil
/// }
/// }
///
/// The above example returns `nil` for other guides to indicate that they
/// don't have an explicit value. A guide without an explicit value behaves
/// as it would for any other view. If you don't implement the
/// method, the protocol's default implementation merges the
/// subviews' guides.
///
/// - Parameters:
/// - guide: The ``VerticalAlignment`` guide that the method calculates
/// the position of.
/// - bounds: The region that the container view's parent allocates to the
/// container view, specified in the parent's coordinate space.
/// - proposal: A proposed size for the container.
/// - subviews: A collection of proxy instances that represent the
/// views arranged by the container. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// where to place the guide.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
///
/// - Returns: The guide's position relative to the `bounds`.
/// Return `nil` to indicate that the guide doesn't have an explicit
/// value.
public func explicitAlignment(of guide: VerticalAlignment, in bounds: CGRect, proposal: ProposedViewSize, subviews: AnyLayout.Subviews, cache: inout AnyLayout.Cache) -> CGFloat?
/// The data to animate.
public var animatableData: AnyLayout.AnimatableData
}
/// The base type of type-erased locations with value-type Value.
///
/// It is annotated as `@unchecked Sendable` so that user types such as
/// `State`, and `SceneStorage` can be cleanly `Sendable`. However, it is
/// also the user types' responsibility to ensure that `get`, and `set` does
/// not access the graph concurrently (`get` should not be called while graph
/// is updating, for example).
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open class AnyLocation<Value> : AnyLocationBase, @unchecked Sendable {
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension AnyLocation : 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: AnyLocation<Value>, rhs: AnyLocation<Value>) -> Bool
}
/// The base type of all type-erased locations.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open class AnyLocationBase {
}
/// A type-erased shape value.
///
/// You can use this type to dynamically switch between shape types:
///
/// struct MyClippedView: View {
/// var isCircular: Bool
///
/// var body: some View {
/// OtherView().clipShape(isCircular ?
/// AnyShape(Circle()) : AnyShape(Capsule()))
/// }
/// }
///
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@MainActor @frozen @preconcurrency public struct AnyShape : Shape, @unchecked Sendable {
/// Create an any shape instance from a shape.
nonisolated public init<S>(_ shape: S) where S : Shape
/// Describes this shape as a path within a rectangular frame of reference.
///
/// - Parameter rect: The frame of reference for describing this shape.
///
/// - Returns: A path that describes this shape.
nonisolated public func path(in rect: CGRect) -> Path
/// Returns the size of the view that will render the shape, given
/// a proposed size.
///
/// Implement this method to tell the container of the shape how
/// much space the shape needs to render itself, given a size
/// proposal.
///
/// See ``Layout/sizeThatFits(proposal:subviews:cache:)``
/// for more details about how the layout system chooses the size of
/// views.
///
/// - Parameters:
/// - proposal: A size proposal for the container.
///
/// - Returns: A size that indicates how much space the shape needs.
nonisolated public func sizeThatFits(_ proposal: ProposedViewSize) -> CGSize
/// The type defining the data to animate.
public typealias AnimatableData
/// The data to animate.
@MainActor @preconcurrency public var animatableData: AnyShape.AnimatableData
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
@available(iOS 16.0, tvOS 16.0, watchOS 9.0, macOS 13.0, *)
public typealias Body
}
/// A type-erased ShapeStyle value.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public struct AnyShapeStyle : ShapeStyle {
/// Create an instance from `style`.
public init<S>(_ style: S) where S : ShapeStyle
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension AnyShapeStyle.Storage : @unchecked Sendable {
}
/// A type-erased transition.
///
/// - See Also: `Transition`
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AnyTransition {
/// Create an instance that type-erases `transition`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public init<T>(_ transition: T) where T : Transition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// 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 {
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 {
/// A transition from transparent to opaque on insertion, and from opaque to
/// transparent on removal.
public static let opacity: AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// Combines this transition with another, returning a new transition that
/// is the result of both transitions being applied.
public func combined(with other: AnyTransition) -> AnyTransition
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension AnyTransition {
/// 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 scales the view.
public static var scale: AnyTransition { get }
/// Returns a transition that scales the view by the specified amount.
public static func scale(scale: CGFloat, anchor: UnitPoint = .center) -> AnyTransition
}
/// 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, *)
@MainActor @frozen @preconcurrency public struct AnyView : View {
/// Create an instance that type-erases `view`.
nonisolated public init<V>(_ view: V) where V : View
nonisolated 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body = Never
}
/// 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias RawValue = Int8
/// A collection of all values of this type.
public static var allCases: [Axis] { get }
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public var rawValue: Int8 { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : CustomStringConvertible {
/// A textual representation of this instance.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(describing:)`
/// initializer. This initializer works with any type, and uses the custom
/// `description` property for types that conform to
/// `CustomStringConvertible`:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : Hashable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : RawRepresentable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis : Sendable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Axis.Set : Sendable {
}
/// The prominence of backgrounds underneath other views.
///
/// Background prominence should influence foreground styling to maintain
/// sufficient contrast against the background. For example, selected rows in
/// a `List` and `Table` can have increased prominence backgrounds with
/// accent color fills when focused; the foreground content above the background
/// should be adjusted to reflect that level of prominence.
///
/// This can be read and written for views with the
/// `EnvironmentValues.backgroundProminence` property.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct BackgroundProminence : Hashable, Sendable {
/// The standard prominence of a background
///
/// This is the default level of prominence and doesn't require any
/// adjustment to achieve satisfactory contrast with the background.
public static let standard: BackgroundProminence
/// A more prominent background that likely requires some changes to the
/// views above it.
///
/// This is the level of prominence for more highly saturated and full
/// color backgrounds, such as focused/emphasized selected list rows.
/// Typically foreground content should take on monochrome styling to
/// have greater contrast against the background.
public static let increased: BackgroundProminence
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: BackgroundProminence, b: BackgroundProminence) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// The background style in the current context.
///
/// You can also use ``ShapeStyle/background`` to construct this style.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@frozen public struct BackgroundStyle : ShapeStyle {
/// Creates a background style instance.
@inlinable public init()
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
/// A property wrapper type that can read and write a value owned by a source of
/// truth.
///
/// Use a binding to create a two-way connection between a property that stores
/// data, and a view that displays and changes the data. A binding connects a
/// property to a source of truth stored elsewhere, instead of storing data
/// directly. For example, a button that toggles between play and pause can
/// create a binding to a property of its parent view using the `Binding`
/// property wrapper.
///
/// struct PlayButton: View {
/// @Binding var isPlaying: Bool
///
/// var body: some View {
/// Button(isPlaying ? "Pause" : "Play") {
/// isPlaying.toggle()
/// }
/// }
/// }
///
/// The parent view declares a property to hold the playing state, using the
/// ``State`` property wrapper to indicate that this property is the value's
/// source of truth.
///
/// struct PlayerView: View {
/// var episode: Episode
/// @State private var isPlaying: Bool = false
///
/// var body: some View {
/// VStack {
/// Text(episode.title)
/// .foregroundStyle(isPlaying ? .primary : .secondary)
/// PlayButton(isPlaying: $isPlaying) // Pass a binding.
/// }
/// }
/// }
///
/// When `PlayerView` initializes `PlayButton`, it passes a binding of its state
/// property into the button's binding property. Applying the `$` prefix to a
/// property wrapped value returns its ``State/projectedValue``, which for a
/// state property wrapper returns a binding to the value.
///
/// Whenever the user taps the `PlayButton`, the `PlayerView` updates its
/// `isPlaying` state.
///
/// > Note: To create bindings to properties of a type that conforms to the
/// <doc://com.apple.documentation/documentation/Observation/Observable>
/// protocol, use the ``Bindable`` property wrapper. For more information,
/// see <doc:Migrating-from-the-observable-object-protocol-to-the-observable-macro>.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen @propertyWrapper @dynamicMemberLookup public struct Binding<Value> : @unchecked Sendable {
/// 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 @isolated(any) @Sendable () -> Value, set: @escaping @isolated(any) @Sendable (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 @isolated(any) @Sendable () -> Value, set: @escaping @isolated(any) @Sendable (Value, Transaction) -> Void)
/// Creates a binding with an immutable value.
///
/// Use this method to create a binding to a value that cannot change.
/// This can be useful when using a ``PreviewProvider`` to see how a view
/// represents different values.
///
/// // Example of binding to an immutable value.
/// PlayButton(isPlaying: Binding.constant(true))
///
/// - Parameter value: An immutable value.
public static func constant(_ value: Value) -> Binding<Value>
/// The underlying value referenced by the binding variable.
///
/// This property provides primary access to the value's data. However, you
/// don't access `wrappedValue` directly. Instead, you use the property
/// variable created with the ``Binding`` attribute. In the
/// following code example, the binding variable `isPlaying` returns the
/// value of `wrappedValue`:
///
/// struct PlayButton: View {
/// @Binding var isPlaying: Bool
///
/// var body: some View {
/// Button(isPlaying ? "Pause" : "Play") {
/// isPlaying.toggle()
/// }
/// }
/// }
///
/// When a mutable binding value changes, the new value is immediately
/// available. However, updates to a view displaying the value happens
/// asynchronously, so the view may not show the change immediately.
public var wrappedValue: Value { get nonmutating set }
/// A projection of the binding value that returns a binding.
///
/// Use the projected value to pass a binding value down a view hierarchy.
/// To get the `projectedValue`, prefix the property variable with `$`. For
/// example, in the following code example `PlayerView` projects a binding
/// of the state property `isPlaying` to the `PlayButton` view using
/// `$isPlaying`.
///
/// struct PlayerView: View {
/// var episode: Episode
/// @State private var isPlaying: Bool = false
///
/// var body: some View {
/// VStack {
/// Text(episode.title)
/// .foregroundStyle(isPlaying ? .primary : .secondary)
/// PlayButton(isPlaying: $isPlaying)
/// }
/// }
/// }
///
public var projectedValue: Binding<Value> { get }
/// Creates a binding from the value of another binding.
public init(projectedValue: Binding<Value>)
/// Returns a binding to the resulting value of a given key path.
///
/// - Parameter keyPath: A key path to a specific resulting value.
///
/// - Returns: A new binding.
public subscript<Subject>(dynamicMember keyPath: WritableKeyPath<Value, Subject>) -> Binding<Subject> { get }
}
@available(iOS 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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
public typealias ID = Value.ID
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Binding : Sequence where Value : MutableCollection {
/// A type representing the sequence's elements.
public typealias Element = Binding<Value.Element>
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
public typealias Iterator = IndexingIterator<Binding<Value>>
/// A collection representing a contiguous subrange of this collection's
/// elements. The subsequence shares indices with the original collection.
///
/// The default subsequence type for collections that don't define their own
/// is `Slice`.
public typealias SubSequence = Slice<Binding<Value>>
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Binding : Collection where Value : MutableCollection {
/// A type that represents a position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript
/// argument.
public typealias Index = Value.Index
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
public typealias Indices = Value.Indices
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
public var startIndex: Binding<Value>.Index { get }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.firstIndex(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
public var endIndex: Binding<Value>.Index { get }
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be nonuniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can result in an unexpected copy of the collection. To avoid
/// the unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
public var indices: Value.Indices { get }
/// Returns the position immediately after the given index.
///
/// The successor of an index must be well defined. For an index `i` into a
/// collection `c`, calling `c.index(after: i)` returns the same index every
/// time.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Binding<Value>.Index) -> Binding<Value>.Index
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
public func formIndex(after i: inout Binding<Value>.Index)
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
///
/// - Complexity: O(1)
public subscript(position: Binding<Value>.Index) -> Binding<Value>.Element { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Binding : BidirectionalCollection where Value : BidirectionalCollection, Value : MutableCollection {
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
public func index(before i: Binding<Value>.Index) -> Binding<Value>.Index
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
public func formIndex(before i: inout Binding<Value>.Index)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Binding : RandomAccessCollection where Value : MutableCollection, Value : RandomAccessCollection {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Binding {
/// Specifies a transaction for the binding.
///
/// - Parameter transaction : An instance of a ``Transaction``.
///
/// - Returns: A new binding.
public func transaction(_ transaction: Transaction) -> Binding<Value>
/// Specifies an animation to perform when the binding value changes.
///
/// - Parameter animation: An animation sequence performed when the binding
/// value changes.
///
/// - Returns: A new binding.
public func animation(_ animation: Animation? = .default) -> Binding<Value>
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Binding : DynamicProperty {
}
@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
}
/// Modes for compositing a view with overlapping content.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum BlendMode : Sendable {
case normal
case multiply
case screen
case overlay
case darken
case lighten
case colorDodge
case colorBurn
case softLight
case hardLight
case difference
case exclusion
case hue
case saturation
case color
case luminosity
case sourceAtop
case destinationOver
case destinationOut
case plusDarker
case plusLighter
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: BlendMode, b: BlendMode) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension BlendMode : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension BlendMode : Hashable {
}
/// A view type that supports immediate mode drawing.
///
/// Use a canvas to draw rich and dynamic 2D graphics inside a SwiftUI view.
/// The canvas passes a ``GraphicsContext`` to the closure that you use
/// to perform immediate mode drawing operations. The canvas also passes a
/// <doc://com.apple.documentation/documentation/CoreFoundation/CGSize> value
/// that you can use to customize what you draw. For example, you can use the
/// context's ``GraphicsContext/stroke(_:with:lineWidth:)`` command to draw
/// a ``Path`` instance:
///
/// Canvas { context, size in
/// context.stroke(
/// Path(ellipseIn: CGRect(origin: .zero, size: size)),
/// with: .color(.green),
/// lineWidth: 4)
/// }
/// .frame(width: 300, height: 200)
/// .border(Color.blue)
///
/// The example above draws the outline of an ellipse that exactly inscribes
/// a canvas with a blue border:
///
/// ![A screenshot of a canvas view that shows the green outline of an
/// ellipse inside a blue rectangle.](Canvas-1)
///
/// In addition to outlined and filled paths, you can draw images, text, and
/// complete SwiftUI views. To draw views, use the
/// ``init(opaque:colorMode:rendersAsynchronously:renderer:symbols:)`` method
/// to supply views that you can reference from inside the renderer. You can
/// also add masks, apply filters, perform transforms, control blending, and
/// more. For information about how to draw, see ``GraphicsContext``.
///
/// A canvas doesn't offer interactivity or accessibility for
/// individual elements, including for views that you pass in as symbols.
/// However, it might provide better performance for a complex drawing that
/// involves dynamic data. Use a canvas to improve performance for a drawing
/// that doesn't primarily involve text or require interactive elements.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@MainActor @preconcurrency 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.
@MainActor @preconcurrency 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.
@MainActor @preconcurrency 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.
@MainActor @preconcurrency public var isOpaque: Bool
/// The working color space and storage format of the canvas.
@MainActor @preconcurrency public var colorMode: ColorRenderingMode
/// A Boolean that indicates whether the canvas can present its contents
/// to its parent view asynchronously.
@MainActor @preconcurrency 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/CoreFoundation/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.
@MainActor @preconcurrency 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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@MainActor @preconcurrency 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, *)
@MainActor @frozen @preconcurrency public struct Capsule : Shape {
@MainActor @preconcurrency public var style: RoundedCornerStyle
/// Creates a new capsule shape.
///
/// - Parameters:
/// - style: the style of corners drawn by the shape.
@inlinable nonisolated public init(style: RoundedCornerStyle = .continuous)
/// Describes this shape as a path within a rectangular frame of reference.
///
/// - Parameter rect: The frame of reference for describing this shape.
///
/// - Returns: A path that describes this shape.
nonisolated public func path(in r: CGRect) -> Path
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
nonisolated public var layoutDirectionBehavior: LayoutDirectionBehavior { get }
/// The type defining the data to animate.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Capsule : InsettableShape {
/// Returns `self` inset by `amount`.
@MainActor @inlinable @preconcurrency public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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, *)
@MainActor @frozen @preconcurrency 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.
nonisolated public func path(in rect: CGRect) -> Path
/// Creates a new circle shape.
@inlinable nonisolated public init()
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
nonisolated public var layoutDirectionBehavior: LayoutDirectionBehavior { get }
/// The type defining the data to animate.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Circle {
/// Returns the size of the view that will render the shape, given
/// a proposed size.
///
/// Implement this method to tell the container of the shape how
/// much space the shape needs to render itself, given a size
/// proposal.
///
/// See ``Layout/sizeThatFits(proposal:subviews:cache:)``
/// for more details about how the layout system chooses the size of
/// views.
///
/// - Parameters:
/// - proposal: A size proposal for the container.
///
/// - Returns: A size that indicates how much space the shape needs.
@MainActor @preconcurrency public func sizeThatFits(_ proposal: ProposedViewSize) -> CGSize
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Circle : InsettableShape {
/// Returns `self` inset by `amount`.
@MainActor @inlinable @preconcurrency public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias InsetShape = some InsettableShape
}
/// 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
/// <doc://com.apple.documentation/design/human-interface-guidelines/sf-symbols>:
///
/// Image(systemName: "leaf.fill")
/// .foregroundStyle(Color.green)
///
/// ![A screenshot of a green leaf.](Color-1)
///
/// Because SwiftUI treats colors as ``View`` instances, you can also
/// directly add them to a view hierarchy. For example, you can layer
/// a rectangle beneath a sun image using colors defined above:
///
/// ZStack {
/// skyBlue
/// Image(systemName: "sun.max.fill")
/// .foregroundStyle(lemonYellow)
/// }
/// .frame(width: 200, height: 100)
///
/// A color used as a view expands to fill all the space it's given,
/// as defined by the frame of the enclosing ``ZStack`` in the above example:
///
/// ![A screenshot of a yellow sun on a blue background.](Color-2)
///
/// SwiftUI only resolves a color to a concrete value
/// just before using it in a given environment.
/// This enables a context-dependent appearance for
/// system defined colors, or those that you load from an Asset Catalog.
/// For example, a color can have distinct light and dark variants
/// that the system chooses from at render time.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Color : Hashable, CustomStringConvertible, Sendable {
/// Creates a color that represents the specified custom color.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public init<T>(_ color: T) where T : Hashable, T : ShapeStyle, T.Resolved == Color.Resolved
/// Evaluates this color to a resolved color given the current
/// `context`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func resolve(in environment: EnvironmentValues) -> Color.Resolved
/// A Core Graphics representation of the color, if available.
///
/// You can get a
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGColor>
/// instance from a constant SwiftUI color. This includes colors you create
/// from a Core Graphics color, from RGB or HSB components, or from constant
/// UIKit and AppKit colors.
///
/// For a dynamic color, like one you load from an Asset Catalog using
/// ``init(_:bundle:)``, or one you create from a dynamic UIKit or AppKit
/// color, this property is `nil`. To evaluate all types of colors, use the
/// `resolve(in:)` method.
@available(iOS, introduced: 14.0, deprecated: 100000.0, renamed: "resolve(in:)")
@available(macOS, introduced: 11.0, deprecated: 100000.0, renamed: "resolve(in:)")
@available(tvOS, introduced: 14.0, deprecated: 100000.0, renamed: "resolve(in:)")
@available(watchOS, introduced: 7.0, deprecated: 100000.0, renamed: "resolve(in:)")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, renamed: "resolve(in:)")
public var cgColor: CGColor? { get }
/// Hashes the essential components of the color by feeding them into the
/// given hash function.
///
/// - Parameters:
/// - hasher: The hash function to use when combining the components of
/// the color.
public func hash(into hasher: inout Hasher)
/// Indicates whether two colors are equal.
///
/// - Parameters:
/// - lhs: The first color to compare.
/// - rhs: The second color to compare.
/// - Returns: A Boolean that's set to `true` if the two colors are equal.
public static func == (lhs: Color, rhs: Color) -> Bool
/// A textual representation of the color.
///
/// Use this method to get a string that represents the color.
/// The <doc://com.apple.documentation/documentation/Swift/print(_:separator:terminator:)>
/// function uses this property to get a string representing an instance:
///
/// print(Color.red)
/// // Prints "red"
public var description: String { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color : ShapeStyle {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color {
/// A 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 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color {
/// A concrete color value.
///
/// `Color.Resolved` is a set of RGBA values that represent a color that can
/// be shown. The values are in Linear sRGB color space, extended range. This is
/// a low-level type, most colors are represented by the `Color` type.
///
/// - SeeAlso: `Color`
@frozen public struct Resolved : Hashable {
/// The amount of red in the color in the sRGB linear color space.
public var linearRed: Float
/// The amount of green in the color in the sRGB linear color space.
public var linearGreen: Float
/// The amount of blue in the color in the sRGB linear color space.
public var linearBlue: Float
/// The degree of opacity in the color, given in the range `0` to `1`.
///
/// A value of `0` means 100% transparency, while a value of `1` means
/// 100% opacity.
public var opacity: Float
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Color.Resolved, b: Color.Resolved) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// Creates a constant color with the values specified by the resolved
/// color.
public init(_ resolved: Color.Resolved)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color {
/// A profile that specifies how to interpret a color value for display.
public enum RGBColorSpace : Sendable {
/// The extended red, green, blue (sRGB) color space.
///
/// For information about the sRGB colorimetry and nonlinear
/// transform function, see the IEC 61966-2-1 specification.
///
/// Standard sRGB color spaces clamp the red, green, and blue
/// components of a color to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so you can use component values
/// outside that range.
case sRGB
/// The extended sRGB color space with a linear transfer function.
///
/// This color space has the same colorimetry as ``sRGB``, but uses
/// a linear transfer function.
///
/// Standard sRGB color spaces clamp the red, green, and blue
/// components of a color to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so you can use component values
/// outside that range.
case sRGBLinear
/// The Display P3 color space.
///
/// This color space uses the Digital Cinema Initiatives - Protocol 3
/// (DCI-P3) primary colors, a D65 white point, and the ``sRGB``
/// transfer function.
case displayP3
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Color.RGBColorSpace, b: Color.RGBColorSpace) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// Creates a constant color from red, green, and blue component values.
///
/// This initializer creates a constant color that doesn't change based
/// on context. For example, it doesn't have distinct light and dark
/// appearances, unlike various system-defined colors, or a color that
/// you load from an Asset Catalog with ``init(_:bundle:)``.
///
/// A standard sRGB color space clamps each color component — `red`,
/// `green`, and `blue` — to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so
/// you can use component values outside that range. This makes it
/// possible to create colors using the ``RGBColorSpace/sRGB`` or
/// ``RGBColorSpace/sRGBLinear`` color space that make full use of the wider
/// gamut of a diplay that supports ``RGBColorSpace/displayP3``.
///
/// - Parameters:
/// - colorSpace: The profile that specifies how to interpret the color
/// for display. The default is ``RGBColorSpace/sRGB``.
/// - red: The amount of red in the color.
/// - green: The amount of green in the color.
/// - blue: The amount of blue in the color.
/// - opacity: An optional degree of opacity, given in the range `0` to
/// `1`. A value of `0` means 100% transparency, while a value of `1`
/// means 100% opacity. The default is `1`.
public init(_ colorSpace: Color.RGBColorSpace = .sRGB, red: Double, green: Double, blue: Double, opacity: Double = 1)
/// Creates a constant grayscale color.
///
/// This initializer creates a constant color that doesn't change based
/// on context. For example, it doesn't have distinct light and dark
/// appearances, unlike various system-defined colors, or a color that
/// you load from an Asset Catalog with ``init(_:bundle:)``.
///
/// A standard sRGB color space clamps the `white` component
/// to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so
/// you can use component values outside that range. This makes it
/// possible to create colors using the ``RGBColorSpace/sRGB`` or
/// ``RGBColorSpace/sRGBLinear`` color space that make full use of the wider
/// gamut of a diplay that supports ``RGBColorSpace/displayP3``.
///
/// - Parameters:
/// - colorSpace: The profile that specifies how to interpret the color
/// for display. The default is ``RGBColorSpace/sRGB``.
/// - white: A value that indicates how white
/// the color is, with higher values closer to 100% white, and lower
/// values closer to 100% black.
/// - opacity: An optional degree of opacity, given in the range `0` to
/// `1`. A value of `0` means 100% transparency, while a value of `1`
/// means 100% opacity. The default is `1`.
public init(_ colorSpace: Color.RGBColorSpace = .sRGB, white: Double, opacity: Double = 1)
/// Creates a constant color from hue, saturation, and brightness values.
///
/// This initializer creates a constant color that doesn't change based
/// on context. For example, it doesn't have distinct light and dark
/// appearances, unlike various system-defined colors, or a color that
/// you load from an Asset Catalog with ``init(_:bundle:)``.
///
/// - Parameters:
/// - hue: A value in the range `0` to `1` that maps to an angle
/// from 0° to 360° to represent a shade on the color wheel.
/// - saturation: A value in the range `0` to `1` that indicates
/// how strongly the hue affects the color. A value of `0` removes the
/// effect of the hue, resulting in gray. As the value increases,
/// the hue becomes more prominent.
/// - brightness: A value in the range `0` to `1` that indicates
/// how bright a color is. A value of `0` results in black, regardless
/// of the other components. The color lightens as you increase this
/// component.
/// - opacity: An optional degree of opacity, given in the range `0` to
/// `1`. A value of `0` means 100% transparency, while a value of `1`
/// means 100% opacity. The default is `1`.
public init(hue: Double, saturation: Double, brightness: Double, opacity: Double = 1)
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Color {
/// Returns the standard gradient for the color `self`.
///
/// For example, filling a rectangle with a gradient derived from
/// the standard blue color:
///
/// Rectangle().fill(.blue.gradient)
///
public var gradient: AnyGradient { get }
}
@available(iOS 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 : 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")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use Color(cgColor:) when converting a CGColor, or create a standard Color directly")
extension Color {
/// Creates a color from a Core Graphics color.
///
/// - Parameter color: A
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGColor> instance
/// from which to create a color.
public init(_ cgColor: CGColor)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Color {
/// Creates a color from a Core Graphics color.
///
/// - Parameter color: A
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGColor> instance
/// from which to create a color.
public init(cgColor: CGColor)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color {
/// Creates a color from a color set that you indicate by name.
///
/// Use this initializer to load a color from a color set stored in an
/// Asset Catalog. The system determines which color within the set to use
/// based on the environment at render time. For example, you
/// can provide light and dark versions for background and foreground
/// colors:
///
/// ![A screenshot of color sets for foreground and background colors,
/// each with light and dark variants,
/// in an Asset Catalog.](Color-init-1)
///
/// You can then instantiate colors by referencing the names of the assets:
///
/// struct Hello: View {
/// var body: some View {
/// ZStack {
/// Color("background")
/// Text("Hello, world!")
/// .foregroundStyle(Color("foreground"))
/// }
/// .frame(width: 200, height: 100)
/// }
/// }
///
/// SwiftUI renders the appropriate colors for each appearance:
///
/// ![A side by side comparison of light and dark appearance screenshots
/// of the same content. The light variant shows dark text on a light
/// background, while the dark variant shows light text on a dark
/// background.](Color-init-2)
///
/// - Parameters:
/// - name: The name of the color resource to look up.
/// - bundle: The bundle in which to search for the color resource.
/// If you don't indicate a bundle, the initializer looks in your app's
/// main bundle by default.
public init(_ name: String, bundle: Bundle? = nil)
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color {
/// Initialize a `Color` with a color resource.
public init(_ resource: ColorResource)
}
@available(iOS 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
/// Returns a version of self mixed with `rhs` by the amount specified
/// by `fraction`.
///
/// - Parameters:
/// - rhs: The color to mix `self` with.
/// - fraction: The amount of blending, `0.5` means `self` is mixed in
/// equal parts with `rhs`.
/// - colorSpace: The color space used to mix the colors.
/// - Returns: A new `Color` based on `self` and `rhs`.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public func mix(with rhs: Color, by fraction: Double, in colorSpace: Gradient.ColorSpace = .perceptual) -> Color
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved : ShapeStyle {
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved : CustomStringConvertible {
/// A textual representation of this instance.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(describing:)`
/// initializer. This initializer works with any type, and uses the custom
/// `description` property for types that conform to
/// `CustomStringConvertible`:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved : Animatable {
/// The type defining the data to animate.
public typealias AnimatableData = AnimatablePair<Float, AnimatablePair<Float, AnimatablePair<Float, Float>>>
/// The data to animate.
public var animatableData: Color.Resolved.AnimatableData
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved {
/// Creates a resolved color from red, green, and blue component values.
///
/// A standard sRGB color space clamps each color component — `red`,
/// `green`, and `blue` — to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so
/// you can use component values outside that range. This makes it
/// possible to create colors using the ``RGBColorSpace/sRGB`` or
/// ``RGBColorSpace/sRGBLinear`` color space that make full use of the
/// wider gamut of a diplay that supports ``RGBColorSpace/displayP3``.
///
/// - Parameters:
/// - colorSpace: The profile that specifies how to interpret the
/// color for display. The default is ``RGBColorSpace/sRGB``.
/// - red: The amount of red in the color.
/// - green: The amount of green in the color.
/// - blue: The amount of blue in the color.
/// - opacity: An optional degree of opacity, given in the range `0`
/// to `1`. A value of `0` means 100% transparency, while a value of
/// `1` means 100% opacity. The default is `1`.
public init(colorSpace: Color.RGBColorSpace = .sRGB, red: Float, green: Float, blue: Float, opacity: Float = 1)
/// The amount of red in the color in the sRGB color space.
public var red: Float
/// The amount of green in the color in the sRGB color space.
public var green: Float
/// The amount of blue in the color in the sRGB color space.
public var blue: Float
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved : Codable {
/// Encodes this value into the given encoder.
///
/// If the value fails to encode anything, `encoder` will encode an empty
/// keyed container in its place.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: any Encoder) throws
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: any Decoder) throws
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Color.Resolved {
/// A Core Graphics representation of the color.
///
/// You can get a
/// <doc://com.apple.documentation/documentation/CoreGraphics/CGColor>
/// instance from a resolved color.
public var cgColor: CGColor { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color.RGBColorSpace : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color.RGBColorSpace : Hashable {
}
/// A matrix to use in an RGBA color transformation.
///
/// The matrix has five columns, each with a red, green, blue, and alpha
/// component. You can use the matrix for tasks like creating a color
/// transformation ``GraphicsContext/Filter`` for a ``GraphicsContext`` using
/// the ``GraphicsContext/Filter/colorMatrix(_:)`` method.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@frozen public struct ColorMatrix : Equatable {
public var r1: Float
public var r2: Float
public var r3: Float
public var r4: Float
public var r5: Float
public var g1: Float
public var g2: Float
public var g3: Float
public var g4: Float
public var g5: Float
public var b1: Float
public var b2: Float
public var b3: Float
public var b4: Float
public var b5: Float
public var a1: Float
public var a2: Float
public var a3: Float
public var a4: Float
public var a5: Float
/// Creates the identity matrix.
@inlinable public init()
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ColorMatrix, b: ColorMatrix) -> Bool
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ColorMatrix : Sendable {
}
/// The set of possible working color spaces for color-compositing operations.
///
/// Each color space guarantees the preservation of a particular range of color
/// values.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum ColorRenderingMode : Sendable {
/// The non-linear sRGB working color space.
///
/// Color component values outside the range `[0, 1]` produce undefined
/// results. This color space is gamma corrected.
case nonLinear
/// The linear sRGB working color space.
///
/// Color component values outside the range `[0, 1]` produce undefined
/// results. This color space isn't gamma corrected.
case linear
/// The extended linear sRGB working color space.
///
/// Color component values outside the range `[0, 1]` are preserved.
/// This color space isn't gamma corrected.
case extendedLinear
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ColorRenderingMode, b: ColorRenderingMode) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorRenderingMode : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorRenderingMode : Hashable {
}
/// The possible color schemes, corresponding to the light and dark appearances.
///
/// You receive a color scheme value when you read the
/// ``EnvironmentValues/colorScheme`` environment value. The value tells you if
/// a light or dark appearance currently applies to the view. SwiftUI updates
/// the value whenever the appearance changes, and redraws views that
/// depend on the value. For example, the following ``Text`` view automatically
/// updates when the user enables Dark Mode:
///
/// @Environment(\.colorScheme) private var colorScheme
///
/// var body: some View {
/// Text(colorScheme == .dark ? "Dark" : "Light")
/// }
///
/// Set a preferred appearance for a particular view hierarchy to override
/// the user's Dark Mode setting using the ``View/preferredColorScheme(_:)``
/// view modifier.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum ColorScheme : CaseIterable, Sendable {
/// The color scheme that corresponds to a light appearance.
case light
/// The color scheme that corresponds to a dark appearance.
case dark
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ColorScheme, b: ColorScheme) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias AllCases = [ColorScheme]
/// A collection of all values of this type.
public static var allCases: [ColorScheme] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorScheme : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorScheme : Hashable {
}
/// The contrast between the app's foreground and background colors.
///
/// You receive a contrast value when you read the
/// ``EnvironmentValues/colorSchemeContrast`` environment value. The value
/// tells you if a standard or increased contrast currently applies to the view.
/// SwiftUI updates the value whenever the contrast changes, and redraws
/// views that depend on the value. For example, the following ``Text`` view
/// automatically updates when the user enables increased contrast:
///
/// @Environment(\.colorSchemeContrast) private var colorSchemeContrast
///
/// var body: some View {
/// Text(colorSchemeContrast == .standard ? "Standard" : "Increased")
/// }
///
/// The user sets the contrast by selecting the Increase Contrast option in
/// Accessibility > Display in System Preferences on macOS, or
/// Accessibility > Display & Text Size in the Settings app on iOS.
/// Your app can't override the user's choice. For
/// information about using color and contrast in your app, see
/// <doc://com.apple.documentation/design/human-interface-guidelines/accessibility#Color-and-effects>
/// in the Human Interface Guidelines.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum ColorSchemeContrast : CaseIterable, Sendable {
/// SwiftUI displays views with standard contrast between the app's
/// foreground and background colors.
case standard
/// SwiftUI displays views with increased contrast between the app's
/// foreground and background colors.
case increased
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ColorSchemeContrast, b: ColorSchemeContrast) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias AllCases = [ColorSchemeContrast]
/// A collection of all values of this type.
public static var allCases: [ColorSchemeContrast] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorSchemeContrast : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ColorSchemeContrast : Hashable {
}
/// A 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, *)
@MainActor @frozen @preconcurrency 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.
nonisolated public func path(in rect: CGRect) -> Path
@inlinable nonisolated public init()
/// The type defining the data to animate.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
public typealias Body
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ContainerRelativeShape : InsettableShape {
/// Returns `self` inset by `amount`.
@MainActor @inlinable @preconcurrency public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
public typealias InsetShape = some InsettableShape
}
/// Constants that define how a view's content fills the available space.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public enum ContentMode : Hashable, CaseIterable {
/// An option that resizes the content so it's all within the available space,
/// both vertically and horizontally.
///
/// This mode preserves the content's aspect ratio.
/// If the content doesn't have the same aspect ratio as the available
/// space, the content becomes the same size as the available space on
/// one axis and leaves empty space on the other.
case fit
/// An option that resizes the content so it occupies all available space,
/// both vertically and horizontally.
///
/// This mode preserves the content's aspect ratio.
/// If the content doesn't have the same aspect ratio as the available
/// space, the content becomes the same size as the available space on
/// one axis, and larger on the other axis.
case fill
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ContentMode, b: ContentMode) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias AllCases = [ContentMode]
/// A collection of all values of this type.
public static var allCases: [ContentMode] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ContentMode : Sendable {
}
/// A kind for the content shape of a view.
///
/// The kind is used by the system to influence various effects, hit-testing,
/// and more.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct ContentShapeKinds : OptionSet, Sendable {
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public var rawValue: Int
/// Creates a content shape kind.
public init(rawValue: Int)
/// The kind for hit-testing and accessibility.
///
/// Setting a content shape with this kind causes the view to hit-test
/// using the specified shape.
public static let interaction: ContentShapeKinds
/// The kind for drag and drop previews.
///
/// When using this kind, only the preview shape is affected. To control the
/// shape used to hit-test and start the drag preview, use the `interaction`
/// kind.
@available(watchOS, unavailable)
@available(tvOS, unavailable)
public static let dragPreview: ContentShapeKinds
/// The kind for the focus effect.
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(visionOS, unavailable)
public static let focusEffect: ContentShapeKinds
/// The kind for accessibility visuals and sorting.
///
/// Setting a content shape with this kind causes the accessibility frame
/// and path of the view's underlying accessibility element to match the
/// shape without adjusting the hit-testing shape, updating the visual focus
/// ring that assistive apps, such as VoiceOver, draw, as well as how the
/// element is sorted. Updating the accessibility shape is only required if
/// the shape or size used to hit-test significantly diverges from the visual
/// shape of the view.
///
/// To control the shape for accessibility and hit-testing, use the `interaction` kind.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public static let accessibility: ContentShapeKinds
/// The type of the elements of an array literal.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
public typealias ArrayLiteralElement = ContentShapeKinds
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
public typealias Element = ContentShapeKinds
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
public typealias RawValue = Int
}
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
public enum ContentSizeCategory : Hashable, CaseIterable {
case extraSmall
case small
case medium
case large
case extraLarge
case extraExtraLarge
case extraExtraExtraLarge
case accessibilityMedium
case accessibilityLarge
case accessibilityExtraLarge
case accessibilityExtraExtraLarge
case accessibilityExtraExtraExtraLarge
/// A Boolean value indicating whether the content size category is one that
/// is associated with accessibility.
@available(iOS 13.4, macOS 10.15.4, tvOS 13.4, watchOS 6.2, *)
public var isAccessibilityCategory: Bool { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ContentSizeCategory, b: ContentSizeCategory) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "DynamicTypeSize")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, renamed: "DynamicTypeSize")
public typealias AllCases = [ContentSizeCategory]
/// A collection of all values of this type.
public static var allCases: [ContentSizeCategory] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ContentSizeCategory {
/// Returns a Boolean value indicating whether the value of the first argument is less than that of the second argument.
public static func < (lhs: ContentSizeCategory, rhs: ContentSizeCategory) -> Bool
/// Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.
public static func <= (lhs: ContentSizeCategory, rhs: ContentSizeCategory) -> Bool
/// Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.
public static func > (lhs: ContentSizeCategory, rhs: ContentSizeCategory) -> Bool
/// Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.
public static func >= (lhs: ContentSizeCategory, rhs: ContentSizeCategory) -> Bool
}
/// A kind of transition that applies to the content within a single view,
/// rather than to the insertion or removal of a view.
///
/// Set the behavior of content transitions within a view with the
/// ``View/contentTransition(_:)`` modifier, passing in one of the defined
/// transitions, such as ``opacity`` or ``interpolate`` as the parameter.
///
/// > Tip: Content transitions only take effect within transactions that apply
/// an ``Animation`` to the views inside the ``View/contentTransition(_:)``
/// modifier.
///
/// Content transitions only take effect within the context of an
/// ``Animation`` block.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct ContentTransition : Equatable, Sendable {
/// The identity content transition, which indicates that content changes
/// shouldn't animate.
///
/// You can pass this value to a ``View/contentTransition(_:)``
/// modifier to selectively disable animations that would otherwise
/// be applied by a ``withAnimation(_:_:)`` block.
public static let identity: ContentTransition
/// A content transition that indicates content fades from transparent
/// to opaque on insertion, and from opaque to transparent on removal.
public static let opacity: ContentTransition
/// A content transition that indicates the views attempt to interpolate
/// their contents during transitions, where appropriate.
///
/// Text views can interpolate transitions when the text views have
/// identical strings. Matching glyph pairs can animate changes to their
/// color, position, size, and any variable properties. Interpolation can
/// apply within a ``Font/Design`` case, but not between cases, or between
/// entirely different fonts. For example, you can interpolate a change
/// between ``Font/Weight/thin`` and ``Font/Weight/black`` variations of a
/// font, since these are both cases of ``Font/Weight``. However, you can't
/// interpolate between the default design of a font and its Italic version,
/// because these are different fonts. Any changes that can't show an
/// interpolated animation use an opacity animation instead.
///
/// Symbol images created with the ``Image/init(systemName:)`` initializer
/// work the same way as text: changes within the same symbol attempt to
/// interpolate the symbol's paths. When interpolation is unavailable, the
/// system uses an opacity transition instead.
public static let interpolate: ContentTransition
/// Creates a content transition intended to be used with `Text`
/// views displaying numeric text. In certain environments changes
/// to the text will enable a nonstandard transition tailored to
/// numeric characters that count up or down.
///
/// - Parameters:
/// - countsDown: true if the numbers represented by the text
/// are counting downwards.
///
/// - Returns: a new content transition.
public static func numericText(countsDown: Bool = false) -> ContentTransition
/// Creates a content transition intended to be used with `Text`
/// views displaying numbers.
///
/// The example below creates a text view displaying a particular
/// value, assigning the same value to the associated transition:
///
/// Text("\(value)")
/// .contentTransition(.numericText(value: value))
///
/// - Parameters:
/// - value: the value represented by the `Text` view being
/// animated. The difference between the old and new values
/// when the text changes will be used to determine the
/// animation direction.
///
/// - Returns: a new content transition.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public static func numericText(value: Double) -> ContentTransition
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ContentTransition, b: ContentTransition) -> Bool
}
/// The active appearance expected of controls in a window.
///
/// `ControlActiveState` and `EnvironmentValues.controlActiveState` are
/// deprecated, use `EnvironmentValues.appearsActive` instead.
@available(iOS, unavailable)
@available(macCatalyst, introduced: 13.0, deprecated: 100000.0, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public enum ControlActiveState : Equatable, CaseIterable, Sendable {
case key
case active
case inactive
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ControlActiveState, b: ControlActiveState) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
@available(iOS, unavailable, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(tvOS, unavailable, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(watchOS, unavailable, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(macCatalyst, introduced: 13.0, deprecated: 100000.0, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(visionOS, unavailable, message: "Use `EnvironmentValues.appearsActive` instead.")
public typealias AllCases = [ControlActiveState]
/// A collection of all values of this type.
public static var allCases: [ControlActiveState] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS, unavailable)
@available(macCatalyst, introduced: 13.0, deprecated: 100000.0, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
extension ControlActiveState : Hashable {
}
/// A resolved coordinate space created by the coordinate space protocol.
///
/// You don't typically use `CoordinateSpace` directly. Instead, use the static
/// properties and functions of `CoordinateSpaceProtocol` such as `.global`,
/// `.local`, and `.named(_:)`.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum CoordinateSpace {
/// The global coordinate space at the root of the view hierarchy.
case global
/// The local coordinate space of the current view.
case local
/// A named reference to a view's local coordinate space.
case named(AnyHashable)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension CoordinateSpace {
public var isGlobal: Bool { get }
public var isLocal: Bool { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension CoordinateSpace : Equatable, Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: CoordinateSpace, rhs: CoordinateSpace) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A frame of reference within the layout system.
///
/// All geometric properties of a view, including size, position, and
/// transform, are defined within the local coordinate space of the view's
/// parent. These values can be converted into other coordinate spaces
/// by passing types conforming to this protocol into functions such as
/// `GeometryProxy.frame(in:)`.
///
/// For example, a named coordinate space allows you to convert the frame
/// of a view into the local coordinate space of an ancestor view by defining
/// a named coordinate space using the `coordinateSpace(_:)` modifier, then
/// passing that same named coordinate space into the `frame(in:)` function.
///
/// VStack {
/// GeometryReader { geometryProxy in
/// let distanceFromTop = geometryProxy.frame(in: "container").origin.y
/// Text("This view is \(distanceFromTop) points from the top of the VStack")
/// }
/// .padding()
/// }
/// .coordinateSpace(.named("container"))
///
/// You don't typically create types conforming to this protocol yourself.
/// Instead, use the system-provided `.global`, `.local`, and `.named(_:)`
/// implementations.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public protocol CoordinateSpaceProtocol {
/// The resolved coordinate space.
var coordinateSpace: CoordinateSpace { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CoordinateSpaceProtocol where Self == NamedCoordinateSpace {
/// Creates a named coordinate space using the given value.
///
/// Use the `coordinateSpace(_:)` modifier to assign a name to the local
/// coordinate space of a parent view. Child views can then refer to that
/// coordinate space using `.named(_:)`.
///
/// - Parameter name: A unique value that identifies the coordinate space.
///
/// - Returns: A named coordinate space identified by the given value.
public static func named(_ name: some Hashable) -> NamedCoordinateSpace
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CoordinateSpaceProtocol where Self == LocalCoordinateSpace {
/// The local coordinate space of the current view.
public static var local: LocalCoordinateSpace { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CoordinateSpaceProtocol where Self == GlobalCoordinateSpace {
/// The global coordinate space at the root of the view hierarchy.
public static var global: GlobalCoordinateSpace { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CoordinateSpaceProtocol where Self == NamedCoordinateSpace {
/// The named coordinate space that is added by the system for the innermost
/// containing scroll view that allows scrolling along the provided axis.
public static func scrollView(axis: Axis) -> Self
/// The named coordinate space that is added by the system for the innermost
/// containing scroll view.
public static var scrollView: NamedCoordinateSpace { get }
}
/// A keyframe that uses a cubic curve to smoothly interpolate between values.
///
/// If you don't specify a start or end velocity, SwiftUI automatically
/// computes a curve that maintains smooth motion between keyframes.
///
/// Adjacent cubic keyframes result in a Catmull-Rom spline.
///
/// If a cubic keyframe follows a different type of keyframe, such as a linear
/// keyframe, the end velocity of the segment defined by the previous keyframe
/// will be used as the starting velocity.
///
/// Likewise, if a cubic keyframe is followed by a different type of keyframe,
/// the initial velocity of the next segment is used as the end velocity of the
/// segment defined by this keyframe.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct CubicKeyframe<Value> : KeyframeTrackContent where Value : Animatable {
/// Creates a new keyframe using the given value and timestamp.
///
/// - Parameters:
/// - to: The value of the keyframe.
/// - startVelocity: The velocity of the value at the beginning of the
/// segment, or `nil` to automatically compute the velocity to maintain
/// smooth motion.
/// - endVelocity: The velocity of the value at the end of the segment,
/// or `nil` to automatically compute the velocity to maintain smooth
/// motion.
/// - duration: The duration of the segment defined by this keyframe.
public init(_ to: Value, duration: TimeInterval, startVelocity: Value? = nil, endVelocity: Value? = nil)
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = CubicKeyframe<Value>
}
/// A type that defines how an animatable value changes over time.
///
/// Use this protocol to create a type that changes an animatable value over
/// time, which produces a custom visual transition of a view. For example, the
/// follow code changes an animatable value using an elastic ease-in ease-out
/// function:
///
/// struct ElasticEaseInEaseOutAnimation: CustomAnimation {
/// let duration: TimeInterval
///
/// func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
/// if time > duration { return nil } // The animation has finished.
///
/// let p = time / duration
/// let s = sin((20 * p - 11.125) * ((2 * Double.pi) / 4.5))
/// if p < 0.5 {
/// return value.scaled(by: -(pow(2, 20 * p - 10) * s) / 2)
/// } else {
/// return value.scaled(by: (pow(2, -20 * p + 10) * s) / 2 + 1)
/// }
/// }
/// }
///
/// > Note: To maintain state during the life span of a custom animation, use
/// the ``AnimationContext/state`` property available on the `context`
/// parameter value. You can also use context's
/// ``AnimationContext/environment`` property to retrieve environment values
/// from the view that created the custom animation. For more information, see
/// ``AnimationContext``.
///
/// To create an ``Animation`` instance of a custom animation, use the
/// ``Animation/init(_:)`` initializer, passing in an instance of a custom
/// animation; for example:
///
/// Animation(ElasticEaseInEaseOutAnimation(duration: 5.0))
///
/// To help make view code more readable, extend ``Animation`` and add a static
/// property and function that returns an `Animation` instance of a custom
/// animation. For example, the following code adds the static property
/// `elasticEaseInEaseOut` that returns the elastic ease-in ease-out animation
/// with a default duration of `0.35` seconds. Next, the code adds a method
/// that returns the animation with a specified duration.
///
/// extension Animation {
/// static var elasticEaseInEaseOut: Animation { elasticEaseInEaseOut(duration: 0.35) }
/// static func elasticEaseInEaseOut(duration: TimeInterval) -> Animation {
/// Animation(ElasticEaseInEaseOutAnimation(duration: duration))
/// }
/// }
///
/// To animate a view with the elastic ease-in ease-out animation, a view calls
/// either `.elasticEaseInEaseOut` or `.elasticEaseInEaseOut(duration:)`. For
/// example, the follow code includes an Animate button that, when clicked,
/// animates a circle as it moves from one edge of the view to the other,
/// using the elastic ease-in ease-out animation with a duration of `5`
/// seconds:
///
/// struct ElasticEaseInEaseOutView: View {
/// @State private var isActive = false
///
/// var body: some View {
/// VStack(alignment: isActive ? .trailing : .leading) {
/// Circle()
/// .frame(width: 100.0)
/// .foregroundColor(.accentColor)
///
/// Button("Animate") {
/// withAnimation(.elasticEaseInEaseOut(duration: 5.0)) {
/// isActive.toggle()
/// }
/// }
/// .frame(maxWidth: .infinity)
/// }
/// .padding()
/// }
/// }
///
/// @Video(source: "animation-20-elastic.mp4", poster: "animation-20-elastic.png", alt: "A video that shows a circle that moves from one edge of the view to the other using an elastic ease-in ease-out animation. The circle's initial position is near the leading edge of the view. The circle begins moving slightly towards the leading, then towards trail edges of the view before it moves off the leading edge showing only two-thirds of the circle. The circle then moves quickly to the trailing edge of the view, going slightly beyond the edge so that only two-thirds of the circle is visible. The circle bounces back into full view before settling into position near the trailing edge of the view. The circle repeats this animation in reverse, going from the trailing edge of the view to the leading edge.")
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public protocol CustomAnimation : Hashable {
/// Calculates the value of the animation at the specified time.
///
/// Implement this method to calculate and return the value of the
/// animation at a given point in time. If the animation has finished,
/// return `nil` as the value. This signals to the system that it can
/// remove the animation.
///
/// If your custom animation needs to maintain state between calls to the
/// `animate(value:time:context:)` method, store the state data in
/// `context`. This makes the data available to the method next time
/// the system calls it. To learn more about managing state data in a
/// custom animation, see ``AnimationContext``.
///
/// - Parameters:
/// - value: The vector to animate towards.
/// - time: The elapsed time since the start of the animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: The current value of the animation, or `nil` if the
/// animation has finished.
func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic
/// Calculates the velocity of the animation at a specified time.
///
/// Implement this method to provide the velocity of the animation at a
/// given time. Should subsequent animations merge with the animation,
/// the system preserves continuity of the velocity between animations.
///
/// The default implementation of this method returns `nil`.
///
/// > Note: State and environment data is available to this method via the
/// `context` parameter, but `context` is read-only. This behavior is
/// different than with ``animate(value:time:context:)`` and
/// ``shouldMerge(previous:value:time:context:)`` where `context` is
/// an `inout` parameter, letting you change the context including state
/// data of the animation. For more information about managing state data
/// in a custom animation, see ``AnimationContext``.
///
/// - Parameters:
/// - value: The vector to animate towards.
/// - time: The amount of time since the start of the animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: The current velocity of the animation, or `nil` if the
/// animation has finished.
func velocity<V>(value: V, time: TimeInterval, context: AnimationContext<V>) -> V? where V : VectorArithmetic
/// Determines whether an instance of the animation can merge with other
/// instance of the same type.
///
/// When a view creates a new animation on an animatable value that already
/// has a running animation of the same animation type, the system calls
/// the `shouldMerge(previous:value:time:context:)` method on the new
/// instance to determine whether it can merge the two instance. Implement
/// this method if the animation can merge with another instance. The
/// default implementation returns `false`.
///
/// If `shouldMerge(previous:value:time:context:)` returns `true`, the
/// system merges the new animation instance with the previous animation.
/// The system provides to the new instance the state and elapsed time from
/// the previous one. Then it removes the previous animation.
///
/// If this method returns `false`, the system doesn't merge the animation
/// with the previous one. Instead, both animations run together and the
/// system combines their results.
///
/// If your custom animation needs to maintain state between calls to the
/// `shouldMerge(previous:value:time:context:)` method, store the state
/// data in `context`. This makes the data available to the method next
/// time the system calls it. To learn more, see ``AnimationContext``.
///
/// - Parameters:
/// - previous: The previous running animation.
/// - value: The vector to animate towards.
/// - time: The amount of time since the start of the previous animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: A Boolean value of `true` if the animation should merge with
/// the previous animation; otherwise, `false`.
func shouldMerge<V>(previous: Animation, value: V, time: TimeInterval, context: inout AnimationContext<V>) -> Bool where V : VectorArithmetic
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension CustomAnimation {
/// Calculates the velocity of the animation at a specified time.
///
/// Implement this method to provide the velocity of the animation at a
/// given time. Should subsequent animations merge with the animation,
/// the system preserves continuity of the velocity between animations.
///
/// The default implementation of this method returns `nil`.
///
/// > Note: State and environment data is available to this method via the
/// `context` parameter, but `context` is read-only. This behavior is
/// different than with ``animate(value:time:context:)`` and
/// ``shouldMerge(previous:value:time:context:)`` where `context` is
/// an `inout` parameter, letting you change the context including state
/// data of the animation. For more information about managing state data
/// in a custom animation, see ``AnimationContext``.
///
/// - Parameters:
/// - value: The vector to animate towards.
/// - time: The amount of time since the start of the animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: The current velocity of the animation, or `nil` if the
/// animation has finished.
public func velocity<V>(value: V, time: TimeInterval, context: AnimationContext<V>) -> V? where V : VectorArithmetic
/// Determines whether an instance of the animation can merge with other
/// instance of the same type.
///
/// When a view creates a new animation on an animatable value that already
/// has a running animation of the same animation type, the system calls
/// the `shouldMerge(previous:value:time:context:)` method on the new
/// instance to determine whether it can merge the two instance. Implement
/// this method if the animation can merge with another instance. The
/// default implementation returns `false`.
///
/// If `shouldMerge(previous:value:time:context:)` returns `true`, the
/// system merges the new animation instance with the previous animation.
/// The system provides to the new instance the state and elapsed time from
/// the previous one. Then it removes the previous animation.
///
/// If this method returns `false`, the system doesn't merge the animation
/// with the previous one. Instead, both animations run together and the
/// system combines their results.
///
/// If your custom animation needs to maintain state between calls to the
/// `shouldMerge(previous:value:time:context:)` method, store the state
/// data in `context`. This makes the data available to the method next
/// time the system calls it. To learn more, see ``AnimationContext``.
///
/// - Parameters:
/// - previous: The previous running animation.
/// - value: The vector to animate towards.
/// - time: The amount of time since the start of the previous animation.
/// - context: An instance of ``AnimationContext`` that provides access
/// to state and the animation environment.
/// - Returns: A Boolean value of `true` if the animation should merge with
/// the previous animation; otherwise, `false`.
public func shouldMerge<V>(previous: Animation, value: V, time: TimeInterval, context: inout AnimationContext<V>) -> Bool where V : VectorArithmetic
}
/// A selectability type that disables text selection by the person using your app.
///
/// Don't use this type directly. Instead, use ``TextSelectability/disabled``.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct DisabledTextSelectability : TextSelectability {
/// A Boolean value that indicates whether the selectability type allows
/// selection.
///
/// Conforming types, such as ``EnabledTextSelectability`` and
/// ``DisabledTextSelectability``, return `true` or `false` for this
/// property as appropriate. SwiftUI expects this value for a given
/// selectability type to be constant, unaffected by global state.
public static let allowsSelection: Bool
}
/// 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, see
/// <doc://com.apple.documentation/design/human-interface-guidelines/typography>
/// in the Human Interface Guidelines.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public enum DynamicTypeSize : Hashable, Comparable, CaseIterable, Sendable {
/// An extra small size.
case xSmall
/// A small size.
case small
/// A medium size.
case medium
/// A large size.
case large
/// An extra large size.
case xLarge
/// An extra extra large size.
case xxLarge
/// An extra extra extra large size.
case xxxLarge
/// The first accessibility size.
case accessibility1
/// The second accessibility size.
case accessibility2
/// The third accessibility size.
case accessibility3
/// The fourth accessibility size.
case accessibility4
/// The fifth accessibility size.
case accessibility5
/// A Boolean value indicating whether the size is one that is associated
/// with accessibility.
public var isAccessibilitySize: Bool { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: DynamicTypeSize, b: DynamicTypeSize) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (a: DynamicTypeSize, b: DynamicTypeSize) -> Bool
/// A type that can represent a collection of all values of this type.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
public typealias AllCases = [DynamicTypeSize]
/// A collection of all values of this type.
public static var allCases: [DynamicTypeSize] { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A type of view that generates views from an underlying collection of data.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol DynamicViewContent : View {
/// The type of the underlying collection of data.
associatedtype Data : Collection
/// The collection of underlying data.
var data: Self.Data { get }
}
/// 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 edges.
@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 set of edges containing only the specified edge.
public init(_ e: Edge)
/// The type of the elements of an array literal.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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
}
@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 {
}
/// An ellipse aligned inside the frame of the view containing it.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@MainActor @frozen @preconcurrency 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.
nonisolated public func path(in rect: CGRect) -> Path
/// Creates a new ellipse shape.
@inlinable nonisolated public init()
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
nonisolated public var layoutDirectionBehavior: LayoutDirectionBehavior { get }
/// The type defining the data to animate.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Ellipse : InsettableShape {
/// Returns `self` inset by `amount`.
@MainActor @inlinable @preconcurrency public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias InsetShape = some InsettableShape
}
/// A radial gradient that draws an ellipse.
///
/// The gradient maps its coordinate space to the unit space square
/// in which its center and radii are defined, then stretches that
/// square to fill its bounding rect, possibly also stretching the
/// circular gradient to have elliptical contours.
///
/// For example, an elliptical gradient centered on the view, filling
/// its bounds:
///
/// EllipticalGradient(gradient: .init(colors: [.red, .yellow]))
///
/// When using an elliptical gradient as a shape style, you can also use
/// ``ShapeStyle/ellipticalGradient(_:center:startRadiusFraction:endRadiusFraction:)``.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@MainActor @frozen @preconcurrency public struct EllipticalGradient : ShapeStyle, View, Sendable {
/// Creates an elliptical gradient.
///
/// For example, an elliptical gradient centered on the top-leading
/// corner of the view:
///
/// EllipticalGradient(
/// gradient: .init(colors: [.blue, .green]),
/// center: .topLeading,
/// startRadiusFraction: 0,
/// endRadiusFraction: 1)
///
/// - Parameters:
/// - gradient: The colors and their parametric locations.
/// - center: The center of the circle, in [0, 1] coordinates.
/// - startRadiusFraction: The start radius value, as a fraction
/// between zero and one. Zero maps to the center point, one
/// maps to the diameter of the unit circle.
/// - endRadiusFraction: The end radius value, as a fraction
/// between zero and one. Zero maps to the center point, one
/// maps to the diameter of the unit circle.
nonisolated 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.
nonisolated 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.
nonisolated 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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
public typealias Body
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
/// An empty type for animatable data.
///
/// This type is suitable for use as the `animatableData` property of
/// types that do not have any animatable properties.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct EmptyAnimatableData : VectorArithmetic {
@inlinable public init()
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
@inlinable public static var zero: EmptyAnimatableData { get }
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@inlinable public static func += (lhs: inout EmptyAnimatableData, rhs: EmptyAnimatableData)
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@inlinable public static func -= (lhs: inout EmptyAnimatableData, rhs: EmptyAnimatableData)
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@inlinable public static func + (lhs: EmptyAnimatableData, rhs: EmptyAnimatableData) -> EmptyAnimatableData
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@inlinable public static func - (lhs: EmptyAnimatableData, rhs: EmptyAnimatableData) -> EmptyAnimatableData
/// Multiplies each component of this value by the given value.
@inlinable public mutating func scale(by rhs: Double)
/// The dot-product of this animatable data instance with itself.
@inlinable public var magnitudeSquared: Double { get }
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: EmptyAnimatableData, b: EmptyAnimatableData) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EmptyAnimatableData : Sendable {
}
/// An empty, 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, *)
@MainActor @frozen @preconcurrency public struct EmptyModifier : ViewModifier {
@MainActor @preconcurrency public static let identity: EmptyModifier
/// The type of view representing the body.
public typealias Body = Never
@inlinable nonisolated public init()
/// Gets the current body of the caller.
///
/// `content` is a proxy for the view that will have the modifier
/// represented by `Self` applied to it.
@MainActor @preconcurrency 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, *)
@MainActor @frozen @preconcurrency public struct EmptyView : View {
/// Creates an empty view.
@inlinable nonisolated 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body = Never
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EmptyView : Sendable {
}
/// The base visual effect that you apply additional effect to.
///
/// `EmptyVisualEffect` does not change the appearance of the view
/// that it is applied to.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct EmptyVisualEffect : VisualEffect {
/// Creates a new empty visual effect.
public init()
/// The type defining the data to animate.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias AnimatableData = EmptyAnimatableData
}
/// A selectability type that enables text selection by the person using your app.
///
/// Don't use this type directly. Instead, use ``TextSelectability/enabled``.
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct EnabledTextSelectability : TextSelectability {
/// A Boolean value that indicates whether the selectability type allows
/// selection.
///
/// Conforming types, such as ``EnabledTextSelectability`` and
/// ``DisabledTextSelectability``, return `true` or `false` for this
/// property as appropriate. SwiftUI expects this value for a given
/// selectability type to be constant, unaffected by global state.
public static let allowsSelection: Bool
}
/// Creates an environment values, transaction, container values,
/// or focused values entry.
///
/// ## Environment Values
///
/// Create ``EnvironmentValues`` entries by extending the
/// ``EnvironmentValues`` structure with new properties and attaching the
/// @Entry macro to the variable declarations:
///
/// ```swift
/// extension EnvironmentValues {
/// @Entry var myCustomValue: String = "Default value"
/// @Entry var anotherCustomValue = true
/// }
/// ```
///
/// ## Transaction Values
///
/// Create ``Transaction`` entries by extending the ``Transaction``
/// structure with new properties and attaching the @Entry macro
/// to the variable declarations:
///
/// ```swift
/// extension Transaction {
/// @Entry var myCustomValue: String = "Default value"
/// }
/// ```
///
/// ## Container Values
///
/// Create ``ContainerValues`` entries by extending the ``ContainerValues``
/// structure with new properties and attaching the @Entry macro
/// to the variable declarations:
///
/// ```swift
/// extension ContainerValues {
/// @Entry var myCustomValue: String = "Default value"
/// }
/// ```
///
/// ## Focused Values
///
/// Since the default value for ``FocusedValues`` is always `nil`,
/// ``FocusedValues`` entries cannot specify a different default value and
/// must have an Optional type.
///
/// Create ``FocusedValues`` entries by extending the
/// ``FocusedValues`` structure with new properties and attaching
/// the @Entry macro to the variable declarations:
///
/// ```swift
/// extension FocusedValues {
/// @Entry var myCustomValue: String?
/// }
/// ```
@attached(accessor) @attached(peer, names: prefixed(__Key_)) public macro Entry() = #externalMacro(module: "SwiftUIMacros", type: "EntryMacro")
/// 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 SwiftUI provides, see the
/// properties of the ``EnvironmentValues`` structure. For information about
/// creating custom environment values, see the ``Entry()`` macro.
///
/// ### Get an observable object
///
/// You can also use `Environment` to get an observable object from a view's
/// environment. The observable object must conform to the
/// <doc://com.apple.documentation/documentation/Observation/Observable>
/// protocol, and your app must set the object in the environment using the
/// the object itself or a key path.
///
/// To set the object in the environment using the object itself, use the
/// ``View/environment(_:)`` modifier:
///
/// @Observable
/// class Library {
/// var books: [Book] = [Book(), Book(), Book()]
///
/// var availableBooksCount: Int {
/// books.filter(\.isAvailable).count
/// }
/// }
///
/// @main
/// struct BookReaderApp: App {
/// @State private var library = Library()
///
/// var body: some Scene {
/// WindowGroup {
/// LibraryView()
/// .environment(library)
/// }
/// }
/// }
///
/// To get the observable object using its type, create a property and provide
/// the `Environment` property wrapper the object's type:
///
/// struct LibraryView: View {
/// @Environment(Library.self) private var library
///
/// var body: some View {
/// // ...
/// }
/// }
///
/// By default, reading an object from the environment returns a non-optional
/// object when using the object type as the key. This default behavior assumes
/// that a view in the current hierarchy previously stored a non-optional
/// instance of the type using the ``View/environment(_:)`` modifier. If
/// a view attempts to retrieve an object using its type and that object isn't
/// in the environment, SwiftUI throws an exception.
///
/// In cases where there is no guarantee that an object is in the environment,
/// retrieve an optional version of the object as shown in the following code.
/// If the object isn't available the environment, SwiftUI returns `nil`
/// instead of throwing an exception.
///
/// @Environment(Library.self) private var library: Library?
///
/// ### Get an observable object using a key path
///
/// To set the object with a key path, use the ``View/environment(_:_:)``
/// modifier:
///
/// @Observable
/// class Library {
/// var books: [Book] = [Book(), Book(), Book()]
///
/// var availableBooksCount: Int {
/// books.filter(\.isAvailable).count
/// }
/// }
///
/// @main
/// struct BookReaderApp: App {
/// @State private var library = Library()
///
/// var body: some Scene {
/// WindowGroup {
/// LibraryView()
/// .environment(\.library, library)
/// }
/// }
/// }
///
/// To get the object, create a property and specify the key path:
///
/// struct LibraryView: View {
/// @Environment(\.library) private var library
///
/// var body: some View {
/// // ...
/// }
/// }
///
@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 }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Environment : Sendable where Value : Sendable {
}
/// A key for accessing values in the environment.
///
/// You can create custom environment values by extending the
/// ``EnvironmentValues`` structure with new properties.
/// First declare a new environment key type and specify a value for the
/// required ``defaultValue`` property:
///
/// private struct MyEnvironmentKey: EnvironmentKey {
/// static let defaultValue: String = "Default value"
/// }
///
/// The Swift compiler automatically infers the associated ``Value`` type as the
/// type you specify for the default value. Then use the key to define a new
/// environment value property:
///
/// extension EnvironmentValues {
/// var myCustomValue: String {
/// get { self[MyEnvironmentKey.self] }
/// set { self[MyEnvironmentKey.self] = newValue }
/// }
/// }
///
/// Clients of your environment value never use the key directly.
/// Instead, they use the key path of your custom environment value property.
/// To set the environment value for a view and all its subviews, add the
/// ``View/environment(_:_:)`` view modifier to that view:
///
/// MyView()
/// .environment(\.myCustomValue, "Another string")
///
/// As a convenience, you can also define a dedicated view modifier to
/// apply this environment value:
///
/// extension View {
/// func myCustomValue(_ myCustomValue: String) -> some View {
/// environment(\.myCustomValue, myCustomValue)
/// }
/// }
///
/// This improves clarity at the call site:
///
/// MyView()
/// .myCustomValue("Another string")
///
/// To read the value from inside `MyView` or one of its descendants, use the
/// ``Environment`` property wrapper:
///
/// struct MyView: View {
/// @Environment(\.myCustomValue) var customValue: String
///
/// var body: some View {
/// Text(customValue) // Displays "Another string".
/// }
/// }
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol EnvironmentKey {
/// The associated type representing the type of the environment key's
/// value.
associatedtype Value
/// The default value for the environment key.
static var defaultValue: Self.Value { get }
}
/// A 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 a custom environment value by declaring a new property
/// in an extension to the environment values structure and applying
/// the ``Entry()`` macro to the variable declaration:
///
/// extension EnvironmentValues {
/// @Entry var myCustomValue: String = "Default value"
/// }
///
/// 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 a custom environment value by declaring a new property
/// in an extension to the environment values structure and applying
/// the ``Entry()`` macro to the variable declaration:
///
/// extension EnvironmentValues {
/// @Entry var myCustomValue: String = "Default value"
/// }
///
/// 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 }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// The layout direction associated with the current environment.
///
/// Use this value to determine or set whether the environment uses a
/// left-to-right or right-to-left direction.
public var layoutDirection: LayoutDirection
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// A Boolean value that indicates whether the view associated with this
/// environment allows user interaction.
///
/// The default value is `true`.
public var isEnabled: Bool
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension EnvironmentValues {
/// An action that opens a URL.
///
/// Read this environment value to get an ``OpenURLAction``
/// instance for a given ``Environment``. Call the
/// instance to open a URL. You call the instance directly because it
/// defines a ``OpenURLAction/callAsFunction(_:)`` method that Swift
/// calls when you call the instance.
///
/// For example, you can open a web site when the user taps a button:
///
/// struct OpenURLExample: View {
/// @Environment(\.openURL) private var openURL
///
/// var body: some View {
/// Button {
/// if let url = URL(string: "https://www.example.com") {
/// openURL(url)
/// }
/// } label: {
/// Label("Get Help", systemImage: "person.fill.questionmark")
/// }
/// }
/// }
///
/// If you want to know whether the action succeeds, add a completion
/// handler that takes a Boolean value. In this case, Swift implicitly
/// calls the ``OpenURLAction/callAsFunction(_:completion:)`` method
/// instead. That method calls your completion handler after it determines
/// whether it can open the URL, but possibly before it finishes opening
/// the URL. You can add a handler to the example above so that
/// it prints the outcome to the console:
///
/// openURL(url) { accepted in
/// print(accepted ? "Success" : "Failure")
/// }
///
/// The system provides a default open URL action with behavior
/// that depends on the contents of the URL. For example, the default
/// action opens a Universal Link in the associated app if possible,
/// or in the user’s default web browser if not.
///
/// You can also set a custom action using the ``View/environment(_:_:)``
/// view modifier. Any views that read the action from the environment,
/// including the built-in ``Link`` view and ``Text`` views with markdown
/// links, or links in attributed strings, use your action. Initialize an
/// action by calling the ``OpenURLAction/init(handler:)`` initializer with
/// a handler that takes a URL and returns an ``OpenURLAction/Result``:
///
/// Text("Visit [Example Company](https://www.example.com) for details.")
/// .environment(\.openURL, OpenURLAction { url in
/// handleURL(url) // Define this method to take appropriate action.
/// return .handled
/// })
///
/// SwiftUI translates the value that your custom action's handler
/// returns into an appropriate Boolean result for the action call.
/// For example, a view that uses the action declared above
/// receives `true` when calling the action, because the
/// handler always returns ``OpenURLAction/Result/handled``.
public var openURL: OpenURLAction
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 8.0, *)
extension EnvironmentValues {
/// A Boolean value that indicates whether the display or environment currently requires
/// reduced luminance.
///
/// When you detect this condition, lower the overall brightness of your view.
/// For example, you can change large, filled shapes to be stroked, and choose
/// less bright colors:
///
/// @Environment(\.isLuminanceReduced) var isLuminanceReduced
///
/// var body: some View {
/// if isLuminanceReduced {
/// Circle()
/// .stroke(Color.gray, lineWidth: 10)
/// } else {
/// Circle()
/// .fill(Color.white)
/// }
/// }
///
/// In addition to the changes that you make, the system could also
/// dim the display to achieve a suitable brightness. By reacting to
/// `isLuminanceReduced`, you can preserve contrast and readability
/// while helping to satisfy the reduced brightness requirement.
///
/// > Note: On watchOS, the system typically sets this value to `true` when the user
/// lowers their wrist, but the display remains on. Starting in watchOS 8, the system keeps your
/// view visible on wrist down by default. If you want the system to blur the screen
/// instead, as it did in earlier versions of watchOS, set the value for the
/// <doc://com.apple.documentation/documentation/BundleResources/Information_Property_List/WKSupportsAlwaysOnDisplay>
/// key in your app's
/// <doc://com.apple.documentation/documentation/BundleResources/Information_Property_List>
/// file to `false`.
public var isLuminanceReduced: Bool
}
@available(iOS 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 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:)``, 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?
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension EnvironmentValues {
/// The behavior materials should use for their active state, defaulting to
/// `automatic`.
public var materialActiveAppearance: MaterialActiveAppearance
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The current symbol rendering mode, or `nil` denoting that the
/// mode is picked automatically using the current image and
/// foreground style as parameters.
public var symbolRenderingMode: SymbolRenderingMode?
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// An environment value that indicates how a text view aligns its lines
/// when the content wraps or contains newlines.
///
/// Set this value for a view hierarchy by applying the
/// ``View/multilineTextAlignment(_:)`` view modifier. Views in the
/// hierarchy that display text, like ``Text`` or ``TextEditor``, read the
/// value from the environment and adjust their text alignment accordingly.
///
/// This value has no effect on a ``Text`` view that contains only one
/// line of text, because a text view has a width that exactly matches the
/// width of its widest line. If you want to align an entire text view
/// rather than its contents, set the aligment of its container, like a
/// ``VStack`` or a frame that you create with the
/// ``View/frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)``
/// modifier.
///
/// > Note: You can use this value to control the alignment of a ``Text``
/// view that you create with the ``Text/init(_:style:)`` initializer
/// to display localized dates and times, including when the view uses
/// only a single line, but only when that view appears in a widget.
public var multilineTextAlignment: TextAlignment
/// A value that indicates how the layout truncates the last line of text to
/// fit into the available space.
///
/// The default value is ``Text/TruncationMode/tail``. Some controls,
/// however, might have a different default if appropriate.
public var truncationMode: Text.TruncationMode
/// The distance in points between the bottom of one line fragment and the
/// top of the next.
///
/// This value is always nonnegative.
public var lineSpacing: CGFloat
/// A Boolean value that indicates whether inter-character spacing should
/// tighten to fit the text into the available space.
///
/// The default value is `false`.
public var allowsTightening: Bool
/// The minimum permissible proportion to shrink the font size to fit
/// the text into the available space.
///
/// In the example below, a label with a `minimumScaleFactor` of `0.5`
/// draws its text in a font size as small as half of the actual font if
/// needed to fit into the space next to the text input field:
///
/// HStack {
/// Text("This is a very long label:")
/// .lineLimit(1)
/// .minimumScaleFactor(0.5)
/// TextField("My Long Text Field", text: $myTextField)
/// .frame(width: 250, height: 50, alignment: .center)
/// }
///
/// ![A screenshot showing the effects of setting the minimumScaleFactor on
/// the text in a view](SwiftUI-View-minimumScaleFactor.png)
///
/// You can set the minimum scale factor to any value greater than `0` and
/// less than or equal to `1`. The default value is `1`.
///
/// SwiftUI uses this value to shrink text that doesn't fit in a view when
/// it's okay to shrink the text. For example, a label with a
/// `minimumScaleFactor` of `0.5` draws its text in a font size as small as
/// half the actual font if needed.
public var minimumScaleFactor: CGFloat
/// A stylistic override to transform the case of `Text` when displayed,
/// using the environment's locale.
///
/// The default value is `nil`, displaying the `Text` without any case
/// changes.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public var textCase: Text.Case?
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// The maximum number of lines that text can occupy in a view.
///
/// The maximum number of lines is `1` if the value is less than `1`. If the
/// value is `nil`, the text uses as many lines as required. The default is
/// `nil`.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public var lineLimit: Int?
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension EnvironmentValues {
/// The prominence of the background underneath views associated with this
/// environment.
///
/// Foreground elements above an increased prominence background are
/// typically adjusted to have higher contrast against a potentially vivid
/// color, such as taking on a higher opacity monochrome appearance
/// according to the `colorScheme`. System styles like `primary`,
/// `secondary`, etc will automatically resolve to an appropriate style in
/// this context. The property can be read and used for custom styled
/// elements.
///
/// In the example below, a custom star rating element is in a list row
/// alongside some text. When the row is selected and has an increased
/// prominence appearance, the text and star rating will update their
/// appearance, the star rating replacing its use of yellow with the
/// standard `secondary` style.
///
/// struct RecipeList: View {
/// var recipes: [Recipe]
/// @Binding var selectedRecipe: Recipe.ID?
///
/// var body: some View {
/// List(recipes, selection: $selectedRecipe) {
/// RecipeListRow(recipe: $0)
/// }
/// }
/// }
///
/// struct RecipeListRow: View {
/// var recipe: Recipe
/// var body: some View {
/// VStack(alignment: .leading) {
/// HStack(alignment: .firstTextBaseline) {
/// Text(recipe.name)
/// Spacer()
/// StarRating(rating: recipe.rating)
/// }
/// Text(recipe.description)
/// .foregroundStyle(.secondary)
/// .lineLimit(2, reservesSpace: true)
/// }
/// }
/// }
///
/// private struct StarRating: View {
/// var rating: Int
///
/// @Environment(\.backgroundProminence)
/// private var backgroundProminence
///
/// var body: some View {
/// HStack(spacing: 1) {
/// ForEach(0..<rating, id: \.self) { _ in
/// Image(systemName: "star.fill")
/// }
/// }
/// .foregroundStyle(backgroundProminence == .increased ?
/// AnyShapeStyle(.secondary) : AnyShapeStyle(.yellow))
/// .imageScale(.small)
/// }
/// }
///
/// Note that the use of `backgroundProminence` was used by a view that
/// was nested in additional stack containers within the row. This ensured
/// that the value correctly reflected the environment within the list row
/// itself, as opposed to the environment of the list as a whole. One way
/// to ensure correct resolution would be to prefer using this in a custom
/// ShapeStyle instead, for example:
///
/// private struct StarRating: View {
/// var rating: Int
///
/// var body: some View {
/// HStack(spacing: 1) {
/// ForEach(0..<rating, id: \.self) { _ in
/// Image(systemName: "star.fill")
/// }
/// }
/// .foregroundStyle(FillStyle())
/// .imageScale(.small)
/// }
/// }
///
/// extension StarRating {
/// struct FillStyle: ShapeStyle {
/// func resolve(in env: EnvironmentValues) -> some ShapeStyle {
/// switch env.backgroundProminence {
/// case .increased: return AnyShapeStyle(.secondary)
/// default: return AnyShapeStyle(.yellow)
/// }
/// }
/// }
/// }
///
/// Views like `List` and `Table` as well as standard shape styles like
/// `ShapeStyle.selection` will automatically update the background
/// prominence of foreground views. For custom backgrounds, this environment
/// property can be explicitly set on views above custom backgrounds.
public var backgroundProminence: BackgroundProminence
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EnvironmentValues {
/// An optional style that overrides the default system background
/// style when set.
public var backgroundStyle: AnyShapeStyle?
}
@available(iOS 18.0, macOS 10.15, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension EnvironmentValues {
/// Whether views and styles in this environment should prefer an active
/// appearance over an inactive appearance.
///
/// On macOS, views in the focused window (also referred to as the "key"
/// window) should appear active. Some contexts also appear active in other
/// circumstances, such as the contents of a window toolbar appearing active
/// when the window is not focused but is the main window.
///
/// Typical adjustments made when a view does not appear active include:
/// - Uses of `Color.accentColor` should generally be removed or replaced
/// with a desaturated style.
/// - Text and image content in sidebars should appear dimmer.
/// - Buttons with destructive actions should appear disabled.
/// - `ShapeStyle.selection` and selection in list and tables will
/// automatically become a grey color
///
/// Custom views, styles, and shape styles can use this to adjust their
/// own appearance:
///
/// struct ProminentPillButtonStyle: ButtonStyle {
/// @Environment(\.appearsActive) private var appearsActive
///
/// func makeBody(configuration: Configuration) -> some View {
/// configuration.label
/// .lineLimit(1)
/// .padding(.horizontal, 8)
/// .padding(.vertical, 2)
/// .frame(minHeight: 20)
/// .overlay(Capsule().strokeBorder(.tertiary))
/// .background(appearsActive ? Color.accentColor : .clear, in: .capsule)
/// .contentShape(.capsule)
/// }
/// }
///
/// On all other platforms, this value is always `true`.
///
/// This is bridged with `UITraitCollection.activeAppearance` for UIKit
/// hosted content.
@available(iOS 18.0, macOS 10.15, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@backDeployed(before: macOS 15.0)
public var appearsActive: Bool
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The current Dynamic Type size.
///
/// This value changes as the user's chosen Dynamic Type size changes. The
/// default value is device-dependent.
///
/// When limiting the Dynamic Type size, consider if adding a
/// large content view with ``View/accessibilityShowsLargeContentViewer()``
/// would be appropriate.
///
/// On macOS, this value cannot be changed by users and does not affect the
/// text size.
public var dynamicTypeSize: DynamicTypeSize
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, visionOS 1.0, *)
extension EnvironmentValues {
/// The preferred size of the content.
///
/// The default value is ``ContentSizeCategory/large``.
@available(iOS, introduced: 13.0, deprecated: 100000.0, renamed: "dynamicTypeSize")
@available(macOS, introduced: 10.15, deprecated: 100000.0, renamed: "dynamicTypeSize")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, renamed: "dynamicTypeSize")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, renamed: "dynamicTypeSize")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, renamed: "dynamicTypeSize")
public var sizeCategory: ContentSizeCategory
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The prominence to apply to section headers within a view.
///
/// The default is ``Prominence/standard``.
public var headerProminence: Prominence
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension EnvironmentValues {
/// The allowed dynamic range for the view, or nil.
public var allowedDynamicRange: Image.DynamicRange?
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension EnvironmentValues {
/// The symbol variant to use in this environment.
///
/// You set this environment value indirectly by using the
/// ``View/symbolVariant(_:)`` view modifier. However, you access the
/// environment variable directly using the ``View/environment(_:_:)``
/// modifier. Do this when you want to use the ``SymbolVariants/none``
/// variant to ignore the value that's already in the environment:
///
/// HStack {
/// Image(systemName: "heart")
/// Image(systemName: "heart")
/// .environment(\.symbolVariants, .none)
/// }
/// .symbolVariant(.fill)
///
/// ![A screenshot of two heart symbols. The first is filled while the
/// second is outlined.](SymbolVariants-none-1)
public var symbolVariants: SymbolVariants
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension EnvironmentValues {
/// The current method of animating the contents of views.
public var contentTransition: ContentTransition
/// A Boolean value that controls whether views that render content
/// transitions use GPU-accelerated rendering.
///
/// Setting this value to `true` causes SwiftUI to wrap content transitions
/// with a ``View/drawingGroup(opaque:colorMode:)`` modifier.
public var contentTransitionAddsDrawingGroup: Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// The default font of this environment.
public var font: Font?
/// The image scale for this environment.
@available(macOS 11.0, *)
public var imageScale: Image.Scale
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// The display scale of this environment.
public var displayScale: CGFloat
/// The size of a pixel on the screen.
///
/// This value is usually equal to `1` divided by
/// ``EnvironmentValues/displayScale``.
public var pixelLength: CGFloat { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// 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
/// The active appearance expected of controls in a window.
///
/// `ControlActiveState` and `EnvironmentValues.controlActiveState` are
/// deprecated, use `EnvironmentValues.appearsActive` instead.
///
/// Starting with macOS 15.0, the value of this environment property is
/// strictly mapped to and from `EnvironmentValues.appearsActive` as follows:
/// - `appearsActive == true`, `controlActiveState` returns `.key`
/// - `appearsActive == false`, `controlActiveState` returns `.inactive`
/// - `controlActiveState` is set to `.key` or `.active`, `appearsActive`
/// will be set to `true`.
/// - `controlActiveState` is set to `.inactive`, `appearsActive` will be
/// set to `false`.
@available(iOS, unavailable)
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `EnvironmentValues.appearsActive` instead.")
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public var controlActiveState: ControlActiveState
/// The horizontal size class of this environment.
///
/// You receive a ``UserInterfaceSizeClass`` value when you read this
/// environment value. The value tells you about the amount of horizontal
/// space available to the view that reads it. You can read this
/// size class like any other of the ``EnvironmentValues``, by creating a
/// property with the ``Environment`` property wrapper:
///
/// @Environment(\.horizontalSizeClass) private var horizontalSizeClass
///
/// SwiftUI sets this size class based on several factors, including:
///
/// * The current device type.
/// * The orientation of the device.
/// * The appearance of Slide Over and Split View on iPad.
///
/// Several built-in views change their behavior based on this size class.
/// For example, a ``NavigationView`` presents a multicolumn view when
/// the horizontal size class is ``UserInterfaceSizeClass/regular``,
/// but a single column otherwise. You can also adjust the appearance of
/// custom views by reading the size class and conditioning your views.
/// If you do, be prepared to handle size class changes while
/// your app runs, because factors like device orientation can change at
/// runtime.
///
/// In watchOS, the horizontal size class is always
/// ``UserInterfaceSizeClass/compact``. In macOS, and tvOS, it's always
/// ``UserInterfaceSizeClass/regular``.
///
/// Writing to the horizontal size class in the environment
/// before macOS 14.0, tvOS 17.0, and watchOS 10.0 is not supported.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@backDeployed(before: macOS 14.0, tvOS 17.0, watchOS 10.0)
public var horizontalSizeClass: UserInterfaceSizeClass?
/// The vertical size class of this environment.
///
/// You receive a ``UserInterfaceSizeClass`` value when you read this
/// environment value. The value tells you about the amount of vertical
/// space available to the view that reads it. You can read this
/// size class like any other of the ``EnvironmentValues``, by creating a
/// property with the ``Environment`` property wrapper:
///
/// @Environment(\.verticalSizeClass) private var verticalSizeClass
///
/// SwiftUI sets this size class based on several factors, including:
///
/// * The current device type.
/// * The orientation of the device.
///
/// You can adjust the appearance of custom views by reading this size
/// class and conditioning your views. If you do, be prepared to
/// handle size class changes while your app runs, because factors like
/// device orientation can change at runtime.
///
/// In watchOS, the vertical size class is always
/// ``UserInterfaceSizeClass/compact``. In macOS, and tvOS, it's always
/// ``UserInterfaceSizeClass/regular``.
///
/// Writing to the vertical size class in the environment
/// before macOS 14.0, tvOS 17.0, and watchOS 10.0 is not supported.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@backDeployed(before: macOS 14.0, tvOS 17.0, watchOS 10.0)
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 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension EnvironmentValues {
/// Whether the setting to reduce flashing or strobing lights in video
/// content is on. This setting can also be used to determine if UI in
/// playback controls should be shown to indicate upcoming content that
/// includes flashing or strobing lights.
public var accessibilityDimFlashingLights: Bool { get }
/// Whether the setting for playing animations in an animated image is
/// on. When this value is false, any presented image that contains
/// animation should not play automatically.
public var accessibilityPlayAnimatedImages: Bool { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {
/// The color scheme of this environment.
///
/// Read this environment value from within a view to find out if SwiftUI
/// is currently displaying the view using the ``ColorScheme/light`` or
/// ``ColorScheme/dark`` appearance. The value that you receive depends on
/// whether the user has enabled Dark Mode, possibly superseded by
/// the configuration of the current presentation's view hierarchy.
///
/// @Environment(\.colorScheme) private var colorScheme
///
/// var body: some View {
/// Text(colorScheme == .dark ? "Dark" : "Light")
/// }
///
/// You can set the `colorScheme` environment value directly,
/// but that usually isn't what you want. Doing so changes the color
/// scheme of the given view and its child views but *not* the views
/// above it in the view hierarchy. Instead, set a color scheme using the
/// ``View/preferredColorScheme(_:)`` modifier, which also propagates the
/// value up through the view hierarchy to the enclosing presentation, like
/// a sheet or a window.
///
/// When adjusting your app's user interface to match the color scheme,
/// consider also checking the ``EnvironmentValues/colorSchemeContrast``
/// property, which reflects a system-wide contrast setting that the user
/// controls. For information, see
/// <doc://com.apple.documentation/design/human-interface-guidelines/accessibility#Color-and-effects>
/// in the Human Interface Guidelines.
///
/// > Note: If you only need to provide different colors or
/// images for different color scheme and contrast settings, do that in
/// your app's Asset Catalog. See
/// <doc://com.apple.documentation/documentation/Xcode/Asset-Management>.
public var colorScheme: ColorScheme
/// The contrast associated with the color scheme of this environment.
///
/// Read this environment value from within a view to find out if SwiftUI
/// is currently displaying the view using ``ColorSchemeContrast/standard``
/// or ``ColorSchemeContrast/increased`` contrast. The value that you read
/// depends entirely on user settings, and you can't change it.
///
/// @Environment(\.colorSchemeContrast) private var colorSchemeContrast
///
/// var body: some View {
/// Text(colorSchemeContrast == .standard ? "Standard" : "Increased")
/// }
///
/// When adjusting your app's user interface to match the contrast,
/// consider also checking the ``EnvironmentValues/colorScheme`` property
/// to find out if SwiftUI is displaying the view with a light or dark
/// appearance. For information, see
/// <doc://com.apple.documentation/design/human-interface-guidelines/accessibility#Color-and-effects>
/// in the Human Interface Guidelines.
///
/// > Note: If you only need to provide different colors or
/// images for different color scheme and contrast settings, do that in
/// your app's Asset Catalog. See
/// <doc://com.apple.documentation/documentation/Xcode/Asset-Management>.
public var colorSchemeContrast: ColorSchemeContrast { get }
}
/// 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 set of key modifiers that you can add to a gesture.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct EventModifiers : OptionSet {
/// The raw value.
public let rawValue: Int
/// Creates a new set from a raw value.
///
/// - Parameter rawValue: The raw value with which to create the key
/// modifier.
public init(rawValue: Int)
/// The Caps Lock key.
public static let capsLock: EventModifiers
/// The Shift key.
public static let shift: EventModifiers
/// The Control key.
public static let control: EventModifiers
/// The Option key.
public static let option: EventModifiers
/// The Command key.
public static let command: EventModifiers
/// Any key on the numeric keypad.
public static let numericPad: EventModifiers
/// The Function key.
@available(iOS, deprecated: 15.0, message: "Function modifier is reserved for system applications")
@available(macOS, deprecated: 12.0, message: "Function modifier is reserved for system applications")
@available(tvOS, deprecated: 15.0, message: "Function modifier is reserved for system applications")
@available(watchOS, deprecated: 8.0, message: "Function modifier is reserved for system applications")
@available(visionOS, deprecated: 1.0, message: "Function modifier is reserved for system applications")
public static let function: EventModifiers
/// All possible modifier keys.
public static let all: EventModifiers
/// The type of the elements of an array literal.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias RawValue = Int
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension EventModifiers : Sendable {
}
/// A schedule for updating a timeline view at the start of every minute.
///
/// You can also use ``TimelineSchedule/everyMinute`` to construct this
/// schedule.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct EveryMinuteTimelineSchedule : TimelineSchedule, Sendable {
/// The sequence of dates in an every minute schedule.
///
/// The ``EveryMinuteTimelineSchedule/entries(from:mode:)`` method returns
/// a value of this type, which is a
/// <doc://com.apple.documentation/documentation/Swift/Sequence>
/// of dates, one per minute, in ascending order. A ``TimelineView`` that
/// you create updates its content at the moments in time corresponding to
/// the dates included in the sequence.
public struct Entries : Sequence, IteratorProtocol, Sendable {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying sequence. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// You must not call this method if any other copy of this iterator has been
/// advanced with a call to its `next()` method.
///
/// The following example shows how an iterator can be used explicitly to
/// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and
/// then call the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence, if a next element
/// exists; otherwise, `nil`.
public mutating func next() -> Date?
/// A type representing the sequence's elements.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
public typealias Element = Date
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
public typealias Iterator = EveryMinuteTimelineSchedule.Entries
}
/// Creates a per-minute update schedule.
///
/// Use the ``EveryMinuteTimelineSchedule/entries(from:mode:)`` method
/// to get the sequence of dates.
public init()
/// Provides a sequence of per-minute dates starting from a given date.
///
/// A ``TimelineView`` that you create with an every minute schedule
/// calls this method to ask the schedule when to update its content.
/// The method returns a sequence of per-minute dates in increasing
/// order, from earliest to latest, that represents
/// when the timeline view updates.
///
/// For a `startDate` that's exactly minute-aligned, the
/// schedule's sequence of dates starts at that time. Otherwise, it
/// starts at the beginning of the specified minute. For
/// example, for start dates of both `10:09:32` and `10:09:00`, the first
/// entry in the sequence is `10:09:00`.
///
/// - Parameters:
/// - startDate: The date from which the sequence begins.
/// - mode: The mode for the update schedule.
/// - Returns: A sequence of per-minute dates in ascending order.
public func entries(from startDate: Date, mode: TimelineScheduleMode) -> EveryMinuteTimelineSchedule.Entries
}
/// A gesture that consists of two gestures where only one of them can succeed.
///
/// The `ExclusiveGesture` gives precedence to its first gesture.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct ExclusiveGesture<First, Second> : Gesture where First : Gesture, Second : Gesture {
/// The value of an exclusive gesture that indicates which of two gestures
/// succeeded.
@frozen public enum Value {
/// The first of two gestures succeeded.
case first(First.Value)
/// The second of two gestures succeeded.
case second(Second.Value)
}
/// The first of two gestures.
public var first: First
/// The second of two gestures.
public var second: Second
/// Creates a gesture from two gestures where only one of them succeeds.
///
/// - Parameters:
/// - first: The first of two gestures. This gesture has precedence over
/// the other gesture.
/// - second: The second of two gestures.
@inlinable public init(_ first: First, _ second: Second)
/// The type of gesture representing the body of `Self`.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body = Never
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ExclusiveGesture.Value : Sendable where First.Value : Sendable, Second.Value : Sendable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ExclusiveGesture.Value : Equatable where First.Value : Equatable, Second.Value : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ExclusiveGesture<First, Second>.Value, b: ExclusiveGesture<First, Second>.Value) -> Bool
}
/// A schedule for updating a timeline view at explicit points in time.
///
/// You can also use ``TimelineSchedule/explicit(_:)`` to construct this
/// schedule.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct ExplicitTimelineSchedule<Entries> : TimelineSchedule where Entries : Sequence, Entries.Element == Date {
/// Creates a schedule composed of an explicit sequence of dates.
///
/// Use the ``ExplicitTimelineSchedule/entries(from:mode:)`` method
/// to get the sequence of dates.
///
/// - Parameter dates: The sequence of dates at which a timeline view
/// updates. Use a monotonically increasing sequence of dates,
/// and ensure that at least one is in the future.
public init(_ dates: Entries)
/// Provides the sequence of dates with which you initialized the schedule.
///
/// A ``TimelineView`` that you create with a schedule calls this
/// ``TimelineSchedule`` method to ask the schedule when to update its
/// content. The explicit timeline schedule implementation
/// of this method returns the unmodified sequence of dates that you
/// provided when you created the schedule with
/// ``TimelineSchedule/explicit(_:)``. As a result, this particular
/// implementation ignores the `startDate` and `mode` parameters.
///
/// - Parameters:
/// - startDate: The date from which the sequence begins. This
/// particular implementation of the protocol method ignores the start
/// date.
/// - mode: The mode for the update schedule. This particular
/// implementation of the protocol method ignores the mode.
/// - Returns: The sequence of dates that you provided at initialization.
public func entries(from startDate: Date, mode: TimelineScheduleMode) -> Entries
}
/// A shape provider that fills its shape.
///
/// You do not create this type directly, it is the return type of `Shape.fill`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@MainActor @frozen @preconcurrency public struct FillShapeView<Content, Style, Background> : ShapeView where Content : Shape, Style : ShapeStyle, Background : View {
/// The shape that this type draws and provides for other drawing
/// operations.
@MainActor @preconcurrency public var shape: Content
/// The style that fills this view's shape.
@MainActor @preconcurrency public var style: Style
/// The fill style used when filling this view's shape.
@MainActor @preconcurrency public var fillStyle: FillStyle
/// The background shown beneath this view.
@MainActor @preconcurrency public var background: Background
/// Create a FillShapeView.
@MainActor @preconcurrency public init(shape: Content, style: Style, fillStyle: FillStyle, background: Background)
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = Never
}
/// A style for rasterizing vector shapes.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct FillStyle : Equatable {
/// A Boolean value that indicates whether to use the even-odd rule when
/// rendering a shape.
///
/// When `isOEFilled` is `false`, the style uses the non-zero winding number
/// rule.
public var isEOFilled: Bool
/// A Boolean value that indicates whether to apply antialiasing to the
/// edges of a shape.
public var isAntialiased: Bool
/// Creates a new fill style with the specified settings.
///
/// - Parameters:
/// - eoFill: A Boolean value that indicates whether to use the even-odd
/// rule for rendering a shape. Pass `false` to use the non-zero winding
/// number rule instead.
/// - antialiased: A Boolean value that indicates whether to use
/// antialiasing when rendering the edges of a shape.
@inlinable public init(eoFill: Bool = false, antialiased: Bool = true)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: FillStyle, b: FillStyle) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension FillStyle : Sendable {
}
/// The default text variant preference that chooses the largest available
/// variant.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public struct FixedTextVariant : TextVariantPreference, Sendable {
}
/// An environment-dependent font.
///
/// The system resolves a font's value at the time it uses the font in a given
/// environment because ``Font`` is a late-binding token.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct Font : Hashable, Sendable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Font, rhs: Font) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font {
/// A font with the large title text style.
public static let largeTitle: Font
/// A font with the title text style.
public static let title: Font
/// Create a font for second level hierarchical headings.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static let title2: Font
/// Create a font for third level hierarchical headings.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static let title3: Font
/// A font with the headline text style.
public static let headline: Font
/// A font with the subheadline text style.
public static let subheadline: Font
/// A font with the body text style.
public static let body: Font
/// A font with the callout text style.
public static let callout: Font
/// A font with the footnote text style.
public static let footnote: Font
/// A font with the caption text style.
public static let caption: Font
/// Create a font with the alternate caption text style.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static let caption2: Font
/// Gets a system font that uses the specified style, design, and weight.
///
/// Use this method to create a system font that has the specified
/// properties. The following example creates a system font with the
/// ``TextStyle/body`` text style, a ``Design/serif`` design, and
/// a ``Weight/bold`` weight, and applies the font to a ``Text`` view
/// using the ``View/font(_:)`` view modifier:
///
/// Text("Hello").font(.system(.body, design: .serif, weight: .bold))
///
/// The `design` and `weight` parameters are both optional. If you omit
/// either, the system uses a default value for that parameter. The
/// default values are typically ``Design/default`` and ``Weight/regular``,
/// respectively, but might vary depending on the context.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public static func system(_ style: Font.TextStyle, design: Font.Design? = nil, weight: Font.Weight? = nil) -> Font
/// Gets a system font with the given text style and design.
///
/// This function has been deprecated, use the one with nullable `design`
/// and `weight` instead.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use `system(_:design:weight:)` instead.")
public static func system(_ style: Font.TextStyle, design: Font.Design = .default) -> Font
/// A dynamic text style to use for fonts.
public enum TextStyle : CaseIterable, Sendable {
/// The font style for large titles.
case largeTitle
/// The font used for first level hierarchical headings.
case title
/// The font used for second level hierarchical headings.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
case title2
/// The font used for third level hierarchical headings.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
case title3
/// The font used for headings.
case headline
/// The font used for subheadings.
case subheadline
/// The font used for body text.
case body
/// The font used for callouts.
case callout
/// The font used in footnotes.
case footnote
/// The font used for standard captions.
case caption
/// The font used for alternate captions.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
case caption2
/// A collection of all values of this type.
public static var allCases: [Font.TextStyle]
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.TextStyle, b: Font.TextStyle) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias AllCases = [Font.TextStyle]
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font {
/// Adds italics to the font.
public func italic() -> Font
/// Adjusts the font to enable all small capitals.
///
/// See ``Font/lowercaseSmallCaps()`` and ``Font/uppercaseSmallCaps()`` for
/// more details.
public func smallCaps() -> Font
/// Adjusts the font to enable lowercase small capitals.
///
/// This function turns lowercase characters into small capitals for the
/// font. It is generally used for display lines set in large and small
/// caps, such as titles. It may include forms related to small capitals,
/// such as old-style figures.
public func lowercaseSmallCaps() -> Font
/// Adjusts the font to enable uppercase small capitals.
///
/// This feature turns capital characters into small capitals. It is
/// generally used for words which would otherwise be set in all caps, such
/// as acronyms, but which are desired in small-cap form to avoid disrupting
/// the flow of text.
public func uppercaseSmallCaps() -> Font
/// Returns a modified font that uses fixed-width digits, while leaving
/// other characters proportionally spaced.
///
/// This modifier only affects numeric characters, and leaves all other
/// characters unchanged. If the base font doesn't support fixed-width,
/// or _monospace_ digits, the font remains unchanged.
///
/// The following example shows two text fields arranged in a ``VStack``.
/// Both text fields specify the 12-point system font, with the second
/// adding the `monospacedDigit()` modifier to the font. Because the text
/// includes the digit 1, normally a narrow character in proportional
/// fonts, the second text field becomes wider than the first.
///
/// @State private var userText = "Effect of monospacing digits: 111,111."
///
/// var body: some View {
/// VStack {
/// TextField("Proportional", text: $userText)
/// .font(.system(size: 12))
/// TextField("Monospaced", text: $userText)
/// .font(.system(size: 12).monospacedDigit())
/// }
/// .padding()
/// .navigationTitle(Text("Font + monospacedDigit()"))
/// }
///
/// ![A macOS window showing two text fields arranged vertically. Each
/// shows the text Effect of monospacing digits: 111,111. The even spacing
/// of the digit 1 in the second text field causes it to be noticably wider
/// than the first.](Environment-Font-monospacedDigit-1)
///
/// - Returns: A font that uses fixed-width numeric characters.
public func monospacedDigit() -> Font
/// Sets the weight of the font.
public func weight(_ weight: Font.Weight) -> Font
/// Sets the width of the font.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public func width(_ width: Font.Width) -> Font
/// Adds bold styling to the font.
public func bold() -> Font
/// Returns a fixed-width font from the same family as the base font.
///
/// If there's no suitable font face in the same family, SwiftUI
/// returns a default fixed-width font.
///
/// The following example adds the `monospaced()` modifier to the default
/// system font, then applies this font to a ``Text`` view:
///
/// struct ContentView: View {
/// let myFont = Font
/// .system(size: 24)
/// .monospaced()
///
/// var body: some View {
/// Text("Hello, world!")
/// .font(myFont)
/// .padding()
/// .navigationTitle("Monospaced")
/// }
/// }
///
///
/// ![A macOS window showing the text Hello, world in a 24-point
/// fixed-width font.](Environment-Font-monospaced-1)
///
/// SwiftUI may provide different fixed-width replacements for standard
/// user interface fonts (such as ``Font/title``, or a system font created
/// with ``Font/system(_:design:)``) than for those same fonts when created
/// by name with ``Font/custom(_:size:)``.
///
/// The ``View/font(_:)`` modifier applies the font to all text within
/// the view. To mix fixed-width text with other styles in the same
/// `Text` view, use the ``Text/init(_:)-1a4oh`` initializer to use an
/// appropropriately-styled
/// <doc://com.apple.documentation/documentation/Foundation/AttributedString>
/// for the text view's content. You can use the
/// <doc://com.apple.documentation/documentation/Foundation/AttributedString/3796160-init>
/// initializer to provide a Markdown-formatted string containing the
/// backtick-syntax (\`…\`) to apply code voice to specific ranges
/// of the attributed string.
///
/// - Returns: A fixed-width font from the same family as the base font,
/// if one is available, and a default fixed-width font otherwise.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public func monospaced() -> Font
/// Adjusts the line spacing of a font.
///
/// You can change a font's line spacing while maintaining other
/// characteristics of the font by applying this modifier.
/// For example, you can decrease spacing of the ``body`` font by
/// applying the ``Leading/tight`` value to it:
///
/// let myFont = Font.body.leading(.tight)
///
/// The availability of leading adjustments depends on the font. For some
/// fonts, the modifier has no effect and returns the original font.
///
/// - Parameter leading: The line spacing adjustment to apply.
///
/// - Returns: A modified font that uses the specified line spacing, or
/// the original font if it doesn't support line spacing adjustments.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public func leading(_ leading: Font.Leading) -> Font
/// A weight to use for fonts.
@frozen public struct Weight : Hashable {
public static let ultraLight: Font.Weight
public static let thin: Font.Weight
public static let light: Font.Weight
public static let regular: Font.Weight
public static let medium: Font.Weight
public static let semibold: Font.Weight
public static let bold: Font.Weight
public static let heavy: Font.Weight
public static let black: Font.Weight
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.Weight, b: Font.Weight) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A width to use for fonts that have multiple widths.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct Width : Hashable, Sendable {
public var value: CGFloat
public static let compressed: Font.Width
public static let condensed: Font.Width
public static let standard: Font.Width
public static let expanded: Font.Width
public init(_ value: CGFloat)
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.Width, b: Font.Width) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A line spacing adjustment that you can apply to a font.
///
/// Apply one of the `Leading` values to a font using the
/// ``Font/leading(_:)`` method to increase or decrease the line spacing.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public enum Leading : Sendable {
/// The font's default line spacing.
///
/// If you modify a font to use a nonstandard line spacing like
/// ``tight`` or ``loose``, you can use this value to return to
/// the font's default line spacing.
case standard
/// Reduced line spacing.
///
/// This value typically reduces line spacing by 1 point for watchOS
/// and 2 points on other platforms.
case tight
/// Increased line spacing.
///
/// This value typically increases line spacing by 1 point for watchOS
/// and 2 points on other platforms.
case loose
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.Leading, b: Font.Leading) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font {
/// Create a custom font with the given `name` and `size` that scales with
/// the body text style.
public static func custom(_ name: String, size: CGFloat) -> Font
/// Create a custom font with the given `name` and `size` that scales
/// relative to the given `textStyle`.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static func custom(_ name: String, size: CGFloat, relativeTo textStyle: Font.TextStyle) -> Font
/// Create a custom font with the given `name` and a fixed `size` that does
/// not scale with Dynamic Type.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static func custom(_ name: String, fixedSize: CGFloat) -> Font
/// Creates a custom font from a platform font instance.
///
/// Initializing ``Font`` with platform font instance
/// (<doc://com.apple.documentation/documentation/CoreText/CTFont-q6r>) can bridge SwiftUI
/// ``Font`` with <doc://com.apple.documentation/documentation/AppKit/NSFont> or
/// <doc://com.apple.documentation/documentation/UIKit/UIFont>, both of which are
/// toll-free bridged to
/// <doc://com.apple.documentation/documentation/CoreText/CTFont-q6r>. For example:
///
/// // Use native Core Text API to create desired ctFont.
/// let ctFont = CTFontCreateUIFontForLanguage(.system, 12, nil)!
///
/// // Create SwiftUI Text with the CTFont instance.
/// let text = Text("Hello").font(Font(ctFont))
public init(_ font: CTFont)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font {
/// Specifies a system font to use, along with the style, weight, and any
/// design parameters you want applied to the text.
///
/// Use this function to create a system font by specifying the size and
/// weight, and a type design together. The following styles the system font
/// as 17 point, ``Font/Weight/semibold`` text:
///
/// Text("Hello").font(.system(size: 17, weight: .semibold))
///
/// While the following styles the text as 17 point ``Font/Weight/bold``,
/// and applies a `serif` ``Font/Design`` to the system font:
///
/// Text("Hello").font(.system(size: 17, weight: .bold, design: .serif))
///
/// Both `weight` and `design` can be optional. When you do not provide a
/// `weight` or `design`, the system can pick one based on the current
/// context, which may not be ``Font/Weight/regular`` or
/// ``Font/Design/default`` in certain context. The following example styles
/// the text as 17 point system font using ``Font/Design/rounded`` design,
/// while its weight can depend on the current context:
///
/// Text("Hello").font(.system(size: 17, design: .rounded))
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public static func system(size: CGFloat, weight: Font.Weight? = nil, design: Font.Design? = nil) -> Font
/// Specifies a system font to use, along with the style, weight, and any
/// design parameters you want applied to the text.
///
/// Use this function to create a system font by specifying the size and
/// weight, and a type design together. The following styles the system font
/// as 17 point, ``Font/Weight/semibold`` text:
///
/// Text("Hello").font(.system(size: 17, weight: .semibold))
///
/// While the following styles the text as 17 point ``Font/Weight/bold``,
/// and applies a `serif` ``Font/Design`` to the system font:
///
/// Text("Hello").font(.system(size: 17, weight: .bold, design: .serif))
///
/// If you want to use the default ``Font/Weight``
/// (``Font/Weight/regular``), you don't need to specify the `weight` in the
/// method. The following example styles the text as 17 point
/// ``Font/Weight/regular``, and uses a ``Font/Design/rounded`` system font:
///
/// Text("Hello").font(.system(size: 17, design: .rounded))
///
/// This function has been deprecated, use the one with nullable `weight`
/// and `design` instead.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use `system(size:weight:design:)` instead.")
public static func system(size: CGFloat, weight: Font.Weight = .regular, design: Font.Design = .default) -> Font
/// A design to use for fonts.
public enum Design : Hashable, Sendable {
case `default`
@available(watchOS 7.0, *)
case serif
case rounded
@available(watchOS 7.0, *)
case monospaced
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Font.Design, b: Font.Design) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Font.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 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach : View where 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
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where ID == Data.Element.ID, Content : View, Data.Element : Identifiable {
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the identity of the underlying data.
///
/// It's important that the `id` of a data element doesn't change unless you
/// replace the data element with a new data element that has a new
/// identity. If the `id` of a data element changes, the content view
/// generated from that data element loses any current state and animations.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create views dynamically.
/// - content: The view builder that creates views dynamically.
public init(_ data: Data, @ViewBuilder content: @escaping (Data.Element) -> Content)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where Content : View {
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the provided key path to the underlying data's
/// identifier.
///
/// It's important that the `id` of a data element doesn't change, unless
/// SwiftUI considers the data element to have been replaced with a new data
/// element that has a new identity. If the `id` of a data element changes,
/// then the content view generated from that data element will lose any
/// current state and animations.
///
/// - Parameters:
/// - data: The data that the ``ForEach`` instance uses to create views
/// dynamically.
/// - id: The key path to the provided data's identifier.
/// - content: The view builder that creates views dynamically.
public init(_ data: Data, id: KeyPath<Data.Element, ID>, @ViewBuilder content: @escaping (Data.Element) -> Content)
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where Content : View {
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the identity of the underlying data.
///
/// It's important that the `id` of a data element doesn't change unless you
/// replace the data element with a new data element that has a new
/// identity. If the `id` of a data element changes, the content view
/// generated from that data element loses any current state and animations.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create views dynamically.
/// - content: The view builder that creates views dynamically.
public init<C>(_ data: Binding<C>, @ViewBuilder content: @escaping (Binding<C.Element>) -> Content) where Data == LazyMapSequence<C.Indices, (C.Index, ID)>, ID == C.Element.ID, C : MutableCollection, C : RandomAccessCollection, C.Element : Identifiable, C.Index : Hashable
/// Creates an instance that uniquely identifies and creates views across
/// updates based on the identity of the underlying data.
///
/// It's important that the `id` of a data element doesn't change unless you
/// replace the data element with a new data element that has a new
/// identity. If the `id` of a data element changes, the content view
/// generated from that data element loses any current state and animations.
///
/// - Parameters:
/// - data: The identified data that the ``ForEach`` instance uses to
/// create views dynamically.
/// - id: The key path to the provided data's identifier.
/// - content: The view builder that creates views dynamically.
public init<C>(_ data: Binding<C>, id: KeyPath<C.Element, ID>, @ViewBuilder content: @escaping (Binding<C.Element>) -> Content) where Data == LazyMapSequence<C.Indices, (C.Index, ID)>, C : MutableCollection, C : RandomAccessCollection, C.Index : Hashable
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where Data == Range<Int>, ID == Int, Content : View {
/// Creates an instance that computes views on demand over a given constant
/// range.
///
/// The instance only reads the initial value of the provided `data` and
/// doesn't need to identify views across updates. To compute views on
/// demand over a dynamic range, use ``ForEach/init(_:id:content:)``.
///
/// - Parameters:
/// - data: A constant range.
/// - content: The view builder that creates views dynamically.
public init(_ data: Range<Int>, @ViewBuilder content: @escaping (Int) -> Content)
}
/// The foreground style in the current context.
///
/// You can also use ``ShapeStyle/foreground`` to construct this style.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct ForegroundStyle : ShapeStyle {
/// Creates a foreground style instance.
@inlinable public init()
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
/// 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
}
/// 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 an anchor to the container view.
public subscript<T>(anchor: Anchor<T>) -> T { get }
/// The safe area inset of the container view.
public var safeAreaInsets: EdgeInsets { get }
/// Returns the container view's bounds rectangle, converted to a defined
/// coordinate space.
@available(iOS, introduced: 13.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(macOS, introduced: 10.15, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(tvOS, introduced: 13.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(watchOS, introduced: 6.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "use overload that accepts a CoordinateSpaceProtocol instead")
public func frame(in coordinateSpace: CoordinateSpace) -> CGRect
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension GeometryProxy {
/// Returns the given coordinate space's bounds rectangle, converted to the
/// local coordinate space.
public func bounds(of coordinateSpace: NamedCoordinateSpace) -> CGRect?
/// Returns the container view's bounds rectangle, converted to a defined
/// coordinate space.
public func frame(in coordinateSpace: some CoordinateSpaceProtocol) -> CGRect
}
/// A container view that defines its content as a function of its own size and
/// coordinate space.
///
/// This view returns a flexible preferred size to its parent layout.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@MainActor @frozen @preconcurrency public struct GeometryReader<Content> : View where Content : View {
@MainActor @preconcurrency public var content: (GeometryProxy) -> Content
@inlinable nonisolated 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body = Never
}
/// An instance that matches a sequence of events to a gesture, and returns a
/// stream of values for each of its states.
///
/// Create custom gestures by declaring types that conform to the `Gesture`
/// protocol.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol Gesture<Value> {
/// The type representing the gesture's value.
associatedtype Value
/// The type of gesture representing the body of `Self`.
associatedtype Body : Gesture
/// The content and behavior of the gesture.
var body: Self.Body { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Gesture {
/// 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 {
/// 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 {
/// 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 uses the given closure to map over this
/// gesture's value.
public func map<T>(_ body: @escaping (Self.Value) -> T) -> _MapGesture<Self, T>
}
/// Options that control how adding a gesture to a view affects other gestures
/// recognized by the view and its subviews.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct GestureMask : OptionSet {
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public let rawValue: UInt32
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
public init(rawValue: UInt32)
/// Disable all gestures in the subview hierarchy, including the added
/// gesture.
public static let none: GestureMask
/// Enable the added gesture but disable all gestures in the subview
/// hierarchy.
public static let gesture: GestureMask
/// Enable all gestures in the subview hierarchy but disable the added
/// gesture.
public static let subviews: GestureMask
/// Enable both the added gesture as well as all other gestures on the view
/// and its subviews.
public static let all: GestureMask
/// The type of the elements of an array literal.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias RawValue = UInt32
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension GestureMask : Sendable {
}
/// The global coordinate space at the root of the view hierarchy.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct GlobalCoordinateSpace : CoordinateSpaceProtocol {
public init()
/// The resolved coordinate space.
public var coordinateSpace: CoordinateSpace { get }
}
/// 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
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Gradient : Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Gradient : ShapeStyle {
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Gradient {
/// A method of interpolating between the colors in a gradient.
public struct ColorSpace : Hashable, Sendable {
/// Interpolates gradient colors in the output color space.
public static let device: Gradient.ColorSpace
/// Interpolates gradient colors in a perceptual color space.
public static let perceptual: Gradient.ColorSpace
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Gradient.ColorSpace, b: Gradient.ColorSpace) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// Returns a version of the gradient that will use a specified
/// color space for interpolating between its colors.
///
/// Rectangle().fill(.linearGradient(
/// colors: [.white, .blue]).colorSpace(.perceptual))
///
/// - Parameters:
/// - space: The color space the new gradient will use to
/// interpolate its constituent colors.
///
/// - Returns: A new gradient that interpolates its colors in the
/// specified color space.
///
public func colorSpace(_ space: Gradient.ColorSpace) -> AnyGradient
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Gradient.Stop : Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Gradient.Stop : Sendable {
}
/// 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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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 the 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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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 : Sendable {
/// 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
/// Returns a filter that applies `shader` to the color of each
/// source pixel.
///
/// For a shader function to act as a color filter it must have
/// a function signature matching:
///
/// [[ stitchable ]] half4 name(float2 position, half4 color, args...)
///
/// where `position` is the user-space coordinates of the pixel
/// applied to the shader and `color` its source color, as a
/// pre-multiplied color in the destination color space. `args...`
/// should be compatible with the uniform arguments bound to
/// `shader`. The function should return the modified color value.
///
/// - Parameters:
/// - shader: The shader to apply to `self` as a color filter.
///
/// - Returns: A filter that applies the shader as a color
/// filter.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public static func colorShader(_ shader: Shader) -> GraphicsContext.Filter
/// Returns a filter that applies `shader` as a geometric
/// distortion effect on the location of each pixel.
///
/// For a shader function to act as a distortion effect it must
/// have a function signature matching:
///
/// [[ stitchable ]] float2 name(float2 position, args...)
///
/// where `position` is the user-space coordinates of the
/// destination pixel applied to the shader. `args...` should be
/// compatible with the uniform arguments bound to `shader`. The
/// function should return the user-space coordinates of the
/// corresponding source pixel.
///
/// - Parameters:
/// - shader: The shader to apply as a distortion effect.
/// - maxSampleOffset: The maximum distance in each axis
/// between the returned source pixel position and the
/// destination pixel position, for all source pixels.
///
/// - Returns: A new filter that applies the shader as a
/// distortion effect.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public static func distortionShader(_ shader: Shader, maxSampleOffset: CGSize) -> GraphicsContext.Filter
/// Returns a filter that applies `shader` to the contents of
/// the source layer.
///
/// For a shader function to act as a layer effect it must
/// have a function signature matching:
///
/// [[ stitchable ]] half4 name(float2 position,
/// SwiftUI::Layer layer, args...)
///
/// where `position` is the user-space coordinates of the
/// destination pixel applied to the shader, and `layer` is a
/// rasterized subregion of the source layer. `args...` should
/// be compatible with the uniform arguments bound to `shader`.
///
/// The `SwiftUI::Layer` type is defined in the
/// `<SwiftUI/SwiftUI.h>` header file. It exports a single
/// `sample()` function that returns a linearly-filtered pixel
/// value from a position in the source content, as a
/// premultiplied RGBA pixel value:
///
/// namespace SwiftUI {
/// struct Layer {
/// half4 sample(float2 position) const;
/// };
/// };
///
/// The function should return the color mapping to the
/// destination pixel, typically by sampling one or more pixels
/// from `layer` at location(s) derived from `position` and
/// them applying some kind of transformation to produce a new
/// color.
///
/// - Parameters:
/// - shader: The shader to apply as a layer effect.
/// - maxSampleOffset: If the shader function samples from
/// the layer at locations not equal to the destination
/// position, this value must specify the maximum sampling
/// distance in each axis, for all source pixels.
///
/// - Returns: A filter applies the shader as a layer effect.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public static func layerShader(_ shader: Shader, maxSampleOffset: CGSize) -> 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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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 : Sendable {
/// 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 results of
/// querying a shader for each pixel.
///
/// For a shader function to act as a shape fill it must have a
/// function signature matching:
///
/// [[ stitchable ]] half4 name(float2 position, args...)
///
/// where `position` is the user-space coordinates of the pixel applied
/// to the shader, and `args...` should be compatible with the uniform
/// arguments bound to `shader`. The function should return the
/// premultiplied color value in the color space of the destination
/// (typically sRGB).
///
/// - Parameters:
/// - shader: The shader defining the filled colors.
/// - bounds: The rect used to define any `bounds` arguments
/// of the shader.
///
/// - Returns: A shading instance that fills using the shader.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public static func shader(_ shader: Shader, bounds: CGRect = .zero) -> GraphicsContext.Shading
/// Returns a shading instance that fills with a mesh gradient.
///
/// - Parameters:
/// - mesh: The mesh gradient defining the filled colors.
///
/// - Returns: A shading that fills using the mesh gradient.
@available(iOS 18.0, macOS 15.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
public static func meshGradient(_ mesh: MeshGradient) -> 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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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
}
/// Gets 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.
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)
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension GraphicsContext {
/// 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 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension GraphicsContext {
/// Draws `line` into the graphics context.
public func draw(_ line: Text.Layout.Line, options: Text.Layout.DrawingOptions = .init())
/// Draws `run` into the graphics context.
public func draw(_ run: Text.Layout.Run, options: Text.Layout.DrawingOptions = .init())
/// Draws `slice` into the graphics context.
public func draw(_ slice: Text.Layout.RunSlice, options: Text.Layout.DrawingOptions = .init())
}
@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 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 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 Group : View where Content : View {
/// Creates a group of views.
/// - Parameter content: A ``SwiftUI/ViewBuilder`` that produces the views
/// to group.
@inlinable nonisolated public init(@ViewBuilder content: () -> Content)
}
/// A view that arranges its subviews 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 subviews 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)
///
/// > Note: If you need a horizontal stack that conforms to the ``Layout``
/// protocol, like when you want to create a conditional layout using
/// ``AnyLayout``, use ``HStackLayout`` instead.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@MainActor @frozen @preconcurrency 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 subview.
/// - 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 nonisolated 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body = Never
}
/// A horizontal container that you can use in conditional layouts.
///
/// This layout container behaves like an ``HStack``, but conforms to the
/// ``Layout`` protocol so you can use it in the conditional layouts that you
/// construct with ``AnyLayout``. If you don't need a conditional layout, use
/// ``HStack`` instead.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@frozen public struct HStackLayout : Layout {
/// The vertical alignment of subviews.
public var alignment: VerticalAlignment
/// The distance between adjacent subviews.
///
/// Set this value to `nil` to use default distances between subviews.
public var spacing: CGFloat?
/// Creates a horizontal stack with the specified spacing and vertical
/// alignment.
///
/// - Parameters:
/// - alignment: The guide for aligning the subviews in this stack. It
/// has the same vertical screen coordinate for all subviews.
/// - spacing: The distance between adjacent subviews. Set this value
/// to `nil` to use default distances between subviews.
@inlinable public init(alignment: VerticalAlignment = .center, spacing: CGFloat? = nil)
/// The type defining the data to animate.
@available(iOS 16.0, tvOS 16.0, watchOS 9.0, macOS 13.0, *)
public typealias AnimatableData = EmptyAnimatableData
/// Cached values associated with the layout instance.
///
/// If you create a cache for your custom layout, you can use
/// a type alias to define this type as your data storage type.
/// Alternatively, you can refer to the data storage type directly in all
/// the places where you work with the cache.
///
/// See ``makeCache(subviews:)`` for more information.
@available(iOS 16.0, tvOS 16.0, watchOS 9.0, macOS 13.0, *)
public typealias Cache
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension HStackLayout : Sendable {
}
/// 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 {
/// A shape style that maps to the first level of the current
/// content style.
public static let primary: HierarchicalShapeStyle
/// A shape style that maps to the second level of the current
/// content style.
public static let secondary: HierarchicalShapeStyle
/// A shape style that maps to the third level of the current
/// content style.
public static let tertiary: HierarchicalShapeStyle
/// A shape style that maps to the fourth level of the current
/// content style.
public static let quaternary: HierarchicalShapeStyle
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
@available(iOS 16.0, macOS 12.0, macCatalyst 15.0, tvOS 17.0, watchOS 10.0, *)
extension HierarchicalShapeStyle {
/// A shape style that maps to the fifth level of the current
/// content style.
public static let quinary: HierarchicalShapeStyle
}
/// Styles that you can apply to hierarchical shapes.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@frozen public struct HierarchicalShapeStyleModifier<Base> : ShapeStyle where Base : ShapeStyle {
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
/// An alignment position along the horizontal axis.
///
/// Use horizontal alignment guides to tell SwiftUI how to position views
/// relative to one another horizontally, like when you place views vertically
/// in an ``VStack``. The following example demonstrates common built-in
/// horizontal alignments:
///
/// ![Three columns of content. Each column contains a string
/// inside a box with a vertical line above and below the box. The
/// lines are aligned horizontally with the text in a different way for each
/// column. The lines for the left-most string, labeled Leading, align with
/// the left edge of the string. The lines for the middle string, labeled
/// Center, align with the center of the string. The lines for the right-most
/// string, labeled Trailing, align with the right edge of the
/// string.](HorizontalAlignment-1-iOS)
///
/// You can generate the example above by creating a series of columns
/// implemented as vertical stacks, where you configure each stack with a
/// different alignment guide:
///
/// private struct HorizontalAlignmentGallery: View {
/// var body: some View {
/// HStack(spacing: 30) {
/// column(alignment: .leading, text: "Leading")
/// column(alignment: .center, text: "Center")
/// column(alignment: .trailing, text: "Trailing")
/// }
/// .frame(height: 150)
/// }
///
/// private func column(alignment: HorizontalAlignment, text: String) -> some View {
/// VStack(alignment: alignment, spacing: 0) {
/// Color.red.frame(width: 1)
/// Text(text).font(.title).border(.gray)
/// Color.red.frame(width: 1)
/// }
/// }
/// }
///
/// During layout, SwiftUI aligns the views inside each stack by bringing
/// together the specified guides of the affected views. SwiftUI calculates
/// the position of a guide for a particular view based on the characteristics
/// of the view. For example, the ``HorizontalAlignment/center`` guide appears
/// at half the width of the view. You can override the guide calculation for a
/// particular view using the ``View/alignmentGuide(_:computeValue:)``
/// view modifier.
///
/// ### Layout direction
///
/// When a user configures their device to use a left-to-right language like
/// English, the system places the leading alignment on the left and the
/// trailing alignment on the right, as the example from the previous section
/// demonstrates. However, in a right-to-left language, the system reverses
/// these. You can see this by using the ``View/environment(_:_:)`` view
/// modifier to explicitly override the ``EnvironmentValues/layoutDirection``
/// environment value for the view defined above:
///
/// HorizontalAlignmentGallery()
/// .environment(\.layoutDirection, .rightToLeft)
///
/// ![Three columns of content. Each column contains a string
/// inside a box with a vertical line above and below the box. The
/// lines are aligned horizontally with the text in a different way for each
/// column. The lines for the left-most string, labeled Trailing, align with
/// the left edge of the string. The lines for the middle string, labeled
/// Center, align with the center of the string. The lines for the right-most
/// string, labeled Leading, align with the right edge of the
/// string.](HorizontalAlignment-2-iOS)
///
/// This automatic layout adjustment makes it easier to localize your app,
/// but it's still important to test your app for the different locales that
/// you ship into. For more information about the localization process, see
/// <doc://com.apple.documentation/documentation/Xcode/localization>.
///
/// ### Custom alignment guides
///
/// You can create a custom horizontal alignment by creating a type that
/// conforms to the ``AlignmentID`` protocol, and then using that type to
/// initalize a new static property on `HorizontalAlignment`:
///
/// private struct OneQuarterAlignment: AlignmentID {
/// static func defaultValue(in context: ViewDimensions) -> CGFloat {
/// context.width / 4
/// }
/// }
///
/// extension HorizontalAlignment {
/// static let oneQuarter = HorizontalAlignment(OneQuarterAlignment.self)
/// }
///
/// You implement the ``AlignmentID/defaultValue(in:)`` method to calculate
/// a default value for the custom alignment guide. The method receives a
/// ``ViewDimensions`` instance that you can use to calculate an appropriate
/// value based on characteristics of the view. The example above places
/// the guide at one quarter of the width of the view, as measured from the
/// view's origin.
///
/// You can then use the custom alignment guide like any built-in guide. For
/// example, you can use it as the `alignment` parameter to a ``VStack``,
/// or you can change it for a specific view using the
/// ``View/alignmentGuide(_:computeValue:)`` view modifier.
/// Custom alignment guides also automatically reverse in a right-to-left
/// environment, just like built-in guides.
///
/// ### Composite alignment
///
/// Combine a ``VerticalAlignment`` with a `HorizontalAlignment` to create a
/// composite ``Alignment`` that indicates both vertical and horizontal
/// positioning in one value. For example, you could combine your custom
/// `oneQuarter` horizontal alignment from the previous section with a built-in
/// ``VerticalAlignment/center`` vertical alignment to use in a ``ZStack``:
///
/// struct LayeredVerticalStripes: View {
/// var body: some View {
/// ZStack(alignment: Alignment(horizontal: .oneQuarter, vertical: .center)) {
/// verticalStripes(color: .blue)
/// .frame(width: 300, height: 150)
/// verticalStripes(color: .green)
/// .frame(width: 180, height: 80)
/// }
/// }
///
/// private func verticalStripes(color: Color) -> some View {
/// HStack(spacing: 1) {
/// ForEach(0..<4) { _ in color }
/// }
/// }
/// }
///
/// The example above uses widths and heights that generate two mismatched sets
/// of four vertical stripes. The ``ZStack`` centers the two sets vertically and
/// aligns them horizontally one quarter of the way from the leading edge of
/// each set. In a left-to-right locale, this aligns the right edges of the
/// left-most stripes of each set:
///
/// ![Two sets of four rectangles. The first set is blue. The
/// second set is green, is smaller, and is layered on top of the first set.
/// The two sets are centered vertically, but align horizontally at the right
/// edge of each set's left-most rectangle.](HorizontalAlignment-3-iOS)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct HorizontalAlignment : Equatable {
/// Creates a custom horizontal alignment of the specified type.
///
/// Use this initializer to create a custom horizontal alignment. Define
/// an ``AlignmentID`` type, and then use that type to create a new
/// static property on ``HorizontalAlignment``:
///
/// private struct OneQuarterAlignment: AlignmentID {
/// static func defaultValue(in context: ViewDimensions) -> CGFloat {
/// context.width / 4
/// }
/// }
///
/// extension HorizontalAlignment {
/// static let oneQuarter = HorizontalAlignment(OneQuarterAlignment.self)
/// }
///
/// Every horizontal alignment instance that you create needs a unique
/// identifier. For more information, see ``AlignmentID``.
///
/// - Parameter id: The type of an identifier that uniquely identifies a
/// horizontal alignment.
public init(_ id: any AlignmentID.Type)
/// You don't use this property directly.
public let key: AlignmentKey
/// 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 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension HorizontalAlignment {
/// Merges a sequence of explicit alignment values produced by
/// this instance.
///
/// For built-in horizontal alignment types, this method returns the mean
/// of all non-`nil` values.
public func combineExplicit<S>(_ values: S) -> CGFloat? where S : Sequence, S.Element == CGFloat?
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension HorizontalAlignment {
/// A guide that marks the leading edge of the view.
///
/// Use this guide to align the leading edges of views.
/// For a device that uses a left-to-right language, the leading edge
/// is on the left:
///
/// ![A box that contains the word, Leading. Vertical
/// lines appear above and below the box. The lines align horizontally
/// with the left edge of the box.](HorizontalAlignment-leading-1-iOS)
///
/// The following code generates the image above using a ``VStack``:
///
/// struct HorizontalAlignmentLeading: View {
/// var body: some View {
/// VStack(alignment: .leading, spacing: 0) {
/// Color.red.frame(width: 1)
/// Text("Leading").font(.title).border(.gray)
/// Color.red.frame(width: 1)
/// }
/// }
/// }
///
public static let leading: HorizontalAlignment
/// A guide that marks the horizontal center of the view.
///
/// Use this guide to align the centers of views:
///
/// ![A box that contains the word, Center. Vertical
/// lines appear above and below the box. The lines align horizontally
/// with the center of the box.](HorizontalAlignment-center-1-iOS)
///
/// The following code generates the image above using a ``VStack``:
///
/// struct HorizontalAlignmentCenter: View {
/// var body: some View {
/// VStack(alignment: .center, spacing: 0) {
/// Color.red.frame(width: 1)
/// Text("Center").font(.title).border(.gray)
/// Color.red.frame(width: 1)
/// }
/// }
/// }
///
public static let center: HorizontalAlignment
/// A guide that marks the trailing edge of the view.
///
/// Use this guide to align the trailing edges of views.
/// For a device that uses a left-to-right language, the trailing edge
/// is on the right:
///
/// ![A box that contains the word, Trailing. Vertical
/// lines appear above and below the box. The lines align horizontally
/// with the right edge of the box.](HorizontalAlignment-trailing-1-iOS)
///
/// The following code generates the image above using a ``VStack``:
///
/// struct HorizontalAlignmentTrailing: View {
/// var body: some View {
/// VStack(alignment: .trailing, spacing: 0) {
/// Color.red.frame(width: 1)
/// Text("Trailing").font(.title).border(.gray)
/// Color.red.frame(width: 1)
/// }
/// }
/// }
///
public static let trailing: HorizontalAlignment
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension HorizontalAlignment : Sendable {
}
/// A direction on the horizontal axis.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@frozen public enum HorizontalDirection : Int8, CaseIterable, Codable {
/// The leading direction.
case leading
/// The trailing direction.
case trailing
/// An efficient set of horizontal directions.
@frozen public struct Set : OptionSet, Equatable, Hashable {
/// 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 = HorizontalDirection.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 direction.
public static let leading: HorizontalDirection.Set
/// A set containing only the trailing horizontal direction.
public static let trailing: HorizontalDirection.Set
/// A set containing the leading and trailing horizontal directions.
public static let all: HorizontalDirection.Set
/// Creates a set of directions containing only the specified direction.
public init(_ direction: HorizontalDirection)
/// The type of the elements of an array literal.
@available(iOS 18.0, tvOS 18.0, watchOS 11.0, macOS 15.0, visionOS 2.0, *)
public typealias ArrayLiteralElement = HorizontalDirection.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.
@available(iOS 18.0, tvOS 18.0, watchOS 11.0, macOS 15.0, visionOS 2.0, *)
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.
@available(iOS 18.0, tvOS 18.0, watchOS 11.0, macOS 15.0, visionOS 2.0, *)
public typealias AllCases = [HorizontalDirection]
/// 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.
@available(iOS 18.0, tvOS 18.0, watchOS 11.0, macOS 15.0, visionOS 2.0, *)
public typealias RawValue = Int8
/// A collection of all values of this type.
public static var allCases: [HorizontalDirection] { 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 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension HorizontalDirection : Equatable {
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension HorizontalDirection : Hashable {
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension HorizontalDirection : RawRepresentable {
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension HorizontalDirection : Sendable {
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension HorizontalDirection.Set : 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 horizontal edges.
@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 a set of edges containing only the specified horizontal edge.
public init(_ edge: HorizontalEdge)
/// The type of the elements of an array literal.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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 {
}
/// A transition that returns the input view, unmodified, as the output
/// view.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@MainActor @preconcurrency public struct IdentityTransition : Transition {
@MainActor @preconcurrency public init()
/// Gets the current body of the caller.
///
/// `content` is a proxy for the view that will have the modifier
/// represented by `Self` applied to it.
@MainActor @preconcurrency public func body(content: IdentityTransition.Content, phase: TransitionPhase) -> IdentityTransition.Content
/// Returns the properties this transition type has.
///
/// Defaults to `TransitionProperties()`.
@MainActor @preconcurrency public static let properties: TransitionProperties
/// The type of view representing the body.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = IdentityTransition.Content
}
/// 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.](Image-1.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:)`` 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, Sendable {
/// 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 {
/// The modes that SwiftUI uses to resize an image to fit within
/// its containing view.
public enum ResizingMode : Sendable {
/// 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: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// 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 {
/// 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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 {
/// 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 : Sendable {
/// 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: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension 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, 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 {
/// 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. Use
/// [SF Symbols](https://developer.apple.com/design/resources/#sf-symbols)
/// to find symbols and their corresponding names.
///
/// 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 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Image {
/// Creates a system symbol image with a variable value.
///
/// This initializer creates an image using a system-provided symbol. The
/// rendered symbol may alter its appearance to represent the value
/// provided in `variableValue`. Use
/// [SF Symbols](https://developer.apple.com/design/resources/#sf-symbols)
/// (version 4.0 or later) to find system symbols that support variable
/// values and their corresponding names.
///
/// The following example shows the effect of creating the `"chart.bar.fill"`
/// symbol with different values.
///
/// HStack{
/// Image(systemName: "chart.bar.fill", variableValue: 0.3)
/// Image(systemName: "chart.bar.fill", variableValue: 0.6)
/// Image(systemName: "chart.bar.fill", variableValue: 1.0)
/// }
/// .font(.system(.largeTitle))
///
/// ![Three instances of the bar chart symbol, arranged horizontally.
/// The first fills one bar, the second fills two bars, and the last
/// symbol fills all three bars.](Image-3)
///
/// To create a custom symbol image from your app's asset
/// catalog, use ``Image/init(_:variableValue: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.
/// - variableValue: An optional value between `0.0` and `1.0` that
/// the rendered image can use to customize its appearance, if
/// specified. If the symbol doesn't support variable values, this
/// parameter has no effect. Use the SF Symbols app to look up which
/// symbols support variable values.
public init(systemName: String, variableValue: Double?)
/// Creates a labeled image that you can use as content for controls,
/// with a variable value.
///
/// This initializer creates an image using a using a symbol in the
/// specified bundle. The rendered symbol may alter its appearance to
/// represent the value provided in `variableValue`.
///
/// > Note: See WWDC22 session [10158: Adopt variable color in SF
/// Symbols](https://developer.apple.com/wwdc22/10158/) for details
/// on how to create symbols that support variable values.
///
/// - Parameters:
/// - name: The name of the image resource to lookup, as well as
/// the localization key with which to label the image.
/// - variableValue: An optional value between `0.0` and `1.0` that
/// the rendered image can use to customize its appearance, if
/// specified. If the symbol doesn't support variable values, this
/// parameter has no effect.
/// - 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, variableValue: Double?, bundle: Bundle? = nil)
/// Creates a labeled image that you can use as content for controls, with
/// the specified label and variable value.
///
/// This initializer creates an image using a using a symbol in the
/// specified bundle. The rendered symbol may alter its appearance to
/// represent the value provided in `variableValue`.
///
/// > Note: See WWDC22 session [10158: Adopt variable color in SF
/// Symbols](https://developer.apple.com/wwdc22/10158/) for details on
/// how to create symbols that support variable values.
///
/// - Parameters:
/// - name: The name of the image resource to lookup.
/// - variableValue: An optional value between `0.0` and `1.0` that
/// the rendered image can use to customize its appearance, if
/// specified. If the symbol doesn't support variable values, this
/// parameter has no effect.
/// - 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, variableValue: Double?, bundle: Bundle? = nil, label: Text)
/// Creates an unlabeled, decorative image, with a variable value.
///
/// This initializer creates an image using a using a symbol in the
/// specified bundle. The rendered symbol may alter its appearance to
/// represent the value provided in `variableValue`.
///
/// > Note: See WWDC22 session [10158: Adopt variable color in SF
/// Symbols](https://developer.apple.com/wwdc22/10158/) for details on
/// how to create symbols that support variable values.
///
/// SwiftUI ignores this image for accessibility purposes.
///
/// - Parameters:
/// - name: The name of the image resource to lookup.
/// - variableValue: An optional value between `0.0` and `1.0` that
/// the rendered image can use to customize its appearance, if
/// specified. If the symbol doesn't support variable values, this
/// parameter has no effect.
/// - bundle: The bundle to search for the image resource. If
/// `nil`, SwiftUI uses the main `Bundle`. Defaults to `nil`.
///
public init(decorative name: String, variableValue: Double?, bundle: Bundle? = nil)
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Image {
/// Initialize an `Image` with an image resource.
public init(_ resource: ImageResource)
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension Image {
public struct DynamicRange : Hashable, Sendable {
/// Restrict the image content dynamic range to the standard range.
public static let standard: Image.DynamicRange
/// Allow image content to use some extended range. This is
/// appropriate for placing HDR content next to SDR content.
public static let constrainedHigh: Image.DynamicRange
/// Allow image content to use an unrestricted extended range.
public static let high: Image.DynamicRange
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Image.DynamicRange, b: Image.DynamicRange) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// Returns a new image configured with the specified allowed
/// dynamic range.
///
/// The following example enables HDR rendering for a specific
/// image view, assuming that the image has an HDR (ITU-R 2100)
/// color space and the output device supports it:
///
/// Image("hdr-asset").allowedDynamicRange(.high)
///
/// - Parameter range: the requested dynamic range, or nil to
/// restore the default allowed range.
///
/// - Returns: a new image.
public func allowedDynamicRange(_ range: Image.DynamicRange?) -> Image
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Image {
/// Initializes an image of the given size, with contents provided by a
/// custom rendering closure.
///
/// Use this initializer to create an image by calling drawing commands on a
/// ``GraphicsContext`` provided to the `renderer` closure.
///
/// The following example shows a custom image created by passing a
/// `GraphicContext` to draw an ellipse and fill it with a gradient:
///
/// let mySize = CGSize(width: 300, height: 200)
/// let image = Image(size: mySize) { context in
/// context.fill(
/// Path(
/// ellipseIn: CGRect(origin: .zero, size: mySize)),
/// with: .linearGradient(
/// Gradient(colors: [.yellow, .orange]),
/// startPoint: .zero,
/// endPoint: CGPoint(x: mySize.width, y:mySize.height))
/// )
/// }
///
/// ![An ellipse with a gradient that blends from yellow at the upper-
/// left to orange at the bottom-right.](Image-2)
///
/// - Parameters:
/// - size: The size of the newly-created image.
/// - label: The label associated with the image. SwiftUI uses the label
/// for accessibility.
/// - opaque: A Boolean value that indicates whether the image is fully
/// opaque. This may improve performance when `true`. Don't render
/// non-opaque pixels to an image declared as opaque. Defaults to `false`.
/// - colorMode: The working color space and storage format of the image.
/// Defaults to ``ColorRenderingMode/nonLinear``.
/// - renderer: A closure to draw the contents of the image. The closure
/// receives a ``GraphicsContext`` as its parameter.
public init(size: CGSize, label: Text? = nil, opaque: Bool = false, colorMode: ColorRenderingMode = .nonLinear, renderer: @escaping (inout GraphicsContext) -> Void)
}
@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 : Sendable {
/// 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: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A 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 : Hashable, Sendable {
/// 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
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Image.Scale, b: Image.Scale) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body = Never
}
@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 {
}
@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.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.TemplateRenderingMode : Equatable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Image.TemplateRenderingMode : Hashable {
}
/// A shape style that fills a shape by repeating a region of an image.
///
/// You can also use ``ShapeStyle/image(_:sourceRect:scale:)`` to construct this
/// style.
@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)
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
/// 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 `lineWidth`-sized
/// border (aka inner stroke) of `self` with `content`. This is
/// equivalent to insetting `self` by `lineWidth / 2` and stroking the
/// resulting shape with `lineWidth` 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 `lineWidth`-sized
/// border (aka inner stroke) of `self` with the foreground color.
/// This is equivalent to insetting `self` by `lineWidth / 2` and
/// stroking the resulting shape with `lineWidth` as the line-width.
@inlinable public func strokeBorder(lineWidth: CGFloat = 1, antialiased: Bool = true) -> some View
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.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`.
public func strokeBorder<S>(_ content: S = .foreground, style: StrokeStyle, antialiased: Bool = true) -> StrokeBorderShapeView<Self, S, EmptyView> where S : ShapeStyle
/// Returns a view that is the result of filling the `lineWidth`-sized
/// border (aka inner stroke) of `self` with `content`. This is
/// equivalent to insetting `self` by `lineWidth / 2` and stroking the
/// resulting shape with `lineWidth` as the line-width.
public func strokeBorder<S>(_ content: S = .foreground, lineWidth: CGFloat = 1, antialiased: Bool = true) -> StrokeBorderShapeView<Self, S, EmptyView> where S : ShapeStyle
}
/// A container that animates its content with keyframes.
///
/// The `content` closure updates every frame while
/// animating, so avoid performing any expensive operations directly within
/// `content`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@MainActor @preconcurrency public struct KeyframeAnimator<Value, KeyframePath, Content> : View where Value == KeyframePath.Value, KeyframePath : Keyframes, Content : View {
/// Plays the given keyframes when the given trigger value changes, updating
/// the view using the modifiers you apply in `body`.
///
/// Note that the `content` closure will be updated on every frame while
/// animating, so avoid performing any expensive operations directly within
/// `content`.
///
/// If the trigger value changes while animating, the `keyframes` closure
/// will be called with the current interpolated value, and the keyframes
/// that you return define a new animation that replaces the old one. The
/// previous velocity will be preserved, so cubic or spring keyframes will
/// maintain continuity from the previous animation if they do not specify
/// a custom initial velocity.
///
/// When a keyframe animation finishes, the animator will remain at the
/// end value, which becomes the initial value for the next animation.
///
/// - Parameters:
/// - initialValue: The initial value that the keyframes will animate
/// from.
/// - trigger: A value to observe for changes.
/// - content: A view builder closure that takes the interpolated value
/// generated by the keyframes as its single argument.
/// - keyframes: Keyframes defining how the value changes over time. The
/// current value of the animator is the single argument, which is
/// equal to `initialValue` when the view first appears, then is equal
/// to the end value of the previous keyframe animation on subsequent
/// calls.
nonisolated public init(initialValue: Value, trigger: some Equatable, @ViewBuilder content: @escaping (Value) -> Content, @KeyframesBuilder<Value> keyframes: @escaping (Value) -> KeyframePath)
/// Loops the given keyframes continuously, updating
/// the view using the modifiers you apply in `body`.
///
/// Note that the `content` closure will be updated on every frame while
/// animating, so avoid performing any expensive operations directly within
/// `content`.
///
/// - Parameters:
/// - initialValue: The initial value that the keyframes will animate
/// from.
/// - repeating: Whether the keyframes are currently repeating. If false,
/// the value at the beginning of the keyframe timeline will be
/// provided to the content closure.
/// - content: A view builder closure that takes the interpolated value
/// generated by the keyframes as its single argument.
/// - keyframes: Keyframes defining how the value changes over time. The
/// current value of the animator is the single argument, which is
/// equal to `initialValue` when the view first appears, then is equal
/// to the end value of the previous keyframe animation on subsequent
/// calls.
nonisolated public init(initialValue: Value, repeating: Bool = true, @ViewBuilder content: @escaping (Value) -> Content, @KeyframesBuilder<Value> keyframes: @escaping (Value) -> KeyframePath)
/// 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.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = Never
}
/// A description of how a value changes over time, modeled using keyframes.
///
/// Unlike other animations in SwiftUI (using ``Animation``), keyframes
/// don't interpolate between from and to values that SwiftUI provides as
/// state changes. Instead, keyframes fully define the path that a value
/// takes over time using the tracks that make up their body.
///
/// `Keyframes` values are roughly analogous to video clips;
/// they have a set duration, and you can scrub and evaluate them for any
/// time within the duration.
///
/// The `Keyframes` structure also allows you to compute an interpolated
/// value at a specific time, which you can use when integrating keyframes
/// into custom use cases.
///
/// For example, you can use a `Keyframes` instance to define animations for a
/// type conforming to `Animatable:`
///
/// let keyframes = KeyframeTimeline(initialValue: CGPoint.zero) {
/// CubcKeyframe(.init(x: 0, y: 100), duration: 0.3)
/// CubicKeyframe(.init(x: 0, y: 0), duration: 0.7)
/// }
///
/// let value = keyframes.value(time: 0.45
///
/// For animations that involve multiple coordinated changes, you can include
/// multiple nested tracks:
///
/// struct Values {
/// var rotation = Angle.zero
/// var scale = 1.0
/// }
///
/// let keyframes = KeyframeTimeline(initialValue: Values()) {
/// KeyframeTrack(\.rotation) {
/// CubicKeyframe(.zero, duration: 0.2)
/// CubicKeyframe(.degrees(45), duration: 0.3)
/// }
/// KeyframeTrack(\.scale) {
/// CubicKeyframe(value: 1.2, duration: 0.5)
/// CubicKeyframe(value: 0.9, duration: 0.2)
/// CubicKeyframe(value: 1.0, duration: 0.3)
/// }
/// }
///
/// Multiple nested tracks update the initial value in the order that they are
/// declared. This means that if multiple nested plans change the same property
/// of the root value, the value from the last competing track will be used.
///
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct KeyframeTimeline<Value> {
/// Creates a new instance using the initial value and content that you
/// provide.
public init(initialValue: Value, @KeyframesBuilder<Value> content: () -> some Keyframes<Value>)
/// The duration of the content in seconds.
public var duration: TimeInterval { get }
/// Returns the interpolated value at the given time.
public func value(time: Double) -> Value
/// Returns the interpolated value at the given progress in the range zero to one.
public func value(progress: Double) -> Value
}
/// A sequence of keyframes animating a single property of a root type.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct KeyframeTrack<Root, Value, Content> : Keyframes where Value == Content.Value, Content : KeyframeTrackContent {
/// Creates an instance that animates the entire value from the root of the key path.
///
/// - Parameter keyframes: A keyframe collection builder closure containing
/// the keyframes that control the interpolation curve.
public init(@KeyframeTrackContentBuilder<Root> content: () -> Content) where Root == Value
/// Creates an instance that animates the property of the root value
/// at the given key path.
///
/// - Parameter keyPath: The property to animate.
/// - Parameter keyframes: A keyframe collection builder closure containing
/// the keyframes that control the interpolation curve.
public init(_ keyPath: WritableKeyPath<Root, Value>, @KeyframeTrackContentBuilder<Value> content: () -> Content)
/// The type of keyframes representing the body of this type.
///
/// When you create a custom keyframes type, Swift infers this type from your
/// implementation of the required
/// ``Keyframes/body-swift.property`` property.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = Never
}
/// A group of keyframes that define an interpolation curve of an animatable
/// value.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public protocol KeyframeTrackContent<Value> {
associatedtype Value : Animatable = Self.Body.Value
associatedtype Body : KeyframeTrackContent
/// The composition of content that comprise the keyframe track.
@KeyframeTrackContentBuilder<Self.Value> var body: Self.Body { get }
}
/// The builder that creates keyframe track content from the keyframes
/// that you define within a closure.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@resultBuilder public struct KeyframeTrackContentBuilder<Value> where Value : Animatable {
public static func buildExpression<K>(_ expression: K) -> K where Value == K.Value, K : KeyframeTrackContent
public static func buildArray(_ components: [some KeyframeTrackContent<Value>]) -> some KeyframeTrackContent<Value>
public static func buildEither<First, Second>(first component: First) -> KeyframeTrackContentBuilder<Value>.Conditional<Value, First, Second> where Value == First.Value, First : KeyframeTrackContent, Second : KeyframeTrackContent, First.Value == Second.Value
public static func buildEither<First, Second>(second component: Second) -> KeyframeTrackContentBuilder<Value>.Conditional<Value, First, Second> where Value == First.Value, First : KeyframeTrackContent, Second : KeyframeTrackContent, First.Value == Second.Value
public static func buildPartialBlock<K>(first: K) -> K where Value == K.Value, K : KeyframeTrackContent
public static func buildPartialBlock(accumulated: some KeyframeTrackContent<Value>, next: some KeyframeTrackContent<Value>) -> some KeyframeTrackContent<Value>
public static func buildBlock() -> some KeyframeTrackContent<Value>
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension KeyframeTrackContentBuilder {
/// A conditional result from the result builder.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct Conditional<ConditionalValue, First, Second> : KeyframeTrackContent where ConditionalValue == First.Value, First : KeyframeTrackContent, Second : KeyframeTrackContent, First.Value == Second.Value {
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = KeyframeTrackContentBuilder<KeyframeTrackContentBuilder<Value>.Conditional<ConditionalValue, First, Second>.Value>.Conditional<ConditionalValue, First, Second>
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Value = ConditionalValue
}
}
/// A type that defines changes to a value over time.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public protocol Keyframes<Value> {
/// The type of value animated by this keyframes type
associatedtype Value = Self.Body.Value
/// The type of keyframes representing the body of this type.
///
/// When you create a custom keyframes type, Swift infers this type from your
/// implementation of the required
/// ``Keyframes/body-swift.property`` property.
associatedtype Body : Keyframes
/// The composition of content that comprise the keyframes.
@KeyframesBuilder<Self.Value> var body: Self.Body { get }
}
/// A builder that combines keyframe content values into a single value.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@resultBuilder public struct KeyframesBuilder<Value> {
public static func buildExpression<K>(_ expression: K) -> K where Value == K.Value, K : KeyframeTrackContent
public static func buildArray(_ components: [some KeyframeTrackContent<Value>]) -> some KeyframeTrackContent<Value>
public static func buildEither<First, Second>(first component: First) -> KeyframeTrackContentBuilder<Value>.Conditional<Value, First, Second> where Value == First.Value, First : KeyframeTrackContent, Second : KeyframeTrackContent, First.Value == Second.Value
public static func buildEither<First, Second>(second component: Second) -> KeyframeTrackContentBuilder<Value>.Conditional<Value, First, Second> where Value == First.Value, First : KeyframeTrackContent, Second : KeyframeTrackContent, First.Value == Second.Value
public static func buildPartialBlock<K>(first: K) -> K where Value == K.Value, K : KeyframeTrackContent
public static func buildPartialBlock(accumulated: some KeyframeTrackContent<Value>, next: some KeyframeTrackContent<Value>) -> some KeyframeTrackContent<Value>
public static func buildBlock() -> some KeyframeTrackContent<Value> where Value : Animatable
public static func buildFinalResult<Content>(_ component: Content) -> KeyframeTrack<Value, Value, Content> where Value == Content.Value, Content : KeyframeTrackContent
/// Keyframes
public static func buildExpression<Content>(_ expression: Content) -> Content where Value == Content.Value, Content : Keyframes
public static func buildPartialBlock<Content>(first: Content) -> Content where Value == Content.Value, Content : Keyframes
public static func buildPartialBlock(accumulated: some Keyframes<Value>, next: some Keyframes<Value>) -> some Keyframes<Value>
public static func buildBlock() -> some Keyframes<Value>
public static func buildFinalResult<Content>(_ component: Content) -> Content where Value == Content.Value, Content : Keyframes
}
/// A type that defines the geometry of a collection of views.
///
/// You traditionally arrange views in your app's user interface using built-in
/// layout containers like ``HStack`` and ``Grid``. If you need more complex
/// layout behavior, you can define a custom layout container by creating a type
/// that conforms to the `Layout` protocol and implementing its required
/// methods:
///
/// * ``Layout/sizeThatFits(proposal:subviews:cache:)``
/// reports the size of the composite layout view.
/// * ``Layout/placeSubviews(in:proposal:subviews:cache:)``
/// assigns positions to the container's subviews.
///
/// You can define a basic layout type with only these two methods:
///
/// struct BasicVStack: Layout {
/// func sizeThatFits(
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGSize {
/// // Calculate and return the size of the layout container.
/// }
///
/// func placeSubviews(
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) {
/// // Tell each subview where to appear.
/// }
/// }
///
/// Use your layout the same way you use a built-in layout
/// container, by providing a ``ViewBuilder`` with the list of subviews
/// to arrange:
///
/// BasicVStack {
/// Text("A Subview")
/// Text("Another Subview")
/// }
///
/// ### Support additional behaviors
///
/// You can optionally implement other protocol methods and properties to
/// provide more layout container features:
///
/// * Define explicit horizontal and vertical layout guides for the container by
/// implementing ``explicitAlignment(of:in:proposal:subviews:cache:)``
/// for each dimension.
/// * Establish the preferred spacing around the container by implementing
/// ``spacing(subviews:cache:)``.
/// * Indicate the axis of orientation for a container that has characteristics
/// of a stack by implementing the ``layoutProperties-5rb5b`` static property.
/// * Create and manage a cache to store computed values across different
/// layout protocol calls by implementing ``makeCache(subviews:)``.
///
/// The protocol provides default implementations for these symbols
/// if you don't implement them. See each method or property for details.
///
/// ### Add input parameters
///
/// You can define parameters as inputs to the layout, like you might
/// for a ``View``:
///
/// struct BasicVStack: Layout {
/// var alignment: HorizontalAlignment
///
/// // ...
/// }
///
/// Set the parameters at the point where you instantiate the layout:
///
/// BasicVStack(alignment: .leading) {
/// // ...
/// }
///
/// If the layout provides default values for its parameters, you can omit the
/// parameters at the call site, but you might need to keep the parentheses
/// after the name of the layout, depending on how you specify the defaults.
/// For example, suppose you set a default alignment for the basic stack in
/// the parameter declaration:
///
/// struct BasicVStack: Layout {
/// var alignment: HorizontalAlignment = .center
///
/// // ...
/// }
///
/// To instantiate this layout using the default center alignment, you don't
/// have to specify the alignment value, but you do need to add empty
/// parentheses:
///
/// BasicVStack() {
/// // ...
/// }
///
/// The Swift compiler requires the parentheses in this case because of how the
/// layout protocol implements this call site syntax. Specifically, the layout's
/// ``callAsFunction(_:)`` method looks for an initializer with exactly zero
/// input arguments when you omit the parentheses from the call site.
/// You can enable the simpler call site for a layout that doesn't have an
/// implicit initializer of this type by explicitly defining one:
///
/// init() {
/// self.alignment = .center
/// }
///
/// For information about Swift initializers, see
/// [Initialization](https://docs.swift.org/swift-book/LanguageGuide/Initialization.html)
/// in *The Swift Programming Language*.
///
/// ### Interact with subviews through their proxies
///
/// To perform layout, you need information about all of its subviews, which
/// are the views that your container arranges. While your layout can't
/// interact directly with its subviews, it can access a set of subview proxies
/// through the ``Subviews`` collection that each protocol method receives as
/// an input parameter. That type is an alias for the ``LayoutSubviews``
/// collection type, which in turn contains ``LayoutSubview`` instances
/// that are the subview proxies.
///
/// You can get information about each subview from its proxy, like its
/// dimensions and spacing preferences. This enables
/// you to measure subviews before you commit to placing them. You also
/// assign a position to each subview by calling its proxy's
/// ``LayoutSubview/place(at:anchor:proposal:)`` method.
/// Call the method on each subview from within your implementation of the
/// layout's ``placeSubviews(in:proposal:subviews:cache:)`` method.
///
/// ### Access layout values
///
/// Views have layout values that you set with view modifiers.
/// Layout containers can choose to condition their behavior accordingly.
/// For example, a built-in ``HStack`` allocates space to its subviews based
/// in part on the priorities that you set with the ``View/layoutPriority(_:)``
/// view modifier. Your layout container accesses this value for a subview by
/// reading the proxy's ``LayoutSubview/priority`` property.
///
/// You can also create custom layout values by creating a layout key.
/// Set a value on a view with the ``View/layoutValue(key:value:)`` view
/// modifier. Read the corresponding value from the subview's proxy using the
/// key as an index on the subview. For more information about creating,
/// setting, and accessing custom layout values, see ``LayoutValueKey``.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public protocol Layout : Animatable {
/// Properties of a layout container.
///
/// Implement this property in a type that conforms to the ``Layout``
/// protocol to characterize your custom layout container. For example,
/// you can indicate that your layout has a vertical
/// ``LayoutProperties/stackOrientation``:
///
/// extension BasicVStack {
/// static var layoutProperties: LayoutProperties {
/// var properties = LayoutProperties()
/// properties.stackOrientation = .vertical
/// return properties
/// }
/// }
///
/// If you don't implement this property in your custom layout, the protocol
/// provides a default implementation, namely ``layoutProperties-6h7w0``,
/// that returns a ``LayoutProperties`` instance with default values.
static var layoutProperties: LayoutProperties { get }
/// Cached values associated with the layout instance.
///
/// If you create a cache for your custom layout, you can use
/// a type alias to define this type as your data storage type.
/// Alternatively, you can refer to the data storage type directly in all
/// the places where you work with the cache.
///
/// See ``makeCache(subviews:)`` for more information.
associatedtype Cache = Void
/// A collection of proxies for the subviews of a layout view.
///
/// This collection doesn't store views. Instead it stores instances of
/// ``LayoutSubview``, each of which acts as a proxy for one of the
/// views arranged by the layout. Use the proxies to
/// get information about the views, and to tell the views where to
/// appear.
///
/// For more information about the behavior of the underlying
/// collection type, see ``LayoutSubviews``.
typealias Subviews = LayoutSubviews
/// Creates and initializes a cache for a layout instance.
///
/// You can optionally use a cache to preserve calculated values across
/// calls to a layout container's methods. Many layout types don't need
/// a cache, because SwiftUI automatically reuses both the results of
/// calls into the layout and the values that the layout reads from its
/// subviews. Rely on the protocol's default implementation of this method
/// if you don't need a cache.
///
/// However you might find a cache useful when:
///
/// - The layout container repeats complex, intermediate calculations
/// across calls like ``sizeThatFits(proposal:subviews:cache:)``,
/// ``placeSubviews(in:proposal:subviews:cache:)``, and
/// ``explicitAlignment(of:in:proposal:subviews:cache:)``.
/// You might be able to improve performance by calculating values
/// once and storing them in a cache.
/// - The layout container reads many ``LayoutValueKey`` values from
/// subviews. It might be more efficient to do that once and store the
/// results in the cache, rather than rereading the subviews' values before
/// each layout call.
/// - You want to maintain working storage, like temporary Swift arrays,
/// across calls into the layout, to minimize the number of allocation
/// events.
///
/// Only implement a cache if profiling shows that it improves performance.
///
/// ### Initialize a cache
///
/// Implement the `makeCache(subviews:)` method to create a cache.
/// You can add computed values to the cache right away, using information
/// from the `subviews` input parameter, or you can do that later. The
/// methods of the ``Layout`` protocol that can access the cache
/// take the cache as an in-out parameter, which enables you to modify
/// the cache anywhere that you can read it.
///
/// You can use any storage type that makes sense for your layout
/// algorithm, but be sure that you only store data that you derive
/// from the layout and its subviews (lazily, if possible). For this to
/// work correctly, SwiftUI needs to be able to call this method to
/// recreate the cache without changing the layout result.
///
/// When you return a cache from this method, you implicitly define a type
/// for your cache. Be sure to either make the type of the `cache`
/// parameters on your other ``Layout`` protocol methods match, or use
/// a type alias to define the ``Cache`` associated type.
///
/// ### Update the cache
///
/// If the layout container or any of its subviews change, SwiftUI
/// calls the ``updateCache(_:subviews:)`` method so you can
/// modify or invalidate the contents of the
/// cache. The default implementation of that method calls the
/// `makeCache(subviews:)` method to recreate the cache, but you can
/// provide your own implementation of the update method to take an
/// incremental approach, if appropriate.
///
/// - Parameters:
/// - subviews: A collection of proxy instances that represent the
/// views that the container arranges. You can use the proxies in the
/// collection to get information about the subviews as you
/// calculate values to store in the cache.
///
/// - Returns: Storage for calculated data that you share among
/// the methods of your custom layout container.
func makeCache(subviews: Self.Subviews) -> Self.Cache
/// Updates the layout's cache when something changes.
///
/// If your custom layout container creates a cache by implementing the
/// ``makeCache(subviews:)`` method, SwiftUI calls the update method
/// when your layout or its subviews change, giving you an opportunity
/// to modify or invalidate the contents of the cache.
/// The method's default implementation recreates the
/// cache by calling the ``makeCache(subviews:)`` method,
/// but you can provide your own implementation to take an
/// incremental approach, if appropriate.
///
/// - Parameters:
/// - cache: Storage for calculated data that you share among
/// the methods of your custom layout container.
/// - subviews: A collection of proxy instances that represent the
/// views arranged by the container. You can use the proxies in the
/// collection to get information about the subviews as you
/// calculate values to store in the cache.
func updateCache(_ cache: inout Self.Cache, subviews: Self.Subviews)
/// Returns the preferred spacing values of the composite view.
///
/// Implement this method to provide custom spacing preferences
/// for a layout container. The value you return affects
/// the spacing around the container, but it doesn't affect how the
/// container arranges subviews relative to one another inside the
/// container.
///
/// Create a custom ``ViewSpacing`` instance for your container by
/// initializing one with default values, and then merging that with
/// spacing instances of certain subviews. For example, if you define
/// a basic vertical stack that places subviews in a column, you could
/// use the spacing preferences of the subview edges that make
/// contact with the container's edges:
///
/// extension BasicVStack {
/// func spacing(subviews: Subviews, cache: inout ()) -> ViewSpacing {
/// var spacing = ViewSpacing()
///
/// for index in subviews.indices {
/// var edges: Edge.Set = [.leading, .trailing]
/// if index == 0 { edges.formUnion(.top) }
/// if index == subviews.count - 1 { edges.formUnion(.bottom) }
/// spacing.formUnion(subviews[index].spacing, edges: edges)
/// }
///
/// return spacing
/// }
/// }
///
/// In the above example, the first and last subviews contribute to the
/// spacing above and below the container, respectively, while all subviews
/// affect the spacing on the leading and trailing edges.
///
/// If you don't implement this method, the protocol provides a default
/// implementation that merges the spacing preferences across all subviews on all edges.
///
/// - Parameters:
/// - subviews: A collection of proxy instances that represent the
/// views that the container arranges. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// how much spacing the container prefers around it.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
///
/// - Returns: A ``ViewSpacing`` instance that describes the preferred
/// spacing around the container view.
func spacing(subviews: Self.Subviews, cache: inout Self.Cache) -> ViewSpacing
/// Returns the size of the composite view, given a proposed size
/// and the view's subviews.
///
/// Implement this method to tell your custom layout container's parent
/// view how much space the container needs for a set of subviews, given
/// a size proposal. The parent might call this method more than once
/// during a layout pass with different proposed sizes to test the
/// flexibility of the container, using proposals like:
///
/// * The ``ProposedViewSize/zero`` proposal; respond with the
/// layout's minimum size.
/// * The ``ProposedViewSize/infinity`` proposal; respond with the
/// layout's maximum size.
/// * The ``ProposedViewSize/unspecified`` proposal; respond with the
/// layout's ideal size.
///
/// The parent might also choose to test flexibility in one dimension at a
/// time. For example, a horizontal stack might propose a fixed height and
/// an infinite width, and then the same height with a zero width.
///
/// The following example calculates the size for a basic vertical stack
/// that places views in a column, with no spacing between the views:
///
/// private struct BasicVStack: Layout {
/// func sizeThatFits(
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGSize {
/// subviews.reduce(CGSize.zero) { result, subview in
/// let size = subview.sizeThatFits(.unspecified)
/// return CGSize(
/// width: max(result.width, size.width),
/// height: result.height + size.height)
/// }
/// }
///
/// // This layout also needs a placeSubviews() implementation.
/// }
///
/// The implementation asks each subview for its ideal size by calling the
/// ``LayoutSubview/sizeThatFits(_:)`` method with an
/// ``ProposedViewSize/unspecified`` proposed size.
/// It then reduces these values into a single size that represents
/// the maximum subview width and the sum of subview heights.
/// Because this example isn't flexible, it ignores its size proposal
/// input and always returns the same value for a given set of subviews.
///
/// SwiftUI views choose their own size, so the layout engine always
/// uses a value that you return from this method as the actual size of the
/// composite view. That size factors into the construction of the `bounds`
/// input to the ``placeSubviews(in:proposal:subviews:cache:)`` method.
///
/// - Parameters:
/// - proposal: A size proposal for the container. The container's parent
/// view that calls this method might call the method more than once
/// with different proposals to learn more about the container's
/// flexibility before deciding which proposal to use for placement.
/// - subviews: A collection of proxies that represent the
/// views that the container arranges. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// how much space the container needs to display them.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
///
/// - Returns: A size that indicates how much space the container
/// needs to arrange its subviews.
func sizeThatFits(proposal: ProposedViewSize, subviews: Self.Subviews, cache: inout Self.Cache) -> CGSize
/// Assigns positions to each of the layout's subviews.
///
/// SwiftUI calls your implementation of this method to tell your
/// custom layout container to place its subviews. From this method, call
/// the ``LayoutSubview/place(at:anchor:proposal:)`` method on each
/// element in `subviews` to tell the subviews where to appear in the
/// user interface.
///
/// For example, you can create a basic vertical stack that places views
/// in a column, with views horizontally aligned on their leading edge:
///
/// struct BasicVStack: Layout {
/// func placeSubviews(
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) {
/// var point = bounds.origin
/// for subview in subviews {
/// subview.place(at: point, anchor: .topLeading, proposal: .unspecified)
/// point.y += subview.dimensions(in: .unspecified).height
/// }
/// }
///
/// // This layout also needs a sizeThatFits() implementation.
/// }
///
/// The example creates a placement point that starts at the origin of the
/// specified `bounds` input and uses that to place the first subview. It
/// then moves the point in the y dimension by the subview's height,
/// which it reads using the ``LayoutSubview/dimensions(in:)`` method.
/// This prepares the point for the next iteration of the loop. All
/// subview operations use an ``ProposedViewSize/unspecified`` size
/// proposal to indicate that subviews should use and report their ideal
/// size.
///
/// A more complex layout container might add space between subviews
/// according to their ``LayoutSubview/spacing`` preferences, or a
/// fixed space based on input configuration. For example, you can extend
/// the basic vertical stack's placement method to calculate the
/// preferred distances between adjacent subviews and store the results in
/// an array:
///
/// let spacing: [CGFloat] = subviews.indices.dropLast().map { index in
/// subviews[index].spacing.distance(
/// to: subviews[index + 1].spacing,
/// along: .vertical)
/// }
///
/// The spacing's ``ViewSpacing/distance(to:along:)`` method considers the
/// preferences of adjacent views on the edge where they meet. It returns
/// the smallest distance that satisfies both views' preferences for the
/// given edge. For example, if one view prefers at least `2` points on its
/// bottom edge, and the next view prefers at least `8` points on its top
/// edge, the distance method returns `8`, because that's the smallest
/// value that satisfies both preferences.
///
/// Update the placement calculations to use the spacing values:
///
/// var point = bounds.origin
/// for (index, subview) in subviews.enumerated() {
/// if index > 0 { point.y += spacing[index - 1] } // Add spacing.
/// subview.place(at: point, anchor: .topLeading, proposal: .unspecified)
/// point.y += subview.dimensions(in: .unspecified).height
/// }
///
/// Be sure that you use computations during placement that are consistent
/// with those in your implementation of other protocol methods for a given
/// set of inputs. For example, if you add spacing during placement,
/// make sure your implementation of
/// ``sizeThatFits(proposal:subviews:cache:)`` accounts for the extra space.
/// Similarly, if the sizing method returns different values for different
/// size proposals, make sure the placement method responds to its
/// `proposal` input in the same way.
///
/// - Parameters:
/// - bounds: The region that the container view's parent allocates to the
/// container view, specified in the parent's coordinate space.
/// Place all the container's subviews within the region.
/// The size of this region matches a size that your container
/// previously returned from a call to the
/// ``sizeThatFits(proposal:subviews:cache:)`` method.
/// - proposal: The size proposal from which the container generated the
/// size that the parent used to create the `bounds` parameter.
/// The parent might propose more than one size before calling the
/// placement method, but it always uses one of the proposals and the
/// corresponding returned size when placing the container.
/// - subviews: A collection of proxies that represent the
/// views that the container arranges. Use the proxies in the collection
/// to get information about the subviews and to tell the subviews
/// where to appear.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Self.Subviews, cache: inout Self.Cache)
/// Returns the position of the specified horizontal alignment guide along
/// the x axis.
///
/// Implement this method to return a value for the specified alignment
/// guide of a custom layout container. The value you return affects
/// the placement of the container as a whole, but it doesn't affect how the
/// container arranges subviews relative to one another.
///
/// You can use this method to put an alignment guide in a nonstandard
/// position. For example, you can indent the container's leading edge
/// alignment guide by 10 points:
///
/// extension BasicVStack {
/// func explicitAlignment(
/// of guide: HorizontalAlignment,
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGFloat? {
/// if guide == .leading {
/// return bounds.minX + 10
/// }
/// return nil
/// }
/// }
///
/// The above example returns `nil` for other guides to indicate that they
/// don't have an explicit value. A guide without an explicit value behaves
/// as it would for any other view. If you don't implement the
/// method, the protocol's default implementation merges the
/// subviews' guides.
///
/// - Parameters:
/// - guide: The ``HorizontalAlignment`` guide that the method calculates
/// the position of.
/// - bounds: The region that the container view's parent allocates to the
/// container view, specified in the parent's coordinate space.
/// - proposal: A proposed size for the container.
/// - subviews: A collection of proxy instances that represent the
/// views arranged by the container. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// where to place the guide.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
///
/// - Returns: The guide's position relative to the `bounds`.
/// Return `nil` to indicate that the guide doesn't have an explicit
/// value.
func explicitAlignment(of guide: HorizontalAlignment, in bounds: CGRect, proposal: ProposedViewSize, subviews: Self.Subviews, cache: inout Self.Cache) -> CGFloat?
/// Returns the position of the specified vertical alignment guide along
/// the y axis.
///
/// Implement this method to return a value for the specified alignment
/// guide of a custom layout container. The value you return affects
/// the placement of the container as a whole, but it doesn't affect how the
/// container arranges subviews relative to one another.
///
/// You can use this method to put an alignment guide in a nonstandard
/// position. For example, you can raise the container's bottom edge
/// alignment guide by 10 points:
///
/// extension BasicVStack {
/// func explicitAlignment(
/// of guide: VerticalAlignment,
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) -> CGFloat? {
/// if guide == .bottom {
/// return bounds.minY - 10
/// }
/// return nil
/// }
/// }
///
/// The above example returns `nil` for other guides to indicate that they
/// don't have an explicit value. A guide without an explicit value behaves
/// as it would for any other view. If you don't implement the
/// method, the protocol's default implementation merges the
/// subviews' guides.
///
/// - Parameters:
/// - guide: The ``VerticalAlignment`` guide that the method calculates
/// the position of.
/// - bounds: The region that the container view's parent allocates to the
/// container view, specified in the parent's coordinate space.
/// - proposal: A proposed size for the container.
/// - subviews: A collection of proxy instances that represent the
/// views arranged by the container. You can use the proxies in the
/// collection to get information about the subviews as you determine
/// where to place the guide.
/// - cache: Optional storage for calculated data that you can share among
/// the methods of your custom layout container. See
/// ``makeCache(subviews:)`` for details.
///
/// - Returns: The guide's position relative to the `bounds`.
/// Return `nil` to indicate that the guide doesn't have an explicit
/// value.
func explicitAlignment(of guide: VerticalAlignment, in bounds: CGRect, proposal: ProposedViewSize, subviews: Self.Subviews, cache: inout Self.Cache) -> CGFloat?
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Layout {
/// The default property values for a layout.
///
/// If you don't implement the ``layoutProperties-5rb5b`` method in
/// your custom layout, the protocol uses this default implementation
/// instead, which returns a ``LayoutProperties`` instance with
/// default values. The properties instance contains information about the
/// layout container, like a ``LayoutProperties/stackOrientation``
/// property that indicates the container's major axis.
public static var layoutProperties: LayoutProperties { get }
/// Reinitializes a cache to a new value.
///
/// If you don't implement the ``updateCache(_:subviews:)`` method in
/// your custom layout, the protocol uses this default implementation
/// instead, which calls ``makeCache(subviews:)``.
public func updateCache(_ cache: inout Self.Cache, subviews: Self.Subviews)
/// Returns the result of merging the horizontal alignment guides of all
/// subviews.
///
/// If you don't implement the
/// ``explicitAlignment(of:in:proposal:subviews:cache:)`` method in
/// your custom layout, the protocol uses this default implementation
/// instead, which merges the guides of all the subviews.
public func explicitAlignment(of guide: HorizontalAlignment, in bounds: CGRect, proposal: ProposedViewSize, subviews: Self.Subviews, cache: inout Self.Cache) -> CGFloat?
/// Returns the result of merging the vertical alignment guides of all
/// subviews.
///
/// If you don't implement the
/// ``explicitAlignment(of:in:proposal:subviews:cache:)`` method in
/// your custom layout, the protocol uses this default implementation
/// instead, which merges the guides of all the subviews.
public func explicitAlignment(of guide: VerticalAlignment, in bounds: CGRect, proposal: ProposedViewSize, subviews: Self.Subviews, cache: inout Self.Cache) -> CGFloat?
/// Returns the union of all subview spacing.
///
/// If you don't implement the ``spacing(subviews:cache:)`` method in
/// your custom layout, the protocol uses this default implementation
/// instead, which returns the union of the spacing preferences of all
/// the layout's subviews.
public func spacing(subviews: Self.Subviews, cache: inout Self.Cache) -> ViewSpacing
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Layout where Self.Cache == () {
/// Returns the empty value when your layout doesn't require a cache.
///
/// If you don't implement the ``makeCache(subviews:)`` method in
/// your custom layout, the protocol uses this default implementation
/// instead, which returns an empty value.
public func makeCache(subviews: Self.Subviews) -> Self.Cache
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Layout {
/// Combines the specified views into a single composite view using
/// the layout algorithms of the custom layout container.
///
/// Don't call this method directly. SwiftUI calls it when you
/// instantiate a custom layout that conforms to the ``Layout``
/// protocol:
///
/// BasicVStack { // Implicitly calls callAsFunction.
/// Text("A View")
/// Text("Another View")
/// }
///
/// For information about how Swift uses the `callAsFunction()` method to
/// simplify call site syntax, see
/// [Methods with Special Names](https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID622)
/// in *The Swift Programming Language*.
///
/// - Parameter content: A ``ViewBuilder`` that contains the views to
/// lay out.
///
/// - Returns: A composite view that combines all the input views.
public func callAsFunction<V>(@ViewBuilder _ content: () -> V) -> some View where V : View
}
/// A direction in which SwiftUI can lay out content.
///
/// SwiftUI supports both left-to-right and right-to-left directions
/// for laying out content to support different languages and locales.
/// The system sets the value based on the user's locale, but
/// you can also use the ``View/environment(_:_:)`` modifier
/// to override the direction for a view and its child views:
///
/// MyView()
/// .environment(\.layoutDirection, .rightToLeft)
///
/// You can also read the ``EnvironmentValues/layoutDirection`` environment
/// value to find out which direction applies to a particular environment.
/// However, in many cases, you don't need to take any action based on this
/// value. SwiftUI horizontally flips the x position of each view within its
/// parent, so layout calculations automatically produce the desired effect
/// for both modes without any changes.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum LayoutDirection : Hashable, CaseIterable, Sendable {
/// A left-to-right layout direction.
case leftToRight
/// A right-to-left layout direction.
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: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// A type that can represent a collection of all values of this type.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A description of what should happen when the layout direction changes.
///
/// A `LayoutDirectionBehavior` can be used with the `layoutDirectionBehavior`
/// view modifier or the `layoutDirectionBehavior` property of `Shape`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public enum LayoutDirectionBehavior : Hashable, Sendable {
/// A behavior that doesn't mirror when the layout direction changes.
case fixed
/// A behavior that mirrors when the layout direction has the specified
/// value.
///
/// If you develop your view or shape in an LTR context, you can use
/// `.mirrors(in: .rightToLeft)` (which is equivalent to `.mirrors`) to
/// mirror your content when the layout direction is RTL (and keep the
/// original version in LTR). If you developer in an RTL context, you can
/// use `.mirrors(in: .leftToRight)` to mirror your content when the layout
/// direction is LTR (and keep the original version in RTL).
case mirrors(in: LayoutDirection)
/// A behavior that mirrors when the layout direction is right-to-left.
public static var mirrors: LayoutDirectionBehavior { get }
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// 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: LayoutDirectionBehavior, b: LayoutDirectionBehavior) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// Layout-specific properties of a layout container.
///
/// This structure contains configuration information that's
/// applicable to a layout container. For example, the ``stackOrientation``
/// value indicates the layout's primary axis, if any.
///
/// You can use an instance of this type to characterize a custom layout
/// container, which is a type that conforms to the ``Layout`` protocol.
/// Implement the protocol's ``Layout/layoutProperties-5rb5b`` property
/// to return an instance. For example, you can indicate that your layout
/// has a vertical stack orientation:
///
/// extension BasicVStack {
/// static var layoutProperties: LayoutProperties {
/// var properties = LayoutProperties()
/// properties.stackOrientation = .vertical
/// return properties
/// }
/// }
///
/// If you don't implement the property in your custom layout, the protocol
/// provides a default implementation that returns a `LayoutProperties`
/// instance with default values.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct LayoutProperties : Sendable {
/// Creates a default set of properties.
///
/// Use a layout properties instance to provide information about
/// a type that conforms to the ``Layout`` protocol. For example, you
/// can create a layout properties instance in your layout's implementation
/// of the ``Layout/layoutProperties-5rb5b`` method, and use it to
/// indicate that the layout has a ``Axis/vertical`` orientation:
///
/// extension BasicVStack {
/// static var layoutProperties: LayoutProperties {
/// var properties = LayoutProperties()
/// properties.stackOrientation = .vertical
/// return properties
/// }
/// }
///
public init()
/// The orientation of the containing stack-like container.
///
/// Certain views alter their behavior based on the stack orientation
/// of the container that they appear in. For example, ``Spacer`` and
/// ``Divider`` align their major axis to match that of their container.
///
/// Set the orientation for your custom layout container by returning a
/// configured ``LayoutProperties`` instance from your ``Layout``
/// type's implementation of the ``Layout/layoutProperties-5rb5b``
/// method. For example, you can indicate that your layout has a
/// ``Axis/vertical`` major axis:
///
/// extension BasicVStack {
/// static var layoutProperties: LayoutProperties {
/// var properties = LayoutProperties()
/// properties.stackOrientation = .vertical
/// return properties
/// }
/// }
///
/// A value of `nil`, which is the default when you don't specify a
/// value, indicates an unknown orientation, or that a layout isn't
/// one-dimensional.
public var stackOrientation: Axis?
}
/// A proxy that represents one subview of a layout.
///
/// This type acts as a proxy for a view that your custom layout container
/// places in the user interface. ``Layout`` protocol methods
/// receive a ``LayoutSubviews`` collection that contains exactly one
/// proxy for each of the subviews arranged by your container.
///
/// Use a proxy to get information about the associated subview, like its
/// dimensions, layout priority, or custom layout values. You also use the
/// proxy to tell its corresponding subview where to appear by calling the
/// proxy's ``LayoutSubview/place(at:anchor:proposal:)`` method.
/// Do this once for each subview from your implementation of the layout's
/// ``Layout/placeSubviews(in:proposal:subviews:cache:)`` method.
///
/// You can read custom layout values associated with a subview
/// by using the property's key as an index on the subview. For more
/// information about defining, setting, and reading custom values,
/// see ``LayoutValueKey``.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct LayoutSubview : Equatable {
/// Gets the value for the subview that's associated with the specified key.
///
/// If you define a custom layout value using ``LayoutValueKey``,
/// you can read the key's associated value for a given subview in
/// a layout container by indexing the container's subviews with
/// the key type. For example, if you define a `Flexibility` key
/// type, you can put the associated values of all the layout's
/// subviews into an array:
///
/// let flexibilities = subviews.map { subview in
/// subview[Flexibility.self]
/// }
///
/// For more information about creating a custom layout, see ``Layout``.
public subscript<K>(key: K.Type) -> K.Value where K : LayoutValueKey { get }
/// The layout priority of the subview.
///
/// If you define a custom layout type using the ``Layout``
/// protocol, you can read this value from subviews and use the value
/// when deciding how to assign space to subviews. For example, you
/// can read all of the subview priorities into an array before
/// placing the subviews in a custom layout type called `BasicVStack`:
///
/// extension BasicVStack {
/// func placeSubviews(
/// in bounds: CGRect,
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout ()
/// ) {
/// let priorities = subviews.map { subview in
/// subview.priority
/// }
///
/// // Place views, based on priorities.
/// }
/// }
///
/// Set the layout priority for a view that appears in your layout by
/// applying the ``View/layoutPriority(_:)`` view modifier. For example,
/// you can assign two different priorities to views that you arrange
/// with `BasicVStack`:
///
/// BasicVStack {
/// Text("High priority")
/// .layoutPriority(10)
/// Text("Low priority")
/// .layoutPriority(1)
/// }
///
public var priority: Double { get }
/// Asks the subview for its size.
///
/// Use this method as a convenience to get the ``ViewDimensions/width``
/// and ``ViewDimensions/height`` properties of the ``ViewDimensions``
/// instance returned by the ``dimensions(in:)`` method, reported as a
/// <doc://com.apple.documentation/documentation/CoreFoundation/CGSize>
/// instance.
///
/// - Parameter proposal: A proposed size for the subview. In SwiftUI,
/// views choose their own size, but can take a size proposal from
/// their parent view into account when doing so.
///
/// - Returns: The size that the subview chooses for itself, given the
/// proposal from its container view.
public func sizeThatFits(_ proposal: ProposedViewSize) -> CGSize
/// Asks the subview for its dimensions and alignment guides.
///
/// Call this method to ask a subview of a custom ``Layout`` type
/// about its size and alignment properties. You can call it from
/// your implementation of any of that protocol's methods, like
/// ``Layout/placeSubviews(in:proposal:subviews:cache:)`` or
/// ``Layout/sizeThatFits(proposal:subviews:cache:)``, to get
/// information for your layout calculations.
///
/// When you call this method, you propose a size using the `proposal`
/// parameter. The subview can choose its own size, but might take the
/// proposal into account. You can call this method more than
/// once with different proposals to find out if the view is flexible.
/// For example, you can propose:
///
/// * ``ProposedViewSize/zero`` to get the subview's minimum size.
/// * ``ProposedViewSize/infinity`` to get the subview's maximum size.
/// * ``ProposedViewSize/unspecified`` to get the subview's ideal size.
///
/// If you need only the view's height and width, you can use the
/// ``sizeThatFits(_:)`` method instead.
///
/// - Parameter proposal: A proposed size for the subview. In SwiftUI,
/// views choose their own size, but can take a size proposal from
/// their parent view into account when doing so.
///
/// - Returns: A ``ViewDimensions`` instance that includes a height
/// and width, as well as a set of alignment guides.
public func dimensions(in proposal: ProposedViewSize) -> ViewDimensions
/// The subviews's preferred spacing values.
///
/// This ``ViewSpacing`` instance indicates how much space a subview
/// in a custom layout prefers to have between it and the next view.
/// It contains preferences for all edges, and might take into account
/// the type of both this and the adjacent view. If your ``Layout`` type
/// places subviews based on spacing preferences, use this instance
/// to compute a distance between this subview and the next. See
/// ``Layout/placeSubviews(in:proposal:subviews:cache:)`` for an
/// example.
///
/// You can also merge this instance with instances from other subviews
/// to construct a new instance that's suitable for the subviews' container.
/// See ``Layout/spacing(subviews:cache:)``.
public var spacing: ViewSpacing { get }
/// Assigns a position and proposed size to the subview.
///
/// Call this method from your implementation of the ``Layout``
/// protocol's ``Layout/placeSubviews(in:proposal:subviews:cache:)``
/// method for each subview arranged by the layout.
/// Provide a position within the container's bounds where the subview
/// should appear, and an anchor that indicates which part of the subview
/// appears at that point.
///
/// Include a proposed size that the subview can take into account when
/// sizing itself. To learn the subview's size for a given proposal before
/// calling this method, you can call the ``dimensions(in:)`` or
/// ``sizeThatFits(_:)`` method on the subview with the same proposal.
/// That enables you to know subview sizes before committing to subview
/// positions.
///
/// > Important: Call this method only from within your
/// ``Layout`` type's implementation of the
/// ``Layout/placeSubviews(in:proposal:subviews:cache:)`` method.
///
/// If you call this method more than once for a subview, the last call
/// takes precedence. If you don't call this method for a subview, the
/// subview appears at the center of its layout container and uses the
/// layout container's size proposal.
///
/// - Parameters:
/// - position: The place where the anchor of the subview should
/// appear in its container view, relative to container's bounds.
/// - anchor: The unit point on the subview that appears at `position`.
/// You can use a built-in point, like ``UnitPoint/center``, or
/// you can create a custom ``UnitPoint``.
/// - proposal: A proposed size for the subview. In SwiftUI,
/// views choose their own size, but can take a size proposal from
/// their parent view into account when doing so.
public func place(at position: CGPoint, anchor: UnitPoint = .topLeading, proposal: ProposedViewSize)
/// 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: LayoutSubview, b: LayoutSubview) -> Bool
}
/// A collection of proxy values that represent the subviews of a layout view.
///
/// You receive a `LayoutSubviews` input to your implementations of
/// ``Layout`` protocol methods, like
/// ``Layout/placeSubviews(in:proposal:subviews:cache:)`` and
/// ``Layout/sizeThatFits(proposal:subviews:cache:)``. The `subviews`
/// parameter (which the protocol aliases to the ``Layout/Subviews`` type)
/// is a collection that contains proxies for the layout's subviews (of type
/// ``LayoutSubview``). The proxies appear in the collection in the same
/// order that they appear in the ``ViewBuilder`` input to the layout
/// container. Use the proxies to perform layout operations.
///
/// Access the proxies in the collection as you would the contents of any
/// Swift random-access collection. For example, you can enumerate all of the
/// subviews and their indices to inspect or operate on them:
///
/// for (index, subview) in subviews.enumerated() {
/// // ...
/// }
///
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct LayoutSubviews : Equatable, RandomAccessCollection, Sendable {
/// A type that contains a subsequence of proxy values.
public typealias SubSequence = LayoutSubviews
/// A type that contains a proxy value.
public typealias Element = LayoutSubview
/// A type that you can use to index proxy values.
public typealias Index = Int
/// The layout direction inherited by the container view.
///
/// SwiftUI supports both left-to-right and right-to-left directions.
/// Read this property within a custom layout container
/// to find out which environment the container is in.
///
/// In most cases, you don't need to take any action based on this
/// value. SwiftUI horizontally flips the x position of each view within its
/// parent when the mode switches, so layout calculations automatically
/// produce the desired effect for both directions.
public var layoutDirection: LayoutDirection
/// The index of the first subview.
public var startIndex: Int { get }
/// An index that's one higher than the last subview.
public var endIndex: Int { get }
/// Gets the subview proxy at a specified index.
public subscript(index: Int) -> LayoutSubviews.Element { get }
/// Gets the subview proxies in the specified range.
public subscript(bounds: Range<Int>) -> LayoutSubviews { get }
/// Gets the subview proxies with the specified indicies.
public subscript<S>(indices: S) -> LayoutSubviews where S : Sequence, S.Element == Int { 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 == (lhs: LayoutSubviews, rhs: LayoutSubviews) -> Bool
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
@available(iOS 16.0, tvOS 16.0, watchOS 9.0, macOS 13.0, *)
public typealias Indices = Range<LayoutSubviews.Index>
/// 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.
@available(iOS 16.0, tvOS 16.0, watchOS 9.0, macOS 13.0, *)
public typealias Iterator = IndexingIterator<LayoutSubviews>
}
/// A key for accessing a layout value of a layout container's subviews.
///
/// If you create a custom layout by defining a type that conforms to the
/// ``Layout`` protocol, you can also create custom layout values
/// that you set on individual views, and that your container view can access
/// to guide its layout behavior. Your custom values resemble
/// the built-in layout values that you set with view modifiers
/// like ``View/layoutPriority(_:)`` and ``View/zIndex(_:)``, but have a
/// purpose that you define.
///
/// To create a custom layout value, define a type that conforms to the
/// `LayoutValueKey` protocol and implement the one required property that
/// returns the default value of the property. For example, you can create
/// a property that defines an amount of flexibility for a view, defined as
/// an optional floating point number with a default value of `nil`:
///
/// private struct Flexibility: LayoutValueKey {
/// static let defaultValue: CGFloat? = nil
/// }
///
/// The Swift compiler infers this particular key's associated type as an
/// optional <doc://com.apple.documentation/documentation/CoreFoundation/CGFloat>
/// from this definition.
///
/// ### Set a value on a view
///
/// Set the value on a view by adding the ``View/layoutValue(key:value:)``
/// view modifier to the view. To make your custom value easier to work
/// with, you can do this in a convenience modifier in an extension of the
/// ``View`` protocol:
///
/// extension View {
/// func layoutFlexibility(_ value: CGFloat?) -> some View {
/// layoutValue(key: Flexibility.self, value: value)
/// }
/// }
///
/// Use your modifier to set the value on any views that need a nondefault
/// value:
///
/// BasicVStack {
/// Text("One View")
/// Text("Another View")
/// .layoutFlexibility(3)
/// }
///
/// Any view that you don't explicitly set a value for uses the default
/// value, as with the first ``Text`` view, above.
///
/// ### Retrieve a value during layout
///
/// Access a custom layout value using the key as an index
/// on subview's proxy (an instance of ``LayoutSubview``)
/// and use the value to make decisions about sizing, placement, or other
/// layout operations. For example, you might read the flexibility value
/// in your layout view's ``LayoutSubview/sizeThatFits(_:)`` method, and
/// adjust your size calculations accordingly:
///
/// extension BasicVStack {
/// func sizeThatFits(
/// proposal: ProposedViewSize,
/// subviews: Subviews,
/// cache: inout Void
/// ) -> CGSize {
///
/// // Map the flexibility property of each subview into an array.
/// let flexibilities = subviews.map { subview in
/// subview[Flexibility.self]
/// }
///
/// // Calculate and return the size of the layout container.
/// // ...
/// }
/// }
///
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public protocol LayoutValueKey {
/// The type of the key's value.
///
/// Swift typically infers this type from your implementation of the
/// ``defaultValue`` property, so you don't have to define it explicitly.
associatedtype Value
/// The default value of the key.
///
/// Implement the `defaultValue` property for a type that conforms to the
/// ``LayoutValueKey`` protocol. For example, you can create a `Flexibility`
/// layout value that defaults to `nil`:
///
/// private struct Flexibility: LayoutValueKey {
/// static let defaultValue: CGFloat? = nil
/// }
///
/// The type that you declare for the `defaultValue` sets the layout
/// key's ``Value`` associated type. The Swift compiler infers the key's
/// associated type in the above example as an optional
/// <doc://com.apple.documentation/documentation/CoreFoundation/CGFloat>.
///
/// Any view that you don't explicitly set a value for uses the default
/// value. Override the default value for a view using the
/// ``View/layoutValue(key:value:)`` modifier.
static var defaultValue: Self.Value { get }
}
/// The Accessibility Bold Text user setting options.
///
/// The app can't override the user's choice before iOS 16, tvOS 16 or
/// watchOS 9.0.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum LegibilityWeight : Hashable, Sendable {
/// 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: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A 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, *)
@MainActor @frozen @preconcurrency public struct LinearGradient : ShapeStyle, View, Sendable {
/// Creates a linear gradient from a base gradient.
nonisolated public init(gradient: Gradient, startPoint: UnitPoint, endPoint: UnitPoint)
/// Creates a linear gradient from a collection of colors.
nonisolated public init(colors: [Color], startPoint: UnitPoint, endPoint: UnitPoint)
/// Creates a linear gradient from a collection of color stops.
nonisolated 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
/// A keyframe that uses simple linear interpolation.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct LinearKeyframe<Value> : KeyframeTrackContent where Value : Animatable {
/// Creates a new keyframe using the given value and timestamp.
///
/// - Parameters:
/// - to: The value of the keyframe.
/// - duration: The duration of the segment defined by this keyframe.
/// - timingCurve: A unit curve that controls the speed of interpolation.
public init(_ to: Value, duration: TimeInterval, timingCurve: UnitCurve = .linear)
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = LinearKeyframe<Value>
}
/// The local coordinate space of the current view.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct LocalCoordinateSpace : CoordinateSpaceProtocol {
public init()
/// The resolved coordinate space.
public var coordinateSpace: CoordinateSpace { 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 formatted representation of a nonstring type
/// supported by a corresponding format style.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// The following example shows how to use a string interpolation to
/// format a
/// <doc://com.apple.documentation/documentation/Foundation/Date>
/// with a
/// <doc://com.apple.documentation/documentation/Foundation/Date/FormatStyle> and
/// append it to static text. The resulting interpolation implicitly
/// creates a ``LocalizedStringKey``, which a ``Text`` uses to provide
/// its content.
///
/// Text("The time is \(myDate, format: Date.FormatStyle(date: .omitted, time:.complete))")
///
/// - Parameters:
/// - input: The instance to format and append.
/// - format: A format style to use when converting `input` into a string
/// representation.
@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 the formatted representation of a nonstring type
/// supported by a corresponding format style.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// The following example shows how to use a string interpolation to
/// format a
/// <doc://com.apple.documentation/documentation/Foundation/Date>
/// with a
/// <doc://com.apple.documentation/documentation/Foundation/Date/FormatStyle> and
/// append it to static text. The resulting interpolation implicitly
/// creates a ``LocalizedStringKey``, which a ``Text`` uses to provide
/// its content.
///
/// Text("The time is \(myDate, format: Date.FormatStyle(date: .omitted, time:.complete).attributedStyle)")
///
/// - Parameters:
/// - input: The instance to format and append.
/// - format: A format style to use when converting `input` into an attributed
/// string representation.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func appendInterpolation<F>(_ input: F.FormatInput, format: F) where F : FormatStyle, F.FormatInput : Equatable, F.FormatOutput == AttributedString
/// 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 attributed string 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 string interpolation to
/// format an
/// <doc://com.apple.documentation/documentation/Foundation/AttributedString>
/// and append it to static text. The resulting interpolation implicitly
/// creates a ``LocalizedStringKey``, which a ``Text`` view uses to provide
/// its content.
///
/// struct ContentView: View {
///
/// var nextDate: AttributedString {
/// var result = Calendar.current
/// .nextWeekend(startingAfter: Date.now)!
/// .start
/// .formatted(
/// .dateTime
/// .month(.wide)
/// .day()
/// .attributed
/// )
/// result.backgroundColor = .green
/// result.foregroundColor = .white
/// return result
/// }
///
/// var body: some View {
/// Text("Our next catch-up is on \(nextDate)!")
/// }
/// }
///
/// For this example, assume that the app runs on a device set to a
/// Russian locale, and has the following entry in a Russian-localized
/// `Localizable.strings` file:
///
/// "Our next catch-up is on %@!" = "Наша следующая встреча состоится %@!";
///
/// The attributed string `nextDate` replaces the format specifier
/// `%@`, maintaining its color and date-formatting attributes, when
/// the ``Text`` view renders its contents:
///
/// ![A text view with Russian text, ending with a date that uses white
/// text on a green
/// background.](LocalizedStringKey-AttributedString-Russian)
///
/// - Parameter attributedString: The attributed string 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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`.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias ExtendedGraphemeClusterLiteralType = String
/// A type that represents a string literal.
///
/// Valid types for `StringLiteralType` are `String` and `StaticString`.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias StringLiteralType = String
/// A type that represents a Unicode scalar literal.
///
/// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,
/// `Character`, `String`, and `StaticString`.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias UnicodeScalarLiteralType = String
}
@available(iOS 16.0, macOS 13, tvOS 16.0, watchOS 9.0, *)
extension LocalizedStringKey.StringInterpolation {
/// Appends the localized string resource to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameters:
/// - value: The localized string resource to append.
@available(iOS 16.0, macOS 13, tvOS 16.0, watchOS 9.0, *)
public mutating func appendInterpolation(_ resource: LocalizedStringResource)
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension LocalizedStringKey.StringInterpolation {
/// Appends a localized description of a color for accessibility
/// to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameters:
/// - color: the color being described.
public mutating func appendInterpolation(accessibilityName color: Color)
}
@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)
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension LocalizedStringKey.StringInterpolation {
/// Appends a timer interval to a string interpolation.
///
/// Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// - Parameters:
/// - timerInterval: The interval between where to run the timer.
/// - pauseTime: If present, the date at which to pause the timer.
/// The default is `nil` which indicates to never pause.
/// - countsDown: Whether to count up or down. The default is `true`.
/// - showsHours: Whether to include an hours component if there are
/// more than 60 minutes left on the timer. The default is `true`.
public mutating func appendInterpolation(timerInterval: ClosedRange<Date>, pauseTime: Date? = nil, countsDown: Bool = true, showsHours: Bool = true)
}
extension LocalizedStringKey.StringInterpolation {
/// Appends a text view that displays the current system time as defined by the
/// given format style, keeping the text up to date as time progresses.
///
/// Use this initializer to create a text view that updates as time progresses, just
/// like ``init(_:style:)``, but with the flexibility of Foundation's `FormatStyle`
/// protocol.
///
/// In the following example, the first ``Text`` view presents the offset to
/// `startDate`, whereas the second view displays a stopwatch counting from
/// `startDate`. Both views are kept up to date as time progresses.
///
/// Text(.currentDate, format: .offset(to: startDate))
/// Text(.currentDate, format: .stopwatch(startingAt: startDate))
///
/// - Note: Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// ## Redaction for Reduced Luminance
///
/// When the text is displayed with reduced luminance and frame rate, it
/// automatically modifies the `format` or its output so it never shows outdated
/// information.
///
/// If the `format` is known to SwiftUI and allows removing units or fields, SwiftUI
/// removes parts that change more frequently than the frame rate allows. E.g. a
/// string like _13 minutes, 22 seconds_ would change to just `13 minutes`.
///
/// Otherwise, SwiftUI inspects the `durationField`, `dateField`, and `measurement`
/// attributes on the formatted output to determine which ranges need to be
/// redacted. If these attributes are not present, all digits are redacted using
/// dashes.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func appendInterpolation<V, F>(_ source: TimeDataSource<V>, format: F) where V == F.FormatInput, F : DiscreteFormatStyle, F.FormatOutput == AttributedString
/// Appends a text view that displays the current system time as defined by the
/// given format style, keeping the text up to date as time progresses.
///
/// Use this initializer to create a text view that updates as time progresses, just
/// like ``init(_:style:)``, but with the flexibility of Foundation's `FormatStyle`
/// protocol.
///
/// In the following example, the first ``Text`` view presents the current date and
/// time, whereas the second view displays a soccer clock counting from `startDate`.
/// Both views are kept up to date as time progresses.
///
/// Text(.currentDate, format: .dateTime)
/// Text(.durationOffset(to: startDate), format: .time(pattern: .minuteSecond))
///
/// - Note: Don't call this method directly; it's used by the compiler when
/// interpreting string interpolations.
///
/// ## Redaction for Reduced Luminance
///
/// When the text is displayed with reduced luminance and frame rate, it
/// automatically modifies the `format` or its output so it never shows outdated
/// information.
///
/// If the `format` is known to SwiftUI and allows removing units or fields, SwiftUI
/// removes parts that change more frequently than the frame rate allows. E.g. a
/// string like _13 minutes, 22 seconds_ would change to just `13 minutes`.
///
/// Otherwise, all digits in the formatted output are redacted using dashes.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func appendInterpolation<V, F>(_ source: TimeDataSource<V>, format: F) where V == F.FormatInput, F : DiscreteFormatStyle, F.FormatOutput == String
}
/// 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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
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:)`` 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-swift.type.property`` --- 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 : Sendable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 10.0, *)
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 {
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension Material {
/// Sets an explicit active appearance for this material.
///
/// Materials used as the `window` container background on macOS will
/// automatically appear inactive when their the window appears inactive, but
/// can be made to always appear active by setting the active appearance
/// behavior to be always active:
///
/// Text("Hello, World!")
/// .containerBackground(
/// Material.regular.materialActiveAppearance(.active),
/// for: .window)
///
public func materialActiveAppearance(_ appearance: MaterialActiveAppearance) -> Material
}
/// The behavior for how materials appear active and inactive.
///
/// On macOS, materials have active and inactive appearances that can reinforce
/// the active appearance of the window they are in:
/// - Materials used as a `window` container background and `bar` materials
/// will appear inactive when their containing window is inactive.
/// - All other materials will always appear active by default.
///
/// An explicit active appearance can be set to override a material's default
/// behavior. For example, materials used as the `window` container background
/// can be made to always appear active by setting the active appearance
/// behavior to be always active:
///
/// Text("Hello, World!")
/// .containerBackground(
/// Material.regular.materialActiveAppearance(.active),
/// for: .window)
///
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public struct MaterialActiveAppearance : Sendable, Equatable {
/// Materials will automatically appear active or inactive based on context
/// and platform convention.
///
/// Examples of automatic behavior on macOS:
/// - Materials used as a `window` container background will appear inactive
/// when the containing window is inactive.
/// - `Material.bar` materials will appear inactive when the containing
/// window is inactive.
/// - All other materials will appear as active.
///
/// Materials always appear as active on all other platforms.
public static let automatic: MaterialActiveAppearance
/// Materials will always appear active.
public static let active: MaterialActiveAppearance
/// Materials will always appear inactive.
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public static let inactive: MaterialActiveAppearance
/// Materials will have an active or inactive appearance based on
/// the active appearance of their window.
///
/// On non-macOS platforms, materials will always appear as active.
public static let matchWindow: MaterialActiveAppearance
/// 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: MaterialActiveAppearance, b: MaterialActiveAppearance) -> Bool
}
/// A two-dimensional gradient defined by a 2D grid of positioned
/// colors.
///
/// Each vertex has a position, a color and four surrounding Bezier
/// control points (leading, top, trailing, bottom) that define the
/// tangents connecting the vertex with its four neighboring vertices.
/// (Vertices on the corners or edges of the mesh have less than four
/// neighbors, they ignore their extra control points.) Control points
/// may either be specified explicitly or implicitly.
///
/// When rendering, a tessellated sequence of Bezier patches are
/// created, and vertex colors are interpolated across each patch,
/// either linearly, or via another set of cubic curves derived from
/// how the colors change between neighbors -- the latter typically
/// gives smoother color transitions.
///
/// MeshGradient(width: 3, height: 3, points: [
/// .init(0, 0), .init(0.5, 0), .init(1, 0),
/// .init(0, 0.5), .init(0.5, 0.5), .init(1, 0.5),
/// .init(0, 1), .init(0.5, 1), .init(1, 1)
/// ], colors: [
/// .red, .purple, .indigo,
/// .orange, .white, .blue,
/// .yellow, .green, .mint
/// ])
///
@available(iOS 18.0, macOS 15.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
@MainActor @preconcurrency public struct MeshGradient : ShapeStyle, Equatable, Sendable {
/// An array of 2D locations and their control points.
public enum Locations : Equatable, Sendable {
/// Vertices are only specified as their location, their control
/// points are inferred from the locations of their neighbors.
case points([SIMD2<Float>])
/// Vertices explicitly specifying their location and control
/// points.
case bezierPoints([MeshGradient.BezierPoint])
/// 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: MeshGradient.Locations, b: MeshGradient.Locations) -> Bool
}
/// An array of colors.
public enum Colors : Equatable, Sendable {
case colors([Color])
case resolvedColors([Color.Resolved])
/// 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: MeshGradient.Colors, b: MeshGradient.Colors) -> Bool
}
/// One location in a gradient mesh, along with the four Bezier
/// control points surrounding it.
@frozen public struct BezierPoint : Equatable, Sendable {
/// The position of the vertex.
public var position: SIMD2<Float>
/// The Bezier control point of the vertex's leading edge.
public var leadingControlPoint: SIMD2<Float>
/// The Bezier control point of the vertex's top edge.
public var topControlPoint: SIMD2<Float>
/// The Bezier control point of the vertex's trailing edge.
public var trailingControlPoint: SIMD2<Float>
/// The Bezier control point of the vertex's bottom edge.
public var bottomControlPoint: SIMD2<Float>
/// Creates a new vertex.
///
/// - Parameters:
/// - position: the position of the vertex in the coordinate
/// space the gradient is interpreted in.
/// - leadingControlPoint: the Bezier control point of the
/// vertex's leading edge.
/// - topControlPoint: the Bezier control point of the
/// vertex's top edge.
/// - trailingControlPoint: the Bezier control point of the
/// vertex's trailing edge.
/// - bottomControlPoint: the Bezier control point of the
/// vertex's bottom edge.
public init(position: SIMD2<Float>, leadingControlPoint: SIMD2<Float>, topControlPoint: SIMD2<Float>, trailingControlPoint: SIMD2<Float>, bottomControlPoint: SIMD2<Float>)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: MeshGradient.BezierPoint, b: MeshGradient.BezierPoint) -> Bool
}
/// The width of the mesh, i.e. the number of vertices per row.
@MainActor @preconcurrency public var width: Int
/// The height of the mesh, i.e. the number of vertices per column.
@MainActor @preconcurrency public var height: Int
/// The array of locations. Must contain `width x height` elements.
@MainActor @preconcurrency public var locations: MeshGradient.Locations
/// The array of colors. Must contain `width x height` elements.
@MainActor @preconcurrency public var colors: MeshGradient.Colors
/// The background color, this fills any points outside the defined
/// vertex mesh.
@MainActor @preconcurrency public var background: Color
/// Whether cubic (smooth) interpolation should be used for the
/// colors in the mesh (rather than only for the shape of the
/// mesh).
@MainActor @preconcurrency public var smoothsColors: Bool
/// The color space in which to interpolate vertex colors.
@MainActor @preconcurrency public var colorSpace: Gradient.ColorSpace
/// Creates a new gradient mesh specified as a 2D grid of colored
/// vertices.
///
/// - Parameters:
/// - width: the width of the mesh, i.e. the number of vertices
/// per row.
/// - height: the height of the mesh, i.e. the number of vertices
/// per column.
/// - locations: the array of locations, containing `width x
/// height` elements.
/// - colors: the array of colors, containing `width x height`
/// elements.
/// - background: the background color, this fills any points
/// outside the defined vertex mesh.
/// - smoothsColors: whether cubic (smooth) interpolation should
/// be used for the colors in the mesh (rather than only for the
/// shape of the mesh).
/// - colorSpace: the color space in which to interpolate vertex
/// colors.
@MainActor @preconcurrency public init(width: Int, height: Int, locations: MeshGradient.Locations, colors: MeshGradient.Colors, background: Color = .clear, smoothsColors: Bool = true, colorSpace: Gradient.ColorSpace = .device)
/// Creates a new gradient mesh specified as a 2D grid of colored
/// points.
///
/// - Parameters:
/// - width: the width of the mesh, i.e. the number of vertices
/// per row.
/// - height: the height of the mesh, i.e. the number of vertices
/// per column.
/// - points: the array of points, containing `width x height`
/// elements.
/// - colors: the array of colors, containing `width x height`
/// elements.
/// - background: the background color, this fills any points
/// outside the defined vertex mesh.
/// - smoothsColors: whether cubic (smooth) interpolation should
/// be used for the colors in the mesh (rather than only for the
/// shape of the mesh).
/// - colorSpace: the color space in which to interpolate vertex
/// colors.
@MainActor @preconcurrency public init(width: Int, height: Int, points: [SIMD2<Float>], colors: [Color], background: Color = .clear, smoothsColors: Bool = true, colorSpace: Gradient.ColorSpace = .device)
/// Creates a new gradient mesh specified as a 2D grid of colored
/// points, with already-resolved sRGB colors.
///
/// - Parameters:
/// - width: the width of the mesh, i.e. the number of vertices
/// per row.
/// - height: the height of the mesh, i.e. the number of vertices
/// per column.
/// - points: the array of points, containing `width x height`
/// elements.
/// - resolvedColors: the array of colors, containing `width x
/// height` elements.
/// - background: the background color, this fills any points
/// outside the defined vertex mesh.
/// - smoothsColors: whether cubic (smooth) interpolation should
/// be used for the colors in the mesh (rather than only for the
/// shape of the mesh).
/// - colorSpace: the color space in which to interpolate vertex
/// colors.
@MainActor @preconcurrency public init(width: Int, height: Int, points: [SIMD2<Float>], resolvedColors: [Color.Resolved], background: Color = .clear, smoothsColors: Bool = true, colorSpace: Gradient.ColorSpace = .device)
/// Creates a new gradient mesh specified as a 2D grid of colored
/// points, specifying the Bezier control points explicitly.
///
/// - Parameters:
/// - width: the width of the mesh, i.e. the number of vertices
/// per row.
/// - height: the height of the mesh, i.e. the number of vertices
/// per column.
/// - bezierPoints: the array of points and control points,
/// containing `width x height` elements.
/// - colors: the array of colors, containing `width x height`
/// elements.
/// - background: the background color, this fills any points
/// outside the defined vertex mesh.
/// - smoothsColors: whether cubic (smooth) interpolation should
/// be used for the colors in the mesh (rather than only for the
/// shape of the mesh).
/// - colorSpace: the color space in which to interpolate vertex
/// colors.
@MainActor @preconcurrency public init(width: Int, height: Int, bezierPoints: [MeshGradient.BezierPoint], colors: [Color], background: Color = .clear, smoothsColors: Bool = true, colorSpace: Gradient.ColorSpace = .device)
/// Creates a new gradient mesh specified as a 2D grid of colored
/// points, specifying the Bezier control points explicitly, with
/// already-resolved sRGB colors.
///
/// - Parameters:
/// - width: the width of the mesh, i.e. the number of vertices
/// per row.
/// - height: the height of the mesh, i.e. the number of vertices
/// per column.
/// - bezierPoints: the array of points and control points,
/// containing `width x height` elements.
/// - resolvedColors: the array of colors, containing `width x
/// height` elements.
/// - background: the background color, this fills any points
/// outside the defined vertex mesh.
/// - smoothsColors: whether cubic (smooth) interpolation should
/// be used for the colors in the mesh (rather than only for the
/// shape of the mesh).
/// - colorSpace: the color space in which to interpolate vertex
/// colors.
@MainActor @preconcurrency public init(width: Int, height: Int, bezierPoints: [MeshGradient.BezierPoint], resolvedColors: [Color.Resolved], background: Color = .clear, smoothsColors: Bool = true, colorSpace: Gradient.ColorSpace = .device)
/// 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.
nonisolated public static func == (a: MeshGradient, b: MeshGradient) -> Bool
/// 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.
@available(iOS 18.0, tvOS 18.0, watchOS 11.0, macOS 15.0, visionOS 2.0, *)
public typealias Body
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 18.0, tvOS 18.0, watchOS 11.0, macOS 15.0, visionOS 2.0, *)
public typealias Resolved = Never
}
@available(iOS 18.0, macOS 15.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
extension MeshGradient : View {
}
/// 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 : 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 built-in views that SwiftUI provides, plus other
/// composite views that you've already defined:
///
/// struct MyView: View {
/// var body: some View {
/// Text("Hello, World!")
/// }
/// }
///
/// For more information about composing views and a view hierarchy,
/// see <doc:Declaring-a-Custom-View>.
@MainActor @preconcurrency 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Data = Content.Data
}
/// A keyframe that immediately moves to the given value without interpolating.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct MoveKeyframe<Value> : KeyframeTrackContent where Value : Animatable {
/// Creates a new keyframe using the given value.
///
/// - Parameters:
/// - to: The value of the keyframe.
public init(_ to: Value)
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = MoveKeyframe<Value>
}
/// A named coordinate space.
///
/// Use the `coordinateSpace(_:)` modifier to assign a name to the local
/// coordinate space of a parent view. Child views can then refer to that
/// coordinate space using `.named(_:)`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct NamedCoordinateSpace : CoordinateSpaceProtocol, Equatable {
/// The resolved coordinate space.
public var coordinateSpace: CoordinateSpace { 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: NamedCoordinateSpace, b: NamedCoordinateSpace) -> Bool
}
/// 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, Sendable {
@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: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: 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.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Namespace.ID : Sendable {
}
/// Returns a transition that offset the view by the specified amount.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@MainActor @preconcurrency public struct OffsetTransition : Transition {
/// The amount to offset the view by.
@MainActor @preconcurrency public var offset: CGSize
/// Creates a transition that offset the view by the specified amount.
@MainActor @preconcurrency public init(_ offset: CGSize)
/// Gets the current body of the caller.
///
/// `content` is a proxy for the view that will have the modifier
/// represented by `Self` applied to it.
@MainActor @preconcurrency public func body(content: OffsetTransition.Content, phase: TransitionPhase) -> some View
/// The type of view representing the body.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = some View
}
/// A transition from transparent to opaque on insertion, and from opaque to
/// transparent on removal.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@MainActor @preconcurrency public struct OpacityTransition : Transition {
@MainActor @preconcurrency public init()
/// Gets the current body of the caller.
///
/// `content` is a proxy for the view that will have the modifier
/// represented by `Self` applied to it.
@MainActor @preconcurrency public func body(content: OpacityTransition.Content, phase: TransitionPhase) -> some View
/// Returns the properties this transition type has.
///
/// Defaults to `TransitionProperties()`.
@MainActor @preconcurrency public static let properties: TransitionProperties
/// The type of view representing the body.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = some View
}
/// An action that opens a URL.
///
/// Read the ``EnvironmentValues/openURL`` environment value to get an
/// instance of this structure for a given ``Environment``. Call the
/// instance to open a URL. You call the instance directly because it
/// defines a ``OpenURLAction/callAsFunction(_:)`` method that Swift
/// calls when you call the instance.
///
/// For example, you can open a web site when the user taps a button:
///
/// struct OpenURLExample: View {
/// @Environment(\.openURL) private var openURL
///
/// var body: some View {
/// Button {
/// if let url = URL(string: "https://www.example.com") {
/// openURL(url)
/// }
/// } label: {
/// Label("Get Help", systemImage: "person.fill.questionmark")
/// }
/// }
/// }
///
/// If you want to know whether the action succeeds, add a completion
/// handler that takes a Boolean value. In this case, Swift implicitly
/// calls the ``OpenURLAction/callAsFunction(_:completion:)`` method
/// instead. That method calls your completion handler after it determines
/// whether it can open the URL, but possibly before it finishes opening
/// the URL. You can add a handler to the example above so that
/// it prints the outcome to the console:
///
/// openURL(url) { accepted in
/// print(accepted ? "Success" : "Failure")
/// }
///
/// The system provides a default open URL action with behavior
/// that depends on the contents of the URL. For example, the default
/// action opens a Universal Link in the associated app if possible,
/// or in the user’s default web browser if not.
///
/// You can also set a custom action using the ``View/environment(_:_:)``
/// view modifier. Any views that read the action from the environment,
/// including the built-in ``Link`` view and ``Text`` views with markdown
/// links, or links in attributed strings, use your action. Initialize an
/// action by calling the ``OpenURLAction/init(handler:)`` initializer with
/// a handler that takes a URL and returns an ``OpenURLAction/Result``:
///
/// Text("Visit [Example Company](https://www.example.com) for details.")
/// .environment(\.openURL, OpenURLAction { url in
/// handleURL(url) // Define this method to take appropriate action.
/// return .handled
/// })
///
/// SwiftUI translates the value that your custom action's handler
/// returns into an appropriate Boolean result for the action call.
/// For example, a view that uses the action declared above
/// receives `true` when calling the action, because the
/// handler always returns ``OpenURLAction/Result/handled``.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@MainActor @preconcurrency public struct OpenURLAction {
/// The result of a custom open URL action.
///
/// If you declare a custom ``OpenURLAction`` in the ``Environment``,
/// return one of the result values from its handler.
///
/// * Use ``handled`` to indicate that the handler opened the URL.
/// * Use ``discarded`` to indicate that the handler discarded the URL.
/// * Use ``systemAction`` without an argument to ask SwiftUI
/// to open the URL with the system handler.
/// * Use ``systemAction(_:)`` with a URL argument to ask SwiftUI
/// to open the specified URL with the system handler.
///
/// You can use the last option to transform URLs, while
/// still relying on the system to open the URL. For example,
/// you could append a path component to every URL:
///
/// .environment(\.openURL, OpenURLAction { url in
/// .systemAction(url.appendingPathComponent("edit"))
/// })
///
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct Result : Sendable {
/// The handler opened the URL.
///
/// The action invokes its completion handler with `true` when your
/// handler returns this value.
public static let handled: OpenURLAction.Result
/// The handler discarded the URL.
///
/// The action invokes its completion handler with `false` when your
/// handler returns this value.
public static let discarded: OpenURLAction.Result
/// The handler asks the system to open the original URL.
///
/// The action invokes its completion handler with a value that
/// depends on the outcome of the system's attempt to open the URL.
public static let systemAction: OpenURLAction.Result
/// The handler asks the system to open the modified URL.
///
/// The action invokes its completion handler with a value that
/// depends on the outcome of the system's attempt to open the URL.
///
/// - Parameter url: The URL that the handler asks the system to open.
public static func systemAction(_ url: URL) -> OpenURLAction.Result
}
/// Creates an action that opens a URL.
///
/// Use this initializer to create a custom action for opening URLs.
/// Provide a handler that takes a URL and returns an
/// ``OpenURLAction/Result``. Place your handler in the environment
/// using the ``View/environment(_:_:)`` view modifier:
///
/// Text("Visit [Example Company](https://www.example.com) for details.")
/// .environment(\.openURL, OpenURLAction { url in
/// handleURL(url) // Define this method to take appropriate action.
/// return .handled
/// })
///
/// Any views that read the action from the environment, including the
/// built-in ``Link`` view and ``Text`` views with markdown links, or
/// links in attributed strings, use your action.
///
/// SwiftUI translates the value that your custom action's handler
/// returns into an appropriate Boolean result for the action call.
/// For example, a view that uses the action declared above
/// receives `true` when calling the action, because the
/// handler always returns ``OpenURLAction/Result/handled``.
///
/// - Parameter handler: The closure to run for the given URL.
/// The closure takes a URL as input, and returns a ``Result``
/// that indicates the outcome of the action.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
@MainActor @preconcurrency public init(handler: @escaping (URL) -> OpenURLAction.Result)
/// Opens a URL, following system conventions.
///
/// Don't call this method directly. SwiftUI calls it when you
/// call the ``OpenURLAction`` structure that you get from the
/// ``Environment``, using a URL as an argument:
///
/// struct OpenURLExample: View {
/// @Environment(\.openURL) private var openURL
///
/// var body: some View {
/// Button {
/// if let url = URL(string: "https://www.example.com") {
/// openURL(url) // Implicitly calls openURL.callAsFunction(url)
/// }
/// } label: {
/// Label("Get Help", systemImage: "person.fill.questionmark")
/// }
/// }
/// }
///
/// For information about how Swift uses the `callAsFunction()` method to
/// simplify call site syntax, see
/// [Methods with Special Names](https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID622)
/// in *The Swift Programming Language*.
///
/// - Parameter url: The URL to open.
@MainActor @preconcurrency public func callAsFunction(_ url: URL)
/// Asynchronously opens a URL, following system conventions.
///
/// Don't call this method directly. SwiftUI calls it when you
/// call the ``OpenURLAction`` structure that you get from the
/// ``Environment``, using a URL and a completion handler as arguments:
///
/// struct OpenURLExample: View {
/// @Environment(\.openURL) private var openURL
///
/// var body: some View {
/// Button {
/// if let url = URL(string: "https://www.example.com") {
/// // Implicitly calls openURL.callAsFunction(url) { ... }
/// openURL(url) { accepted in
/// print(accepted ? "Success" : "Failure")
/// }
/// }
/// } label: {
/// Label("Get Help", systemImage: "person.fill.questionmark")
/// }
/// }
/// }
///
/// For information about how Swift uses the `callAsFunction()` method to
/// simplify call site syntax, see
/// [Methods with Special Names](https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID622)
/// in *The Swift Programming Language*.
///
/// - Parameters:
/// - url: The URL to open.
/// - completion: A closure the method calls after determining if
/// it can open the URL, but possibly before fully opening the URL.
/// The closure takes a Boolean value that indicates whether the
/// method can open the URL.
@available(watchOS, unavailable)
@MainActor @preconcurrency public func callAsFunction(_ url: URL, completion: @escaping (_ accepted: Bool) -> Void)
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension OpenURLAction : Sendable {
}
/// 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, @unchecked Sendable {
/// Creates an empty path.
public init()
/// Creates a path from an immutable shape path.
///
/// - Parameter path: The immutable CoreGraphics path to initialize
/// the new path from.
///
public init(_ path: CGPath)
/// Creates a path from a copy of a mutable shape path.
///
/// - Parameter path: The CoreGraphics path to initialize the new
/// path from.
///
public init(_ path: CGMutablePath)
/// Creates a path containing a rectangle.
///
/// This is a convenience function that creates a path of a
/// rectangle. Using this convenience function is more efficient
/// than creating a path and adding a rectangle to it.
///
/// Calling this function is equivalent to using `minX` and related
/// properties to find the corners of the rectangle, then using the
/// `move(to:)`, `addLine(to:)`, and `closeSubpath()` functions to
/// add the rectangle.
///
/// - Parameter rect: The rectangle to add.
///
public init(_ rect: CGRect)
/// Creates a path containing a rounded rectangle.
///
/// This is a convenience function that creates a path of a rounded
/// rectangle. Using this convenience function is more efficient
/// than creating a path and adding a rounded rectangle to it.
///
/// - Parameters:
/// - rect: A rectangle, specified in user space coordinates.
/// - cornerSize: The size of the corners, specified in user space
/// coordinates.
/// - style: The corner style. Defaults to the `continous` style
/// if not specified.
///
public init(roundedRect rect: CGRect, cornerSize: CGSize, style: RoundedCornerStyle = .continuous)
/// Creates a path containing a rounded rectangle.
///
/// This is a convenience function that creates a path of a rounded
/// rectangle. Using this convenience function is more efficient
/// than creating a path and adding a rounded rectangle to it.
///
/// - Parameters:
/// - rect: A rectangle, specified in user space coordinates.
/// - cornerRadius: The radius of all corners of the rectangle,
/// specified in user space coordinates.
/// - style: The corner style. Defaults to the `continous` style
/// if not specified.
///
public init(roundedRect rect: CGRect, cornerRadius: CGFloat, style: RoundedCornerStyle = .continuous)
/// Creates a path as the given rounded rectangle, which may have
/// uneven corner radii.
///
/// This is a convenience function that creates a path of a rounded
/// rectangle. Using this function is more efficient than creating
/// a path and adding a rounded rectangle to it.
///
/// - Parameters:
/// - rect: A rectangle, specified in user space coordinates.
/// - cornerRadii: The radius of each corner of the rectangle,
/// specified in user space coordinates.
/// - style: The corner style. Defaults to the `continous` style
/// if not specified.
///
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public init(roundedRect rect: CGRect, cornerRadii: RectangleCornerRadii, style: RoundedCornerStyle = .continuous)
/// Creates a path as an ellipse within the given rectangle.
///
/// This is a convenience function that creates a path of an
/// ellipse. Using this convenience function is more efficient than
/// creating a path and adding an ellipse to it.
///
/// The ellipse is approximated by a sequence of Bézier
/// curves. Its center is the midpoint of the rectangle defined by
/// the rect parameter. If the rectangle is square, then the
/// ellipse is circular with a radius equal to one-half the width
/// (or height) of the rectangle. If the rect parameter specifies a
/// rectangular shape, then the major and minor axes of the ellipse
/// are defined by the width and height of the rectangle.
///
/// The ellipse forms a complete subpath of the path—that
/// is, the ellipse drawing starts with a move-to operation and
/// ends with a close-subpath operation, with all moves oriented in
/// the clockwise direction. If you supply an affine transform,
/// then the constructed Bézier curves that define the
/// ellipse are transformed before they are added to the path.
///
/// - Parameter rect: The rectangle that bounds the ellipse.
///
public init(ellipseIn rect: CGRect)
/// Creates an empty path, then executes a closure to add its
/// initial elements.
///
/// - Parameter callback: The Swift function that will be called to
/// initialize the new path.
///
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.
///
/// This is the smallest rectangle completely enclosing all points
/// in the path but not including control points for Bézier
/// curves.
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.
nonisolated public func path(in _: CGRect) -> Path
/// The type defining the data to animate.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
///
/// The specified point becomes the start point of a new subpath.
/// The current point is set to this start point.
///
/// - Parameter end: The point, in user space coordinates, at which
/// to start a new subpath.
///
public mutating func move(to end: CGPoint)
/// Appends a straight line segment from the current point to the
/// specified point.
///
/// After adding the line segment, the current point is set to the
/// endpoint of the line segment.
///
/// - Parameter end: The location, in user space coordinates, for the
/// end of the new line segment.
///
public mutating func addLine(to end: CGPoint)
/// Adds a quadratic Bézier curve to the path, with the
/// specified end point and control point.
///
/// This method constructs a curve starting from the path's current
/// point and ending at the specified end point, with curvature
/// defined by the control point. After this method appends that
/// curve to the current path, the end point of the curve becomes
/// the path's current point.
///
/// - Parameters:
/// the curve.
/// - control: The control point of the curve, in user space
/// coordinates.
///
public mutating func addQuadCurve(to end: CGPoint, control: CGPoint)
/// Adds a cubic Bézier curve to the path, with the
/// specified end point and control points.
///
/// This method constructs a curve starting from the path's current
/// point and ending at the specified end point, with curvature
/// defined by the two control points. After this method appends
/// that curve to the current path, the end point of the curve
/// becomes the path's current point.
///
/// - Parameters:
/// the curve.
/// - control1: The first control point of the curve, in user
/// space coordinates.
/// - control2: The second control point of the curve, in user
/// space coordinates.
///
public mutating func addCurve(to end: CGPoint, control1: CGPoint, control2: CGPoint)
/// Closes and completes the current subpath.
///
/// Appends a line from the current point to the starting point of
/// the current subpath and ends the subpath.
///
/// After closing the subpath, your application can begin a new
/// subpath without first calling `move(to:)`. In this case, a new
/// subpath is implicitly created with a starting and current point
/// equal to the previous subpath's starting point.
///
public mutating func closeSubpath()
/// Adds a rectangular subpath to the path.
///
/// This is a convenience function that adds a rectangle to a path,
/// starting by moving to the bottom-left corner and then adding
/// lines counter-clockwise to create a rectangle, closing the
/// subpath.
///
/// - Parameters:
/// - rect: A rectangle, specified in user space coordinates.
/// - transform: An affine transform to apply to the rectangle
/// before adding to the path. Defaults to the identity
/// transform if not specified.
///
public mutating func addRect(_ rect: CGRect, transform: CGAffineTransform = .identity)
/// Adds a rounded rectangle to the path.
///
/// This is a convenience function that adds a rounded rectangle to
/// a path, starting by moving to the center of the right edge and
/// then adding lines and curves counter-clockwise to create a
/// rounded rectangle, closing the subpath.
///
/// - Parameters:
/// - rect: A rectangle, specified in user space coordinates.
/// - cornerSize: The size of the corners, specified in user space
/// coordinates.
/// - style: The corner style. Defaults to the `continous` style
/// if not specified.
/// - transform: An affine transform to apply to the rectangle
/// before adding to the path. Defaults to the identity
/// transform if not specified.
///
public mutating func addRoundedRect(in rect: CGRect, cornerSize: CGSize, style: RoundedCornerStyle = .continuous, transform: CGAffineTransform = .identity)
/// Adds a rounded rectangle with uneven corners to the path.
///
/// This is a convenience function that adds a rounded rectangle to
/// a path, starting by moving to the center of the right edge and
/// then adding lines and curves counter-clockwise to create a
/// rounded rectangle, closing the subpath.
///
/// - Parameters:
/// - rect: A rectangle, specified in user space coordinates.
/// - cornerRadii: The radius of each corner of the rectangle,
/// specified in user space coordinates.
/// - style: The corner style. Defaults to the `continous` style
/// if not specified.
/// - transform: An affine transform to apply to the rectangle
/// before adding to the path. Defaults to the identity
/// transform if not specified.
///
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public mutating func addRoundedRect(in rect: CGRect, cornerRadii: RectangleCornerRadii, style: RoundedCornerStyle = .continuous, transform: CGAffineTransform = .identity)
/// Adds an ellipse that fits inside the specified rectangle to the
/// path.
///
/// The ellipse is approximated by a sequence of Bézier
/// curves. Its center is the midpoint of the rectangle defined by
/// the `rect` parameter. If the rectangle is square, then the
/// ellipse is circular with a radius equal to one-half the width
/// (or height) of the rectangle. If the `rect` parameter specifies
/// a rectangular shape, then the major and minor axes of the
/// ellipse are defined by the width and height of the rectangle.
///
/// The ellipse forms a complete subpath of the path—
/// that is, the ellipse drawing starts with a move-to operation
/// and ends with a close-subpath operation, with all moves
/// oriented in the clockwise direction.
///
/// - Parameter:
/// - rect: A rectangle that defines the area for the ellipse to
/// fit in.
/// - transform: An affine transform to apply to the ellipse
/// before adding to the path. Defaults to the identity
/// transform if not specified.
///
public mutating func addEllipse(in rect: CGRect, transform: CGAffineTransform = .identity)
/// Adds a set of rectangular subpaths to the path.
///
/// Calling this convenience method is equivalent to repeatedly
/// calling the `addRect(_:transform:)` method for each rectangle
/// in the array.
///
/// - Parameter:
/// - rects: An array of rectangles, specified in user space
/// coordinates.
/// - transform: An affine transform to apply to the ellipse
/// before adding to the path. Defaults to the identity
/// transform if not specified.
///
public mutating func addRects(_ rects: [CGRect], transform: CGAffineTransform = .identity)
/// Adds a sequence of connected straight-line segments to the path.
///
/// Calling this convenience method is equivalent to applying the
/// transform to all points in the array, then calling the
/// `move(to:)` method with the first value in the `points` array,
/// then calling the `addLine(to:)` method for each subsequent
/// point until the array is exhausted. After calling this method,
/// the path's current point is the last point in the array.
///
/// - Parameter:
/// - lines: An array of values that specify the start and end
/// points of the line segments to draw. Each point in the
/// array specifies a position in user space. The first point
/// in the array specifies the initial starting point.
/// - transform: An affine transform to apply to the points
/// before adding to the path. Defaults to the identity
/// transform if not specified.
///
public mutating func addLines(_ lines: [CGPoint])
/// Adds an arc of a circle to the path, specified with a radius
/// and a difference in angle.
///
/// This method calculates starting and ending points using the
/// radius and angles you specify, uses a sequence of cubic
/// Bézier curves to approximate a segment of a circle
/// between those points, and then appends those curves to the
/// path.
///
/// The `delta` parameter determines both the length of the arc the
/// direction in which the arc is created; the actual direction of
/// the final path is dependent on the `transform` parameter and
/// the current transform of a context where the path is drawn.
/// However, because SwiftUI by default uses a vertically-flipped
/// coordinate system (with the origin in the top-left of the
/// view), specifying a clockwise arc results in a counterclockwise
/// arc after the transformation is applied.
///
/// If the path ends with an unclosed subpath, this method adds a
/// line connecting the current point to the starting point of the
/// arc. If there is no unclosed subpath, this method creates a new
/// subpath whose starting point is the starting point of the arc.
/// The ending point of the arc becomes the new current point of
/// the path.
///
/// - Parameters:
/// - center: The center of the arc, in user space coordinates.
/// - radius: The radius of the arc, in user space coordinates.
/// - startAngle: The angle to the starting point of the arc,
/// measured from the positive x-axis.
/// - delta: The difference between the starting angle and ending
/// angle of the arc. A positive value creates a counter-
/// clockwise arc (in user space coordinates), and vice versa.
/// - transform: An affine transform to apply to the arc before
/// adding to the path. Defaults to the identity transform if
/// not specified.
////
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.
///
/// This method calculates starting and ending points using the
/// radius and angles you specify, uses a sequence of cubic
/// Bézier curves to approximate a segment of a circle
/// between those points, and then appends those curves to the
/// path.
///
/// The `clockwise` parameter determines the direction in which the
/// arc is created; the actual direction of the final path is
/// dependent on the `transform` parameter and the current
/// transform of a context where the path is drawn. However,
/// because SwiftUI by default uses a vertically-flipped coordinate
/// system (with the origin in the top-left of the view),
/// specifying a clockwise arc results in a counterclockwise arc
/// after the transformation is applied.
///
/// If the path ends with an unclosed subpath, this method adds a
/// line connecting the current point to the starting point of the
/// arc. If there is no unclosed subpath, this method creates a new
/// subpath whose starting point is the starting point of the arc.
/// The ending point of the arc becomes the new current point of
/// the path.
///
/// - Parameters:
/// - center: The center of the arc, in user space coordinates.
/// - radius: The radius of the arc, in user space coordinates.
/// - startAngle: The angle to the starting point of the arc,
/// measured from the positive x-axis.
/// - endAngle: The angle to the end point of the arc, measured
/// from the positive x-axis.
/// - clockwise: true to make a clockwise arc; false to make a
/// counterclockwise arc.
/// - transform: An affine transform to apply to the arc before
/// adding to the path. Defaults to the identity transform if
/// not specified.
///
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.
///
/// This method calculates two tangent lines—the first
/// from the current point to the tangent1End point, and the second
/// from the `tangent1End` point to the `tangent2End`
/// point—then calculates the start and end points for a
/// circular arc of the specified radius such that the arc is
/// tangent to both lines. Finally, this method approximates that
/// arc with a sequence of cubic Bézier curves and appends
/// those curves to the path.
///
/// If the starting point of the arc (that is, the point where a
/// circle of the specified radius must meet the first tangent line
/// in order to also be tangent to the second line) is not the
/// current point, this method appends a straight line segment from
/// the current point to the starting point of the arc.
///
/// The ending point of the arc (that is, the point where a circle
/// of the specified radius must meet the second tangent line in
/// order to also be tangent to the first line) becomes the new
/// current point of the path.
///
/// - Parameters:
/// - tangent1End:The end point, in user space coordinates, for
/// the first tangent line to be used in constructing the arc.
/// (The start point for this tangent line is the path's
/// current point.)
/// - tangent2End: The end point, in user space coordinates, for
/// the second tangent line to be used in constructing the arc.
/// (The start point for this tangent line is the tangent1End
/// point.)
/// - radius: The radius of the arc, in user space coordinates.
/// - transform: An affine transform to apply to the arc before
/// adding to the path. Defaults to the identity transform if
/// not specified.
///
public mutating func addArc(tangent1End: CGPoint, tangent2End: CGPoint, radius: CGFloat, transform: CGAffineTransform = .identity)
/// Appends another path value to this path.
///
/// If the `path` parameter is a non-empty empty path, its elements
/// are appended in order to this path. Afterward, the start point
/// and current point of this path are those of the last subpath in
/// the `path` parameter.
///
/// - Parameters:
/// - path: The path to add.
/// - transform: An affine transform to apply to the path
/// parameter before adding to this path. Defaults to the
/// identity transform if not specified.
///
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 new weakly-simple copy of this path.
///
/// - Parameters:
/// - eoFill: Whether to use the even-odd rule for determining
/// which areas to treat as the interior of the paths (if true),
/// or the non-zero rule (if false).
/// - Returns: A new path.
///
/// The returned path is a weakly-simple path, has no
/// self-intersections, and has a normalized orientation. The
/// result of filling this path using either even-odd or non-zero
/// fill rules is identical.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func normalized(eoFill: Bool = true) -> Path
/// Returns a new path with filled regions common to both paths.
///
/// - Parameters:
/// - other: The path to intersect.
/// - eoFill: Whether to use the even-odd rule for determining
/// which areas to treat as the interior of the paths (if true),
/// or the non-zero rule (if false).
/// - Returns: A new path.
///
/// The filled region of the resulting path is the overlapping area
/// of the filled region of both paths. This can be used to clip
/// the fill of a path to a mask.
///
/// Any unclosed subpaths in either path are assumed to be closed.
/// The result of filling this path using either even-odd or
/// non-zero fill rules is identical.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func intersection(_ other: Path, eoFill: Bool = false) -> Path
/// Returns a new path with filled regions in either this path or
/// the given path.
///
/// - Parameters:
/// - other: The path to union.
/// - eoFill: Whether to use the even-odd rule for determining
/// which areas to treat as the interior of the paths (if true),
/// or the non-zero rule (if false).
/// - Returns: A new path.
///
/// The filled region of resulting path is the combination of the
/// filled region of both paths added together.
///
/// Any unclosed subpaths in either path are assumed to be closed.
/// The result of filling this path using either even-odd or
/// non-zero fill rules is identical.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func union(_ other: Path, eoFill: Bool = false) -> Path
/// Returns a new path with filled regions from this path that are
/// not in the given path.
///
/// - Parameters:
/// - other: The path to subtract.
/// - eoFill: Whether to use the even-odd rule for determining
/// which areas to treat as the interior of the paths (if true),
/// or the non-zero rule (if false).
/// - Returns: A new path.
///
/// The filled region of the resulting path is the filled region of
/// this path with the filled region `other` removed from it.
///
/// Any unclosed subpaths in either path are assumed to be closed.
/// The result of filling this path using either even-odd or
/// non-zero fill rules is identical.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func subtracting(_ other: Path, eoFill: Bool = false) -> Path
/// Returns a new path with filled regions either from this path or
/// the given path, but not in both.
///
/// - Parameters:
/// - other: The path to difference.
/// - eoFill: Whether to use the even-odd rule for determining
/// which areas to treat as the interior of the paths (if true),
/// or the non-zero rule (if false).
/// - Returns: A new path.
///
/// The filled region of the resulting path is the filled region
/// contained in either this path or `other`, but not both.
///
/// Any unclosed subpaths in either path are assumed to be closed.
/// The result of filling this path using either even-odd or
/// non-zero fill rules is identical.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func symmetricDifference(_ other: Path, eoFill: Bool = false) -> Path
/// Returns a new path with a line from this path that overlaps the
/// filled regions of the given path.
///
/// - Parameters:
/// - other: The path to intersect.
/// - eoFill: Whether to use the even-odd rule for determining
/// which areas to treat as the interior of the paths (if true),
/// or the non-zero rule (if false).
/// - Returns: A new path.
///
/// The line of the resulting path is the line of this path that
/// overlaps the filled region of `other`.
///
/// Intersected subpaths that are clipped create open subpaths.
/// Closed subpaths that do not intersect `other` remain closed.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func lineIntersection(_ other: Path, eoFill: Bool = false) -> Path
/// Returns a new path with a line from this path that does not
/// overlap the filled region of the given path.
///
/// - Parameters:
/// - other: The path to subtract.
/// - eoFill: Whether to use the even-odd rule for determining
/// which areas to treat as the interior of the paths (if true),
/// or the non-zero rule (if false).
/// - Returns: A new path.
///
/// The line of the resulting path is the line of this path that
/// does not overlap the filled region of `other`.
///
/// Intersected subpaths that are clipped create open subpaths.
/// Closed subpaths that do not intersect `other` remain closed.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public func lineSubtraction(_ other: Path, eoFill: Bool = false) -> Path
/// Returns a path constructed by applying the transform to all
/// points of the path.
///
/// - Parameter transform: An affine transform to apply to the path.
///
/// - Returns: a new copy of the path with the transform applied to
/// all points.
///
public func applying(_ transform: CGAffineTransform) -> Path
/// Returns a path constructed by translating all its points.
///
/// - Parameters:
/// - dx: The offset to apply in the horizontal axis.
/// - dy: The offset to apply in the vertical axis.
///
/// - Returns: a new copy of the path with the offset applied to
/// all points.
///
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.
///
/// You can also use ``TimelineSchedule/periodic(from:by:)`` to construct this
/// schedule.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public struct PeriodicTimelineSchedule : TimelineSchedule, Sendable {
/// 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, Sendable {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying sequence. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// You must not call this method if any other copy of this iterator has been
/// advanced with a call to its `next()` method.
///
/// The following example shows how an iterator can be used explicitly to
/// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and
/// then call the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence, if a next element
/// exists; otherwise, `nil`.
public mutating func next() -> Date?
/// A type representing the sequence's elements.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
public typealias Element = Date
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
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.
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 container that animates its content by automatically cycling through
/// a collection of phases that you provide, each defining a discrete step
/// within an animation.
///
/// Use one of the phase animator view modifiers like
/// ``View/phaseAnimator(_:content:animation:)`` to create a phased animation
/// in your app.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@MainActor @preconcurrency public struct PhaseAnimator<Phase, Content> : View where Phase : Equatable, Content : View {
/// Cycles through a sequence of phases in response to changes in a
/// specified value, animating updates to a view on each phase change.
///
/// When the phase animator first appears, this initializer renders the
/// `content` closure using the first phase as input to the closure.
/// When the value of the `trigger` input changes, the animator
/// reevaluates the `content` closure using the value from the second phase
/// and animates the change. This procedure repeats with each
/// successive phase until reaching the last phase, at which point
/// the animator loops back to the first phase.
///
/// - Parameters:
/// - phases: The sequence of phases to cycle through. Ensure that the
/// sequence isn't empty. If it is, SwiftUI logs a runtime warning and
/// also returns a visual warning as the output view.
/// - trigger: A value whose changes cause the animator to use the
/// next phase.
/// - content: A view builder closure that takes the current phase as an
/// input. Return a view that's based on the phase input.
/// - animation: A closure that takes the current phase as input. Return
/// the animation to use when transitioning to the next phase. If you
/// return `nil`, the transition doesn't animate. If you don't set this
/// parameter, SwiftUI uses a default animation.
nonisolated public init(_ phases: some Sequence<Phase>, trigger: some Equatable, @ViewBuilder content: @escaping (Phase) -> Content, animation: @escaping (Phase) -> Animation? = { _ in .default })
/// Cycles through a sequence of phases continuously, animating updates to
/// a view on each phase change.
///
/// When the phase animator first appears, this initializer renders the
/// `content` closure using the first phase as input to the closure.
/// The animator then begins immediately animating to the view produced by
/// sending the second phase to the `content` closure using
/// the animation returned from the `animation` closure. This procedure
/// repeats for successive phases until reaching the last phase, after which
/// the animator loops back to the first phase again.
///
/// - Parameters:
/// - phases: The sequence of phases to cycle through. Ensure that the
/// sequence isn't empty. If it is, SwiftUI logs a runtime warning and
/// also returns a visual warning as the output view.
/// - content: A view builder closure that takes the current phase as an
/// input. Return a view that's based on the current phase.
/// - animation: A closure that takes the current phase as input. Return
/// the animation to use when transitioning to the next phase. If you
/// return `nil`, the transition doesn't animate. If you don't set this
/// parameter, SwiftUI uses a default animation.
nonisolated public init(_ phases: some Sequence<Phase>, @ViewBuilder content: @escaping (Phase) -> Content, animation: @escaping (Phase) -> Animation? = { _ in .default })
/// The content and behavior of the view.
///
/// When you implement a custom view, you must implement a computed
/// `body` property to provide the content for your view. Return a view
/// that's composed of built-in views that SwiftUI provides, plus other
/// composite views that you've already defined:
///
/// struct MyView: View {
/// var body: some View {
/// Text("Hello, World!")
/// }
/// }
///
/// For more information about composing views and a view hierarchy,
/// see <doc:Declaring-a-Custom-View>.
@MainActor @preconcurrency 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.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = some View
}
/// 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, Sendable {
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
public let rawValue: 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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
public typealias RawValue = UInt32
}
/// A placeholder used to construct an inline modifier, transition, or other
/// helper type.
///
/// You don't use this type directly. Instead SwiftUI creates this type on
/// your behalf.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@MainActor @preconcurrency public struct PlaceholderContentView<Value> : 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.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = Never
}
/// 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.
///
/// Don't use this key directly. Instead, set a preferred color scheme for a
/// view using the ``View/preferredColorScheme(_:)`` view modifier. Get the
/// current color scheme for a view by accessing the
/// ``EnvironmentValues/colorScheme`` value.
@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)
}
@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 : Sendable {
/// 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: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 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 proposal for the size of a view.
///
/// During layout in SwiftUI, views choose their own size, but they do that
/// in response to a size proposal from their parent view. When you create
/// a custom layout using the ``Layout`` protocol, your layout container
/// participates in this process using `ProposedViewSize` instances.
/// The layout protocol's methods take a proposed size input that you
/// can take into account when arranging views and calculating the size of
/// the composite container. Similarly, your layout proposes a size to each
/// of its own subviews when it measures and places them.
///
/// Layout containers typically measure their subviews by proposing several
/// sizes and looking at the responses. The container can use this information
/// to decide how to allocate space among its subviews. A
/// layout might try the following special proposals:
///
/// * The ``zero`` proposal; the view responds with its minimum size.
/// * The ``infinity`` proposal; the view responds with its maximum size.
/// * The ``unspecified`` proposal; the view responds with its ideal size.
///
/// A layout might also try special cases for one dimension at a time. For
/// example, an ``HStack`` might measure the flexibility of its subviews'
/// widths, while using a fixed value for the height.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@frozen public struct ProposedViewSize : Equatable {
/// The proposed horizontal size measured in points.
///
/// A value of `nil` represents an unspecified width proposal, which a view
/// interprets to mean that it should use its ideal width.
public var width: CGFloat?
/// The proposed vertical size measured in points.
///
/// A value of `nil` represents an unspecified height proposal, which a view
/// interprets to mean that it should use its ideal height.
public var height: CGFloat?
/// A size proposal that contains zero in both dimensions.
///
/// Subviews of a custom layout return their minimum size when you propose
/// this value using the ``LayoutSubview/dimensions(in:)`` method.
/// A custom layout should also return its minimum size from the
/// ``Layout/sizeThatFits(proposal:subviews:cache:)`` method for this
/// value.
public static let zero: ProposedViewSize
/// The proposed size with both dimensions left unspecified.
///
/// Both dimensions contain `nil` in this size proposal.
/// Subviews of a custom layout return their ideal size when you propose
/// this value using the ``LayoutSubview/dimensions(in:)`` method.
/// A custom layout should also return its ideal size from the
/// ``Layout/sizeThatFits(proposal:subviews:cache:)`` method for this
/// value.
public static let unspecified: ProposedViewSize
/// A size proposal that contains infinity in both dimensions.
///
/// Both dimensions contain
/// <doc://com.apple.documentation/documentation/CoreFoundation/CGFloat/1454161-infinity>
/// in this size proposal.
/// Subviews of a custom layout return their maximum size when you propose
/// this value using the ``LayoutSubview/dimensions(in:)`` method.
/// A custom layout should also return its maximum size from the
/// ``Layout/sizeThatFits(proposal:subviews:cache:)`` method for this
/// value.
public static let infinity: ProposedViewSize
/// Creates a new proposed size using the specified width and height.
///
/// - Parameters:
/// - width: A proposed width in points. Use a value of `nil` to indicate
/// that the width is unspecified for this proposal.
/// - height: A proposed height in points. Use a value of `nil` to
/// indicate that the height is unspecified for this proposal.
@inlinable public init(width: CGFloat?, height: CGFloat?)
/// Creates a new proposed size from a specified size.
///
/// - Parameter size: A proposed size with dimensions measured in points.
@inlinable public init(_ size: CGSize)
/// Creates a new proposal that replaces unspecified dimensions in this
/// proposal with the corresponding dimension of the specified size.
///
/// Use the default value to prevent a flexible view from disappearing
/// into a zero-sized frame, and ensure the unspecified value remains
/// visible during debugging.
///
/// - Parameter size: A set of concrete values to use for the size proposal
/// in place of any unspecified dimensions. The default value is `10`
/// for both dimensions.
///
/// - Returns: A new, fully specified size proposal.
@inlinable public func replacingUnspecifiedDimensions(by size: CGSize = CGSize(width: 10, height: 10)) -> CGSize
/// 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: ProposedViewSize, b: ProposedViewSize) -> Bool
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ProposedViewSize : Sendable {
}
/// 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, *)
@MainActor @frozen @preconcurrency public struct RadialGradient : ShapeStyle, View, Sendable {
/// Creates a radial gradient from a base gradient.
nonisolated public init(gradient: Gradient, center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat)
/// Creates a radial gradient from a collection of colors.
nonisolated public init(colors: [Color], center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat)
/// Creates a radial gradient from a collection of color stops.
nonisolated 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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
/// 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, *)
@MainActor @frozen @preconcurrency 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.
nonisolated public func path(in rect: CGRect) -> Path
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
nonisolated public var layoutDirectionBehavior: LayoutDirectionBehavior { get }
/// Creates a new rectangle shape.
@inlinable nonisolated public init()
/// The type defining the data to animate.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Rectangle : InsettableShape {
/// Returns `self` inset by `amount`.
@MainActor @inlinable @preconcurrency public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias InsetShape = some InsettableShape
}
/// Describes the corner radius values of a rounded rectangle with
/// uneven corners.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
@frozen public struct RectangleCornerRadii : Equatable, Animatable {
/// The radius of the top-leading corner.
public var topLeading: CGFloat
/// The radius of the bottom-leading corner.
public var bottomLeading: CGFloat
/// The radius of the bottom-trailing corner.
public var bottomTrailing: CGFloat
/// The radius of the top-trailing corner.
public var topTrailing: CGFloat
/// Creates a new set of corner radii for a rounded rectangle with
/// uneven corners.
///
/// - Parameters:
/// - topLeading: the radius of the top-leading corner.
/// - bottomLeading: the radius of the bottom-leading corner.
/// - bottomTrailing: the radius of the bottom-trailing corner.
/// - topTrailing: the radius of the top-trailing corner.
public init(topLeading: CGFloat = 0, bottomLeading: CGFloat = 0, bottomTrailing: CGFloat = 0, topTrailing: CGFloat = 0)
/// The type defining the data to animate.
public typealias AnimatableData = AnimatablePair<AnimatablePair<CGFloat, CGFloat>, AnimatablePair<CGFloat, CGFloat>>
/// The data to animate.
public var animatableData: RectangleCornerRadii.AnimatableData
/// 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: RectangleCornerRadii, b: RectangleCornerRadii) -> Bool
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension RectangleCornerRadii : 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, Sendable {
/// The raw value.
public let rawValue: Int
/// Creates a new set from a raw value.
///
/// - Parameter rawValue: The raw value with which to create the
/// 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
/// Displayed data should appear as invalidated and pending a new update.
///
/// Views marked with `invalidatableContent` will be automatically
/// redacted with a standard styling indicating the content is invalidated
/// and new content will be available soon.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public static let invalidated: RedactionReasons
/// The type of the elements of an array literal.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
public typealias RawValue = Int
}
/// 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 : Sendable {
/// 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: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension 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, *)
@MainActor @frozen @preconcurrency public struct RoundedRectangle : Shape {
/// The width and height of the rounded rectangle's corners.
@MainActor @preconcurrency public var cornerSize: CGSize
/// The style of corners drawn by the rounded rectangle.
@MainActor @preconcurrency public var style: RoundedCornerStyle
/// Creates a new rounded rectangle shape.
///
/// - Parameters:
/// - cornerSize: the width and height of the rounded corners.
/// - style: the style of corners drawn by the shape.
@inlinable nonisolated public init(cornerSize: CGSize, style: RoundedCornerStyle = .continuous)
/// Creates a new rounded rectangle shape.
///
/// - Parameters:
/// - cornerRadius: the radius of the rounded corners.
/// - style: the style of corners drawn by the shape.
@inlinable nonisolated public init(cornerRadius: CGFloat, style: RoundedCornerStyle = .continuous)
/// Describes this shape as a path within a rectangular frame of reference.
///
/// - Parameter rect: The frame of reference for describing this shape.
///
/// - Returns: A path that describes this shape.
nonisolated public func path(in rect: CGRect) -> Path
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
nonisolated public var layoutDirectionBehavior: LayoutDirectionBehavior { get }
/// The data to animate.
@MainActor @preconcurrency public var animatableData: CGSize.AnimatableData
/// The type defining the data to animate.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension RoundedRectangle : InsettableShape {
/// Returns `self` inset by `amount`.
@MainActor @inlinable @preconcurrency public func inset(by amount: CGFloat) -> some InsettableShape
/// The type of the inset shape.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
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`, the default.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
public typealias Element = SafeAreaRegions
/// 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.
@available(iOS 14.0, tvOS 14.0, watchOS 7.0, macOS 11.0, *)
public typealias RawValue = UInt
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension SafeAreaRegions : Sendable {
}
/// Returns a transition that scales the view.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@MainActor @preconcurrency public struct ScaleTransition : Transition {
/// The amount to scale the view by.
@MainActor @preconcurrency public var scale: Double
/// The anchor point to scale the view around.
@MainActor @preconcurrency public var anchor: UnitPoint
/// Creates a transition that scales the view by the specified amount.
@MainActor @preconcurrency public init(_ scale: Double, anchor: UnitPoint = .center)
/// Gets the current body of the caller.
///
/// `content` is a proxy for the view that will have the modifier
/// represented by `Self` applied to it.
@MainActor @preconcurrency public func body(content: ScaleTransition.Content, phase: TransitionPhase) -> some View
/// The type of view representing the body.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Body = some View
}
/// A dynamic property that scales a numeric value.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@propertyWrapper public struct ScaledMetric<Value> : DynamicProperty where Value : BinaryFloatingPoint {
/// Creates the scaled metric with an unscaled value and a text style to
/// scale relative to.
public init(wrappedValue: Value, relativeTo textStyle: Font.TextStyle)
/// Creates the scaled metric with an unscaled value using the default
/// scaling.
public init(wrappedValue: Value)
/// The value scaled based on the current environment.
public var wrappedValue: Value { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ScaledMetric : Sendable where Value : Sendable {
}
/// A type that defines the geometry of a scroll view.
///
/// SwiftUI provides you values of this type when using modifiers like
/// ``View/onScrollGeometryChange(_:action:)`` or
/// ``View/onScrollPhaseChange(_:)``.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, *)
public struct ScrollGeometry : Equatable, Sendable {
/// The content offset of the scroll view.
///
/// This is the position of the scroll view within its overall
/// content size. This value may extend before zero or beyond
/// the content size when the content insets of the scroll view
/// are non-zero or when rubber banding.
public var contentOffset: CGPoint
/// The size of the content of the scroll view.
///
/// Unlike the container size of the scroll view, this refers to the
/// total size of the content of the scroll view which can be smaller
/// or larger than its containing size.
public var contentSize: CGSize
/// The content insets of the scroll view.
///
/// Adding these insets to the content size of the scroll view
/// will give you the total scrollable space of the scroll view.
public var contentInsets: EdgeInsets
/// The size of the container of the scroll view.
///
/// This is the overall size of the scroll view. Combining this
/// and the content offset will give you the current visible rect
/// of the scroll view.
public var containerSize: CGSize
/// The visible rect of the scroll view.
///
/// This value is computed from the scroll view's content offset, content
/// insets, and its container size.
public var visibleRect: CGRect { get }
/// The bounds rect of the scroll view.
///
/// Unlike the visible rect, this value is within the content insets
/// of the scroll view.
public var bounds: CGRect { 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: ScrollGeometry, b: ScrollGeometry) -> Bool
}
extension ScrollGeometry {
/// Creates a scroll geometry.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, *)
public init(contentOffset: CGPoint, contentSize: CGSize, contentInsets: EdgeInsets, containerSize: CGSize)
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, *)
extension ScrollGeometry : CustomDebugStringConvertible {
/// 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 }
}
/// A type that describes the state of a scroll gesture of a
/// scrollable view like a scroll view.
///
/// A scroll gesture can be in one of four phases:
/// - idle: No active scroll is occurring.
/// - panning: An active scroll being driven by the user
/// is occurring.
/// - decelerating: The user has stopped driving a scroll
/// and the scroll view is decelerating to its final
/// target.
/// - animating: The system is animating to a final target
/// as a result of a programmatic animated scroll from
/// using a ``ScrollViewReader`` or
/// ``View/scrollPosition(id:anchor:)`` modifier.
///
/// SwiftUI provides you a value of this type when using the
/// ``View/onScrollPhaseChange(_:)`` modifier.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, *)
@frozen public enum ScrollPhase : Equatable {
/// The idle phase where no kind of scrolling is occurring.
case idle
/// The tracking phase where the scroll view is tracking
/// a potential scroll by the user but the user hasn't started
/// a scroll.
///
/// For example, on iOS, the user may start touching content
/// inside of the scroll view. Until the user moves their finger
/// the scroll view would be tracking the the finger. Not all
/// platforms or kinds of scroll may trigger this phase.
case tracking
/// The interacting phase where the user is interacting
/// with the scroll view.
case interacting
/// The decelerating phase where the user use has stopped
/// interacting with the scroll view and the scroll view
/// is decelerating towards its final target.
case decelerating
/// The animating phase where the scroll view is animating
/// towards a final target.
///
/// This phase is the result of a programmatic
/// scroll when using a ``ScrollViewReader`` or
/// ``View/scrollPosition(id:anchor:)`` modifier.
///
/// SwiftUI provides you a value of this type when using the
/// ``View/onScrollPhaseChange(_:)`` modifier with a scrollable
/// view like ``ScrollView`` or ``List``.
case animating
/// Whether the scroll view is actively scrolling.
///
/// This convenience is equivalent to `phase != .idle`.
public var isScrolling: Bool { get }
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// 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: ScrollPhase, b: ScrollPhase) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, *)
extension ScrollPhase : CustomDebugStringConvertible {
/// 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 }
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, *)
extension ScrollPhase : Hashable {
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, *)
extension ScrollPhase : Sendable {
}
/// A type that defines the semantic position of where a scroll view is
/// scrolled within its content.
///
/// Use this type along with the ``View/scrollPosition(_:)``
/// modifier to control where a scroll view is positioned. You
/// can use this type to scroll in a variety of ways:
/// - scroll to a view with a provided identity
/// - scroll to a concrete offset
/// - scroll to an edge
///
/// You can create a scroll position with a specified view identity type
///
/// @State private var position = ScrollPosition(idType: MyItem.ID.self)
///
/// SwiftUI will use that along with the views in the scroll view's
/// scroll target layout to programmatically scroll to those views and to
/// update the ``ScrollPosition/viewID`` property as the user scrolls.
/// Use the ``View/scrollTargetLayout()`` modifier to configure
/// which layout contains your scroll targets.
///
/// When scrolling to a view with an identifier, SwiftUI will update
/// the position with the value of the top-most view scrolled within
/// the visible region of the scroll view.
///
/// In the following example, the position binding will update to reflect
/// the top-most ItemView as the scroll view scrolls.
///
/// @Binding var items: [MyItem]
/// @State private var position: ScrollPosition
/// = .init(idType: MyItem.ID.self)
///
/// ScrollView {
/// LazyVStack {
/// ForEach(items) { item in
/// ItemView(item)
/// }
/// }
/// .scrollTargetLayout()
/// }
/// .scrollPosition($scrolledID)
///
/// You can then query the currently scrolled id by using the
/// ``ScrollPosition/viewID(type:)``.
///
/// let viewID: MyItem.ID = position.viewID(type: MyItem.ID.self)
///
/// While most use cases will use view identity based scrolling, you
/// can also use the scroll position type to scroll to offsets or edges.
/// For example, you can create a button that scrolls to the bottom of
/// the scroll view by specifying an edge.
///
/// Button("Scroll to bottom") {
/// position.scrollTo(edge: .bottom)
/// }
///
/// When configuring a scroll position, SwiftUI will attempt to keep that
/// position stable. For an edge, that means keeping a top aligned
/// scroll view scrolled to the top if the content size changes.
/// For a point, SwiftUI won't attempt to keep that exact offset scrolled
/// when the content size changes nor will it update to a new offset
/// when that changes.
///
/// For view identity positions, SwiftUI will attempt to keep the view with
/// the identity specified in the provided binding visible when events occur
/// that might cause it to be scrolled out of view by the system.
/// Some examples of these include:
/// - The data backing the content of a scroll view is re-ordered.
/// - The size of the scroll view changes, like when a window is resized
/// on macOS or during a rotation on iOS.
/// - The scroll view initially lays out it content defaulting to
/// the top most view, but the binding has a different view's identity.
///
/// You can provide an anchor to a view identity based position to:
/// - Influence which view the system chooses as the view whose
/// identity value will update the providing binding as the scroll
/// view scrolls.
/// - Control the alignment of the view when scrolling to a view
/// when writing a new binding value.
///
/// In the example below, the bottom most view will be chosen to update the
/// position binding with.
///
/// ScrollView {
/// LazyVStack {
/// ForEach(items) { item in
/// ItemView(item)
/// }
/// }
/// .scrollTargetLayout()
/// }
/// .scrollPosition($scrolledID, anchor: .bottom)
///
/// For example, providing a value of ``UnitPoint/bottom`` will prefer
/// to have the bottom-most view chosen and prefer to scroll to views
/// aligned to the bottom.
///
/// If no anchor has been provided, SwiftUI will scroll the minimal amount
/// when using the scroll position to programmatically scroll to a view.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public struct ScrollPosition : Sendable {
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension ScrollPosition {
/// Creates a new scroll position to a view with a provided identity value.
///
/// The type of the ID indicates the type of ID of views within a
/// scroll target layout the scroll view should look for.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public init(id: some Hashable & Sendable, anchor: UnitPoint? = nil)
/// Creates a new automatic scroll position.
///
/// You can provide a type to the scroll position. This type should match
/// the type of IDs associated to views in a scroll target layout. The
/// scroll view will look for those views to update the value of
/// the scroll position with.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public init(idType: (some Hashable & Sendable).Type = Never.self)
/// Creates a new scroll position to be scrolled to the provided edge.
///
/// You can provide a type to indicate the type of ID the scroll view
/// should look for views with an ID of that type within its scroll
/// target layout.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public init(idType: (some Hashable & Sendable).Type = Never.self, edge: Edge)
/// Creates a new scroll position to be scrolled to the provided point.
///
/// You can provide a type to the scroll position. This type should match
/// the type of IDs associated to views in a scroll target layout. The
/// scroll view will look for those views to update the value of
/// the scroll position with.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public init(idType: (some Hashable & Sendable).Type = Never.self, point: CGPoint)
/// Creates a new scroll position to be scrolled to the provided x value.
///
/// You can provide a type to the scroll position. This type should match
/// the type of IDs associated to views in a scroll target layout. The
/// scroll view will look for those views to update the value of
/// the scroll position with.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public init(idType: (some Hashable & Sendable).Type = Never.self, x: CGFloat, y: CGFloat)
/// Creates a new scroll position to be scrolled to the provided y value.
///
/// You can provide a type to the scroll position. This type should match
/// the type of IDs associated to views in a scroll target layout. The
/// scroll view will look for those views to update the value of
/// the scroll position with.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public init(idType: (some Hashable & Sendable).Type = Never.self, x: CGFloat)
/// Creates a new scroll position to be scrolled to the provided y value.
///
/// You can provide a type to the scroll position. This type should match
/// the type of IDs associated to views in a scroll target layout. The
/// scroll view will look for those views to update the value of
/// the scroll position with.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public init(idType: (some Hashable & Sendable).Type = Never.self, y: CGFloat)
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension ScrollPosition {
/// Scrolls the position of the scroll view to a view with a identity value
/// and anchor you provide.
///
/// Inform the scroll view of which layout it should look for view's
/// with the identity value you provide using the
/// ``View/scrollTargetLayout()`` modifier.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func scrollTo(id: some Hashable & Sendable, anchor: UnitPoint? = nil)
/// Scrolls the position of the scroll view to the edge you provide.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func scrollTo(edge: Edge)
/// Scrolls the position of the scroll view to the point you provide.
///
/// The scroll view will clamp this value to only scroll to the size of
/// its actual content.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func scrollTo(point: CGPoint)
/// Scrolls the position of the scroll view to the x and y value you
/// provide.
///
/// The scroll view will clamp this value to only scroll to the size of
/// its actual content.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func scrollTo(x: CGFloat, y: CGFloat)
/// Scrolls the position of the scroll view to the x value you provide.
///
/// The scroll view chooses the y value based on the content insets of
/// the scroll view and will clamp this value to only scroll to the
/// size of its actual content.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func scrollTo(x: CGFloat)
/// Scrolls the position of the scroll view to the y value you provide.
///
/// The scroll view chooses the x value based on the content insets of
/// the scroll view and will clamp this value to only scroll to the
/// size of its actual content.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func scrollTo(y: CGFloat)
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension ScrollPosition {
/// Whether the scroll view has been positioned by the user.
///
/// You can write to this property to control whether the scroll view
/// acts as if it has been positioned by the user. If the position had
/// a non-nil edge / point value, that value will become nil when
/// setting this property to true.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public var isPositionedByUser: Bool
/// The positioned edge of the scroll view if configured to be in that
/// position.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public var edge: Edge? { get }
/// The positioned point of the scroll view if configured to be in that
/// position.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public var point: CGPoint? { get }
/// The type-erased id of the view positioned in the scroll view if
/// configured to be in that position or the user has scrolled past a
/// view with an id of matching type.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public var viewID: (any Hashable & Sendable)? { get }
/// The id of the view positioned in the scroll view if configured
/// to be in that position or the user has scrolled past a view with
/// an id of matching type.
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public func viewID<T>(type: T.Type) -> T? where T : Hashable, T : Sendable
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension ScrollPosition : 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: ScrollPosition, rhs: ScrollPosition) -> Bool
}
/// A type defining the target in which a scroll view should try and scroll to.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public struct ScrollTarget {
/// The rect that a scrollable view should try and have contained.
public var rect: CGRect
/// The anchor to which the rect should be aligned within the visible
/// region of the scrollable view.
public var anchor: UnitPoint?
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, *)
extension ScrollTarget : Hashable, Equatable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ScrollTarget, b: ScrollTarget) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
/// A style appropriate for foreground separator or border lines.
///
/// You can also use ``ShapeStyle/separator`` to construct this style.
@available(iOS 17.0, macOS 10.15, tvOS 17.0, watchOS 10.0, *)
public struct SeparatorShapeStyle : ShapeStyle {
/// Creates a new separator shape style instance.
public init()
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
/// A reference to a function in a Metal shader library, along with its
/// bound uniform argument values.
///
/// Shader values can be used as filter effects on views, see the
/// ``View/colorEffect(_:isEnabled:)``,
/// ``View/distortionEffect(_:maxSampleOffset:isEnabled:)``,
/// and ``View/layerEffect(_:maxSampleOffset:isEnabled:)`` functions.
///
/// Shaders also conform to the ``ShapeStyle`` protocol, letting their
/// MSL shader function provide per-pixel color to fill any shape or
/// text view. For a shader function to act as a fill pattern it must
/// have a function signature matching:
///
/// [[ stitchable ]] half4 name(float2 position, args...)
///
/// where `position` is the user-space coordinates of the pixel applied
/// to the shader, and `args...` should be compatible with the uniform
/// arguments bound to `shader`. The function should return the
/// premultiplied color value in the color space of the destination
/// (typically extended sRGB).
///
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
public struct Shader : Equatable, Sendable {
/// A single uniform argument value to a shader function.
public struct Argument : Equatable, Sendable {
/// Returns an argument value representing the MSL value
/// `float(x)`.
public static func float<T>(_ x: T) -> Shader.Argument where T : BinaryFloatingPoint
/// Returns an argument value representing the MSL value
/// `float2(x, y)`.
public static func float2<T>(_ x: T, _ y: T) -> Shader.Argument where T : BinaryFloatingPoint
/// Returns an argument value representing the MSL value
/// `float3(x, y, z)`.
public static func float3<T>(_ x: T, _ y: T, _ z: T) -> Shader.Argument where T : BinaryFloatingPoint
/// Returns an argument value representing the MSL value
/// `float4(x, y, z, w)`.
public static func float4<T>(_ x: T, _ y: T, _ z: T, _ w: T) -> Shader.Argument where T : BinaryFloatingPoint
/// Returns an argument value representing the MSL value
/// `float2(point.x, point.y)`.
public static func float2(_ point: CGPoint) -> Shader.Argument
/// Returns an argument value representing the MSL value
/// `float2(size.width, size.height)`.
public static func float2(_ size: CGSize) -> Shader.Argument
/// Returns an argument value representing the MSL value
/// `float2(vector.dx, vector.dy)`.
public static func float2(_ vector: CGVector) -> Shader.Argument
/// Returns an argument value defined by the provided array of
/// floating point numbers. When passed to an MSL function it
/// will convert to a `device const float *ptr, int count` pair
/// of parameters.
public static func floatArray(_ array: [Float]) -> Shader.Argument
/// Returns an argument value representing the bounding rect of
/// the shape or view that the shader is attached to, as
/// `float4(x, y, width, height)`. This value is undefined for
/// shaders that do not have a natural bounding rect (e.g.
/// filter effects drawn into `GraphicsContext`).
public static var boundingRect: Shader.Argument { get }
/// Returns an argument value representing `color`. When passed
/// to a MSL function it will convert to a `half4` value, as a
/// premultiplied color in the target color space.
public static func color(_ color: Color) -> Shader.Argument
/// Returns an argument value defined by the provided array of
/// color values. When passed to an MSL function it will convert
/// to a `device const half4 *ptr, int count` pair of
/// parameters.
public static func colorArray(_ array: [Color]) -> Shader.Argument
/// Returns an argument value defined by the provided image.
/// When passed to an MSL function it will convert to a
/// `texture2d<half>` value. Currently only one image parameter
/// is supported per `Shader` instance.
public static func image(_ image: Image) -> Shader.Argument
/// Returns an argument value defined by the provided data
/// value. When passed to an MSL function it will convert to a
/// `device const void *ptr, int size_in_bytes` pair of
/// parameters.
public static func data(_ data: Data) -> Shader.Argument
/// 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: Shader.Argument, b: Shader.Argument) -> Bool
}
/// The shader function called by the shader.
public var function: ShaderFunction
/// The uniform argument values passed to the shader function.
public var arguments: [Shader.Argument]
/// For shader functions that return color values, whether the
/// returned color has dither noise added to it, or is simply
/// rounded to the output bit-depth. For shaders generating smooth
/// gradients, dithering is usually necessary to prevent visible
/// banding in the result.
public var dithersColor: Bool
/// Creates a new shader from a function and the uniform argument
/// values to bind to the function.
public init(function: ShaderFunction, arguments: [Shader.Argument])
/// 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: Shader, b: Shader) -> Bool
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, visionOS 2.0, *)
@available(watchOS, unavailable)
extension Shader {
/// Attempts to asynchronously compile a shader function, to
/// minimize the chance of stalling when it is first used for
/// rendering.
///
/// Before being available for rendering each shader must be
/// compiled for the current GPU. By default this happens on first
/// use, but that may cause that frame to be delayed waiting for
/// the compiler, i.e. cause a visible "glitch" in animations.
///
/// Calling this method for each shader before it's first used
/// allows the necessary compilation to happen ahead of time,
/// eliminating the delay on the first actual use (provided
/// `compile()` completes before the first use of the shader).
///
/// For compilation to be successful the specified usage type must
/// match how the shader is eventually used to render, and its
/// current argument values must match the types of the arguments
/// used when rendering (however array and data sizes may be
/// empty).
///
/// For example, to compile a fill shader asynchronously when your
/// app launches:
///
/// Task {
/// let shader = ShaderLibrary.example(.color(.clear), .float(0))
/// try! await shader.compile(as: .shapeStyle)
/// }
///
/// Here the MSL shader function `example` takes two uniform
/// arguments: a color and a numeric value. The placeholder values
/// are replaced with actual values when using the shader, in this
/// case to fill a circle:
///
/// Circle().fill(
/// ShaderLibrary.example(.color(.orange), .float(32)))
///
/// - Parameter type: how the shader will eventually be used.
///
/// - Throws: an error describing why compilation failed.
public func compile(as type: Shader.UsageType) async throws
/// The different ways in which a `Shader` may be used to render.
public struct UsageType : Hashable, Sendable {
/// The shader will be used as a `ShapeStyle` value.
public static let shapeStyle: Shader.UsageType
/// The shader will be used as a color effect.
public static let colorEffect: Shader.UsageType
/// The shader will be used as a geometric distortion effect.
public static let distortionEffect: Shader.UsageType
/// The shader will be used as a layer effect.
public static let layerEffect: Shader.UsageType
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: Shader.UsageType, b: Shader.UsageType) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension Shader {
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, tvOS 17.0, watchOS 10.0, macOS 14.0, *)
public typealias Resolved = Never
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
extension Shader : ShapeStyle {
}
/// A reference to a function in a Metal shader library.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
@dynamicCallable public struct ShaderFunction : Equatable, Sendable {
/// The shader library storing the function.
public var library: ShaderLibrary
/// The name of the shader function in the library.
public var name: String
/// Creates a new function reference from the provided shader
/// library and function name string.
public init(library: ShaderLibrary, name: String)
/// Returns a new shader by applying the provided argument values
/// to the referenced function.
///
/// Typically this subscript is used implicitly via function-call
/// syntax, for example:
///
/// let shader = ShaderLibrary.default.myFunction(.float(42))
///
/// which creates a shader passing the value `42` to the first
/// unbound parameter of `myFunction()`.
public func dynamicallyCall(withArguments args: [Shader.Argument]) -> Shader
/// 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: ShaderFunction, b: ShaderFunction) -> Bool
}
/// A Metal shader library.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, *)
@available(watchOS, unavailable)
@dynamicMemberLookup public struct ShaderLibrary : Equatable, @unchecked Sendable {
/// The default shader library of the main (i.e. app) bundle.
public static let `default`: ShaderLibrary
/// Returns the default shader library of the specified bundle.
public static func bundle(_ bundle: Bundle) -> ShaderLibrary
/// Creates a new Metal shader library from `data`, which must be
/// the contents of precompiled Metal library. Functions compiled
/// from the returned library will only be cached as long as the
/// returned library exists.
public init(data: Data)
/// Creates a new Metal shader library from the contents of `url`,
/// which must be the location of precompiled Metal library.
/// Functions compiled from the returned library will only be
/// cached as long as the returned library exists.
public init(url: URL)
/// Returns a new shader function representing the stitchable MSL
/// function called `name` in the default shader library.
///
/// Typically this subscript is used implicitly via the dynamic
/// member syntax, for example:
///
/// let fn = ShaderLibrary.myFunction
///
/// which creates a reference to the MSL function called
/// `myFunction()`.
public static subscript(dynamicMember name: String) -> ShaderFunction { get }
/// Returns a new shader function representing the stitchable MSL
/// function in the library called `name`.
///
/// Typically this subscript is used implicitly via the dynamic
/// member syntax, for example:
///
/// let fn = ShaderLibrary.default.myFunction
///
/// which creates a reference to the MSL function called
/// `myFunction()`.
public subscript(dynamicMember name: String) -> ShaderFunction { 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 == (lhs: ShaderLibrary, rhs: ShaderLibrary) -> Bool
}
/// A style to use when rendering shadows.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
public struct ShadowStyle : Equatable, Sendable {
/// Creates a custom drop shadow style.
///
/// Drop shadows draw behind the source content by blurring,
/// tinting and offsetting its per-pixel alpha values.
///
/// - Parameters:
/// - color: The shadow's color.
/// - radius: The shadow's size.
/// - x: A horizontal offset you use to position the shadow
/// relative to this view.
/// - y: A vertical offset you use to position the shadow
/// relative to this view.
///
/// - Returns: A new shadow style.
public static func drop(color: Color = .init(.sRGBLinear, white: 0, opacity: 0.33), radius: CGFloat, x: CGFloat = 0, y: CGFloat = 0) -> ShadowStyle
/// Creates a custom inner shadow style.
///
/// Inner shadows draw on top of the source content by blurring,
/// tinting, inverting and offsetting its per-pixel alpha values.
///
/// - Parameters:
/// - color: The shadow's color.
/// - radius: The shadow's size.
/// - x: A horizontal offset you use to position the shadow
/// relative to this view.
/// - y: A vertical offset you use to position the shadow
/// relative to this view.
///
/// - Returns: A new shadow style.
public static func inner(color: Color = .init(.sRGBLinear, white: 0, opacity: 0.55), radius: CGFloat, x: CGFloat = 0, y: CGFloat = 0) -> ShadowStyle
/// 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: ShadowStyle, b: ShadowStyle) -> Bool
}
/// A 2D shape that you can use when drawing a view.
///
/// Shapes without an explicit fill or stroke get a default fill based on the
/// foreground color.
///
/// You can define shapes in relation to an implicit frame of reference, such as
/// the natural size of the view that contains it. Alternatively, you can define
/// shapes in terms of absolute coordinates.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol Shape : Sendable, Animatable, View {
/// 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.
nonisolated 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, *)
nonisolated static var role: ShapeRole { get }
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
nonisolated var layoutDirectionBehavior: LayoutDirectionBehavior { get }
/// Returns the size of the view that will render the shape, given
/// a proposed size.
///
/// Implement this method to tell the container of the shape how
/// much space the shape needs to render itself, given a size
/// proposal.
///
/// See ``Layout/sizeThatFits(proposal:subviews:cache:)``
/// for more details about how the layout system chooses the size of
/// views.
///
/// - Parameters:
/// - proposal: A size proposal for the container.
///
/// - Returns: A size that indicates how much space the shape needs.
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
nonisolated func sizeThatFits(_ proposal: ProposedViewSize) -> CGSize
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Shape {
/// Returns the original proposal, with nil components replaced by
/// a small positive value.
public func sizeThatFits(_ proposal: ProposedViewSize) -> CGSize
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension Shape {
/// 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 }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Shape {
/// Returns the behavior this shape should use for different layout
/// directions.
///
/// If the layoutDirectionBehavior for a Shape is one that mirrors, the
/// shape's path will be mirrored horizontally when in the specified layout
/// direction. When mirrored, the individual points of the path will be
/// transformed.
///
/// Defaults to `.mirrors` when deploying on iOS 17.0, macOS 14.0,
/// tvOS 17.0, watchOS 10.0 and later, and to `.fixed` if not.
/// To mirror a path when deploying to earlier releases, either use
/// `View.flipsForRightToLeftLayoutDirection` for a filled or stroked
/// shape or conditionally mirror the points in the path of the shape.
public var layoutDirectionBehavior: LayoutDirectionBehavior { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Shape {
/// Returns a new shape that is a stroked copy of `self`, using the
/// contents of `style` to define the stroke characteristics.
@inlinable public func stroke(style: StrokeStyle) -> some Shape
/// Returns a new shape that is a stroked copy of `self` with
/// line-width defined by `lineWidth` and all other properties of
/// `StrokeStyle` having their default values.
@inlinable public func stroke(lineWidth: CGFloat = 1) -> some Shape
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Shape where Self == Rectangle {
/// A rectangular shape aligned inside the frame of the view containing it.
public static var rect: Rectangle { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Shape where Self == RoundedRectangle {
/// A rectangular shape with rounded corners, aligned inside the frame of
/// the view containing it.
public static func rect(cornerSize: CGSize, style: RoundedCornerStyle = .continuous) -> Self
/// A rectangular shape with rounded corners, aligned inside the frame of
/// the view containing it.
public static func rect(cornerRadius: CGFloat, style: RoundedCornerStyle = .continuous) -> Self
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension Shape where Self == UnevenRoundedRectangle {
/// A rectangular shape with rounded corners with different values, aligned
/// inside the frame of the view containing it.
public static func rect(cornerRadii: RectangleCornerRadii, style: RoundedCornerStyle = .continuous) -> Self
/// A rectangular shape with rounded corners with different values, aligned
/// inside the frame of the view containing it.
public static func rect(topLeadingRadius: CGFloat = 0, bottomLeadingRadius: CGFloat = 0, bottomTrailingRadius: CGFloat = 0, topTrailingRadius: CGFloat = 0, style: RoundedCornerStyle = .continuous) -> Self
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Shape where Self == Capsule {
/// 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.
public static var capsule: Capsule { get }
/// 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.
public static func capsule(style: RoundedCornerStyle) -> Self
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Shape where Self == Ellipse {
/// An ellipse aligned inside the frame of the view containing it.
public static var ellipse: Ellipse { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Shape where Self == Circle {
/// 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.
public static var circle: Circle { get }
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Shape where Self == ContainerRelativeShape {
/// 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.
public static var containerRelative: ContainerRelativeShape { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Shape {
/// Fills this shape with a color or gradient.
///
/// - Parameters:
/// - content: The color or gradient to use when filling this shape.
/// - style: The style options that determine how the fill renders.
/// - Returns: A shape filled with the color or gradient you supply.
@inlinable public func fill<S>(_ content: S, style: FillStyle = FillStyle()) -> some View where S : ShapeStyle
/// Fills this shape with the foreground color.
///
/// - Parameter style: The style options that determine how the fill
/// renders.
/// - Returns: A shape filled with the foreground color.
@inlinable public func fill(style: FillStyle = FillStyle()) -> some View
/// Traces the outline of this shape with a color or gradient.
///
/// The following example adds a dashed purple stroke to a `Capsule`:
///
/// Capsule()
/// .stroke(
/// Color.purple,
/// style: StrokeStyle(
/// lineWidth: 5,
/// lineCap: .round,
/// lineJoin: .miter,
/// miterLimit: 0,
/// dash: [5, 10],
/// dashPhase: 0
/// )
/// )
///
/// - Parameters:
/// - content: The color or gradient with which to stroke this shape.
/// - style: The stroke characteristics --- such as the line's width and
/// whether the stroke is dashed --- that determine how to render this
/// shape.
/// - Returns: A stroked shape.
@inlinable public func stroke<S>(_ content: S, style: StrokeStyle) -> some View where S : ShapeStyle
/// Traces the outline of this shape with a color or gradient.
///
/// The following example draws a circle with a purple stroke:
///
/// Circle().stroke(Color.purple, lineWidth: 5)
///
/// - Parameters:
/// - content: The color or gradient with which to stroke this shape.
/// - lineWidth: The width of the stroke that outlines this shape.
/// - Returns: A stroked shape.
@inlinable public func stroke<S>(_ content: S, lineWidth: CGFloat = 1) -> some View where S : ShapeStyle
}
/// A shape acts as view by filling itself with the foreground color and
/// default fill style.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension Shape {
/// The content and behavior of the view.
///
/// When you implement a custom view, you must implement a computed
/// `body` property to provide the content for your view. Return a view
/// that's composed of built-in views that SwiftUI provides, plus other
/// composite views that you've already defined:
///
/// struct MyView: View {
/// var body: some View {
/// Text("Hello, World!")
/// }
/// }
///
/// For more information about composing views and a view hierarchy,
/// see <doc:Declaring-a-Custom-View>.
public var body: _ShapeView<Self, ForegroundStyle> { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension Shape {
/// Fills this shape with a color or gradient.
///
/// - Parameters:
/// - content: The color or gradient to use when filling this shape.
/// - style: The style options that determine how the fill renders.
/// - Returns: A shape filled with the color or gradient you supply.
public func fill<S>(_ content: S = .foreground, style: FillStyle = FillStyle()) -> _ShapeView<Self, S> where S : ShapeStyle
/// Traces the outline of this shape with a color or gradient.
///
/// The following example adds a dashed purple stroke to a `Capsule`:
///
/// Capsule()
/// .stroke(
/// Color.purple,
/// style: StrokeStyle(
/// lineWidth: 5,
/// lineCap: .round,
/// lineJoin: .miter,
/// miterLimit: 0,
/// dash: [5, 10],
/// dashPhase: 0
/// )
/// )
///
/// - Parameters:
/// - content: The color or gradient with which to stroke this shape.
/// - style: The stroke characteristics --- such as the line's width and
/// whether the stroke is dashed --- that determine how to render this
/// shape.
/// - Returns: A stroked shape.
public func stroke<S>(_ content: S, style: StrokeStyle, antialiased: Bool = true) -> StrokeShapeView<Self, S, EmptyView> where S : ShapeStyle
/// Traces the outline of this shape with a color or gradient.
///
/// The following example draws a circle with a purple stroke:
///
/// Circle().stroke(Color.purple, lineWidth: 5)
///
/// - Parameters:
/// - content: The color or gradient with which to stroke this shape.
/// - lineWidth: The width of the stroke that outlines this shape.
/// - Returns: A stroked shape.
public func stroke<S>(_ content: S, lineWidth: CGFloat = 1, antialiased: Bool = true) -> StrokeShapeView<Self, S, EmptyView> where S : ShapeStyle
}
/// Ways of styling a shape.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public enum ShapeRole : Sendable {
/// Indicates to the shape's style that SwiftUI fills the shape.
case fill
/// Indicates to the shape's style that SwiftUI applies a stroke to
/// the shape's path.
case stroke
/// Indicates to the shape's style that SwiftUI uses the shape as a
/// separator.
case separator
/// 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: ShapeRole, b: ShapeRole) -> Bool
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
/// The compiler provides an implementation for `hashValue` for you.
public var hashValue: Int { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ShapeRole : Equatable {
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ShapeRole : Hashable {
}
/// A color or pattern to use when rendering a shape.
///
/// You create custom shape styles by declaring a type that conforms to the
/// `ShapeStyle` protocol and implementing the required `resolve` function to
/// return a shape style that represents the desired appearance based on the
/// current environment.
///
/// For example this shape style reads the current color scheme from the
/// environment to choose the blend mode its color will be composited with:
///
/// struct MyShapeStyle: ShapeStyle {
/// func resolve(in environment: EnvironmentValues) -> some ShapeStyle {
/// if environment.colorScheme == .light {
/// return Color.red.blendMode(.lighten)
/// } else {
/// return Color.red.blendMode(.darken)
/// }
/// }
/// }
///
/// In addition to creating a custom shape style, you can also use one of the
/// concrete styles that SwiftUI defines. To indicate a specific color or
/// pattern, you can use ``Color`` or the style returned by
/// ``ShapeStyle/image(_:sourceRect:scale:)``, or one of the gradient
/// types, like the one returned by
/// ``ShapeStyle/radialGradient(_:center:startRadius:endRadius:)``.
/// To set a color that's appropriate for a given context on a given
/// platform, use one of the semantic styles, like ``ShapeStyle/background`` or
/// ``ShapeStyle/primary``.
///
/// You can use a shape style by:
/// * Filling a shape with a style with the ``Shape/fill(_:style:)``
/// modifier:
///
/// ```
/// Path { path in
/// path.move(to: .zero)
/// path.addLine(to: CGPoint(x: 50, y: 0))
/// path.addArc(
/// center: .zero,
/// radius: 50,
/// startAngle: .zero,
/// endAngle: .degrees(90),
/// clockwise: false)
/// }
/// .fill(.radialGradient(
/// Gradient(colors: [.yellow, .red]),
/// center: .topLeading,
/// startRadius: 15,
/// endRadius: 80))
/// ```
///
/// ![A screenshot of a quarter of a circle filled with
/// a radial gradient.](ShapeStyle-1)
///
/// * Tracing the outline of a shape with a style with either the
/// ``Shape/stroke(_:lineWidth:)`` or the ``Shape/stroke(_:style:)`` modifier:
///
/// ```
/// RoundedRectangle(cornerRadius: 10)
/// .stroke(.mint, lineWidth: 10)
/// .frame(width: 200, height: 50)
/// ```
///
/// ![A screenshot of a rounded rectangle, outlined in mint.](ShapeStyle-2)
///
/// * Styling the foreground elements in a view with the
/// ``View/foregroundStyle(_:)`` modifier:
///
/// ```
/// VStack(alignment: .leading) {
/// Text("Primary")
/// .font(.title)
/// Text("Secondary")
/// .font(.caption)
/// .foregroundStyle(.secondary)
/// }
/// ```
///
/// ![A screenshot of a title in the primary content color above a
/// subtitle in the secondary content color.](ShapeStyle-3)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol ShapeStyle : Sendable {
/// The type of shape style this will resolve to.
///
/// When you create a custom shape style, Swift infers this type
/// from your implementation of the required `resolve` function.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
associatedtype Resolved : ShapeStyle = Never
/// Evaluate to a resolved shape style given the current `environment`.
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
func resolve(in environment: EnvironmentValues) -> Self.Resolved
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ShapeStyle where Self == LinearGradient {
/// 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.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func linearGradient(_ gradient: Gradient, startPoint: UnitPoint, endPoint: UnitPoint) -> LinearGradient
/// A linear gradient defined by a collection of colors.
///
/// 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.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func linearGradient(colors: [Color], startPoint: UnitPoint, endPoint: UnitPoint) -> LinearGradient
/// A linear gradient defined by a collection of color stops.
///
/// 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.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func linearGradient(stops: [Gradient.Stop], startPoint: UnitPoint, endPoint: UnitPoint) -> LinearGradient
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ShapeStyle where Self == RadialGradient {
/// 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.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func radialGradient(_ gradient: Gradient, center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat) -> RadialGradient
/// A radial gradient defined by a collection of colors.
///
/// 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.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func radialGradient(colors: [Color], center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat) -> RadialGradient
/// A radial gradient defined by a collection of color stops.
///
/// 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.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func radialGradient(stops: [Gradient.Stop], center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat) -> RadialGradient
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ShapeStyle where Self == EllipticalGradient {
/// 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 used as a background:
///
/// let gradient = Gradient(colors: [.red, .yellow])
///
/// ContentView()
/// .background(.ellipticalGradient(gradient))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func ellipticalGradient(_ gradient: Gradient, center: UnitPoint = .center, startRadiusFraction: CGFloat = 0, endRadiusFraction: CGFloat = 0.5) -> EllipticalGradient
/// A radial gradient that draws an ellipse defined by a collection of
/// colors.
///
/// 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 used as a background:
///
/// .background(.elliptical(colors: [.red, .yellow]))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func ellipticalGradient(colors: [Color], center: UnitPoint = .center, startRadiusFraction: CGFloat = 0, endRadiusFraction: CGFloat = 0.5) -> EllipticalGradient
/// A radial gradient that draws an ellipse defined by a collection of
/// color stops.
///
/// 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 used as a background:
///
/// .background(.ellipticalGradient(stops: [
/// .init(color: .red, location: 0.0),
/// .init(color: .yellow, location: 0.9),
/// .init(color: .yellow, location: 1.0),
/// ]))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func ellipticalGradient(stops: [Gradient.Stop], center: UnitPoint = .center, startRadiusFraction: CGFloat = 0, endRadiusFraction: CGFloat = 0.5) -> EllipticalGradient
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ShapeStyle where Self == AngularGradient {
/// An angular gradient, which applies the color function as the angle
/// changes between the start and end angles, and anchored to a relative
/// center point within the filled shape.
///
/// An angular gradient is also known as a "conic" gradient. 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 stop locations at `0` and `1`,
/// transitioning between the two halfway across the missing area.
///
/// For example, an angular gradient used as a background:
///
/// let gradient = Gradient(colors: [.red, .yellow])
///
/// ContentView()
/// .background(.angularGradient(gradient))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
///
/// - Parameters:
/// - gradient: The gradient to use for filling the shape, providing the
/// colors and their relative stop locations.
/// - center: The relative center of the gradient, mapped from the unit
/// space into the bounding rectangle of the filled shape.
/// - startAngle: The angle that marks the beginning of the gradient.
/// - endAngle: The angle that marks the end of the gradient.
public static func angularGradient(_ gradient: Gradient, center: UnitPoint, startAngle: Angle, endAngle: Angle) -> AngularGradient
/// An angular gradient defined by a collection of colors.
///
/// For more information on how to use angular gradients, see
/// ``ShapeStyle/angularGradient(_:center:startAngle:endAngle:)``.
///
/// - Parameters:
/// - colors: The colors of the gradient, evenly spaced along its full
/// length.
/// - center: The relative center of the gradient, mapped from the unit
/// space into the bounding rectangle of the filled shape.
/// - startAngle: The angle that marks the beginning of the gradient.
/// - endAngle: The angle that marks the end of the gradient.
public static func angularGradient(colors: [Color], center: UnitPoint, startAngle: Angle, endAngle: Angle) -> AngularGradient
/// An angular gradient defined by a collection of color stops.
///
/// For more information on how to use angular gradients, see
/// ``ShapeStyle/angularGradient(_:center:startAngle:endAngle:)``.
///
/// - Parameters:
/// - stops: The color stops of the gradient, defining each component
/// color and their relative location along the gradient's full length.
/// - center: The relative center of the gradient, mapped from the unit
/// space into the bounding rectangle of the filled shape.
/// - startAngle: The angle that marks the beginning of the gradient.
/// - endAngle: The angle that marks the end of the gradient.
public static func angularGradient(stops: [Gradient.Stop], center: UnitPoint, startAngle: Angle, endAngle: Angle) -> AngularGradient
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ShapeStyle where Self == AngularGradient {
/// A conic gradient that completes a full turn, optionally starting from
/// a given angle and anchored to a relative center point within the filled
/// shape.
///
/// For example, a conic gradient used as a background:
///
/// let gradient = Gradient(colors: [.red, .yellow])
///
/// ContentView()
/// .background(.conicGradient(gradient))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
///
/// - Parameters:
/// - gradient: The gradient to use for filling the shape, providing the
/// colors and their relative stop locations.
/// - center: The relative center of the gradient, mapped from the unit
/// space into the bounding rectangle of the filled shape.
/// - angle: The angle to offset the beginning of the gradient's full
/// turn.
public static func conicGradient(_ gradient: Gradient, center: UnitPoint, angle: Angle = .zero) -> AngularGradient
/// A conic gradient defined by a collection of colors that completes a full
/// turn.
///
/// For more information on how to use conic gradients, see
/// ``ShapeStyle/conicGradient(_:center:angle:)``.
///
/// - Parameters:
/// - colors: The colors of the gradient, evenly spaced along its full
/// length.
/// - center: The relative center of the gradient, mapped from the unit
/// space into the bounding rectangle of the filled shape.
/// - angle: The angle to offset the beginning of the gradient's full
/// turn.
public static func conicGradient(colors: [Color], center: UnitPoint, angle: Angle = .zero) -> AngularGradient
/// A conic gradient defined by a collection of color stops that completes a
/// full turn.
///
/// For more information on how to use conic gradients, see
/// ``ShapeStyle/conicGradient(_:center:angle:)``.
///
/// - Parameters:
/// - stops: The color stops of the gradient, defining each component
/// color and their relative location along the gradient's full length.
/// - center: The relative center of the gradient, mapped from the unit
/// space into the bounding rectangle of the filled shape.
/// - angle: The angle to offset the beginning of the gradient's full
/// turn.
public static func conicGradient(stops: [Gradient.Stop], center: UnitPoint, angle: Angle = .zero) -> AngularGradient
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ShapeStyle where Self == LinearGradient {
/// 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.
///
/// For example, a linear gradient used as a background:
///
/// ContentView()
/// .background(.linearGradient(.red.gradient,
/// startPoint: .top, endPoint: .bottom))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func linearGradient(_ gradient: AnyGradient, startPoint: UnitPoint, endPoint: UnitPoint) -> some ShapeStyle
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ShapeStyle where Self == RadialGradient {
/// 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.
///
/// For example, a radial gradient used as a background:
///
/// ContentView()
/// .background(.radialGradient(.red.gradient, endRadius: 100))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func radialGradient(_ gradient: AnyGradient, center: UnitPoint = .center, startRadius: CGFloat = 0, endRadius: CGFloat) -> some ShapeStyle
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ShapeStyle where Self == EllipticalGradient {
/// 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 used as a background:
///
/// ContentView()
/// .background(.ellipticalGradient(.red.gradient))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static func ellipticalGradient(_ gradient: AnyGradient, center: UnitPoint = .center, startRadiusFraction: CGFloat = 0, endRadiusFraction: CGFloat = 0.5) -> some ShapeStyle
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ShapeStyle where Self == AngularGradient {
/// An angular gradient, which applies the color function as the
/// angle changes between the start and end angles, and anchored to
/// a relative center point within the filled shape.
///
/// An angular gradient is also known as a "conic" gradient. 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 stop locations at `0` and `1`,
/// transitioning between the two halfway across the missing area.
///
/// For example, an angular gradient used as a background:
///
/// ContentView()
/// .background(.angularGradient(.red.gradient))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
///
/// - Parameters:
/// - gradient: The gradient to use for filling the shape, providing the
/// colors and their relative stop locations.
/// - center: The relative center of the gradient, mapped from the unit
/// space into the bounding rectangle of the filled shape.
/// - startAngle: The angle that marks the beginning of the gradient.
/// - endAngle: The angle that marks the end of the gradient.
public static func angularGradient(_ gradient: AnyGradient, center: UnitPoint = .center, startAngle: Angle, endAngle: Angle) -> some ShapeStyle
/// A conic gradient that completes a full turn, optionally starting from
/// a given angle and anchored to a relative center point within the filled
/// shape.
///
/// For example, a conic gradient used as a background:
///
/// let gradient = Gradient(colors: [.red, .yellow])
///
/// ContentView()
/// .background(.conicGradient(gradient))
///
/// For information about how to use shape styles, see ``ShapeStyle``.
///
/// - Parameters:
/// - gradient: The gradient to use for filling the shape, providing the
/// colors and their relative stop locations.
/// - center: The relative center of the gradient, mapped from the unit
/// space into the bounding rectangle of the filled shape.
/// - angle: The angle to offset the beginning of the gradient's full
/// turn.
public static func conicGradient(_ gradient: AnyGradient, center: UnitPoint = .center, angle: Angle = .zero) -> some ShapeStyle
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ShapeStyle where Self == ImagePaint {
/// A shape style that fills a shape by repeating a region of an image.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
///
/// - 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 static func image(_ image: Image, sourceRect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1), scale: CGFloat = 1) -> ImagePaint
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ShapeStyle where Self == AnyShapeStyle {
/// Returns a new style based on the current style that multiplies
/// by `opacity` when drawing.
///
/// In most contexts the current style is the foreground but e.g.
/// when setting the value of the background style, that becomes
/// the current implicit style.
///
/// For example, a circle filled with the current foreground
/// style at fifty-percent opacity:
///
/// Circle().fill(.opacity(0.5))
///
public static func opacity(_ opacity: Double) -> some ShapeStyle
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ShapeStyle {
/// Returns a new style based on `self` that applies the specified
/// blend mode when drawing.
@inlinable public func blendMode(_ mode: BlendMode) -> some ShapeStyle
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ShapeStyle where Self == AnyShapeStyle {
/// Returns a new style based on the current style that uses
/// `mode` as its blend mode when drawing.
///
/// In most contexts the current style is the foreground but e.g.
/// when setting the value of the background style, that becomes
/// the current implicit style.
///
/// For example, a circle filled with the current foreground
/// style and the overlay blend mode:
///
/// Circle().fill(.blendMode(.overlay))
///
public static func blendMode(_ mode: BlendMode) -> some ShapeStyle
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 10.0, *)
extension ShapeStyle where Self == Material {
/// A material that's somewhat translucent.
public static var regularMaterial: Material { get }
/// A material that's more opaque than translucent.
public static var thickMaterial: Material { get }
/// A material that's more translucent than opaque.
public static var thinMaterial: Material { get }
/// A mostly translucent material.
public static var ultraThinMaterial: Material { get }
/// A mostly opaque material.
public static var ultraThickMaterial: Material { get }
}
@available(iOS 15.0, macOS 12.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension ShapeStyle where Self == Material {
/// A material matching the style of system toolbars.
public static var bar: Material { get }
}
@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension ShapeStyle {
/// Sets an explicit active appearance for materials created by this style.
public func materialActiveAppearance(_ appearance: MaterialActiveAppearance) -> some ShapeStyle
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ShapeStyle where Self == HierarchicalShapeStyle {
/// A shape style that maps to the first level of the current content style.
///
/// This hierarchical style maps to the first level of the current
/// foreground style, or to the first level of the default foreground style
/// if you haven't set a foreground style in the view's environment. You
/// typically set a foreground style by supplying a non-hierarchical style
/// to the ``View/foregroundStyle(_:)`` modifier.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static var primary: HierarchicalShapeStyle { get }
/// A shape style that maps to the second level of the current content style.
///
/// This hierarchical style maps to the second level of the current
/// foreground style, or to the second level of the default foreground style
/// if you haven't set a foreground style in the view's environment. You
/// typically set a foreground style by supplying a non-hierarchical style
/// to the ``View/foregroundStyle(_:)`` modifier.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static var secondary: HierarchicalShapeStyle { get }
/// A shape style that maps to the third level of the current content
/// style.
///
/// This hierarchical style maps to the third level of the current
/// foreground style, or to the third level of the default foreground style
/// if you haven't set a foreground style in the view's environment. You
/// typically set a foreground style by supplying a non-hierarchical style
/// to the ``View/foregroundStyle(_:)`` modifier.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static var tertiary: HierarchicalShapeStyle { get }
/// A shape style that maps to the fourth level of the current content
/// style.
///
/// This hierarchical style maps to the fourth level of the current
/// foreground style, or to the fourth level of the default foreground style
/// if you haven't set a foreground style in the view's environment. You
/// typically set a foreground style by supplying a non-hierarchical style
/// to the ``View/foregroundStyle(_:)`` modifier.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static var quaternary: HierarchicalShapeStyle { get }
}
@available(iOS 16.0, macOS 12.0, macCatalyst 15.0, tvOS 17.0, watchOS 10.0, *)
extension ShapeStyle where Self == HierarchicalShapeStyle {
/// A shape style that maps to the fifth level of the current content
/// style.
///
/// This hierarchical style maps to the fifth level of the current
/// foreground style, or to the fifth level of the default foreground style
/// if you haven't set a foreground style in the view's environment. You
/// typically set a foreground style by supplying a non-hierarchical style
/// to the ``View/foregroundStyle(_:)`` modifier.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static var quinary: HierarchicalShapeStyle { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension ShapeStyle {
/// Returns the second level of this shape style.
public var secondary: some ShapeStyle { get }
/// Returns the third level of this shape style.
public var tertiary: some ShapeStyle { get }
/// Returns the fourth level of this shape style.
public var quaternary: some ShapeStyle { get }
/// Returns the fifth level of this shape style.
public var quinary: some ShapeStyle { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ShapeStyle where Self == Color {
/// A context-dependent red color suitable for use in UI elements.
public static var red: Color { get }
/// A context-dependent orange color suitable for use in UI elements.
public static var orange: Color { get }
/// A context-dependent yellow color suitable for use in UI elements.
public static var yellow: Color { get }
/// A context-dependent green color suitable for use in UI elements.
public static var green: Color { get }
/// 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 var mint: Color { get }
/// 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 var teal: Color { get }
/// 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 var cyan: Color { get }
/// A context-dependent blue color suitable for use in UI elements.
public static var blue: Color { get }
/// 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 var indigo: Color { get }
/// A context-dependent purple color suitable for use in UI elements.
public static var purple: Color { get }
/// A context-dependent pink color suitable for use in UI elements.
public static var pink: Color { get }
/// 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 var brown: Color { get }
/// A white color suitable for use in UI elements.
public static var white: Color { get }
/// A context-dependent gray color suitable for use in UI elements.
public static var gray: Color { get }
/// A black color suitable for use in UI elements.
public static var black: Color { get }
/// A clear color suitable for use in UI elements.
public static var clear: Color { get }
}
@available(iOS 17.0, macOS 10.15, tvOS 17.0, watchOS 10.0, *)
extension ShapeStyle where Self == SeparatorShapeStyle {
/// A style appropriate for foreground separator or border lines.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static var separator: SeparatorShapeStyle { get }
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ShapeStyle {
/// Applies the specified shadow effect to the shape style.
///
/// For example, you can create a rectangle that adds a drop shadow to
/// the ``ShapeStyle/red`` shape style.
///
/// Rectangle().fill(.red.shadow(.drop(radius: 2, y: 3)))
///
/// - Parameter style: The shadow style to apply.
///
/// - Returns: A new shape style that uses the specified shadow style.
@inlinable public func shadow(_ style: ShadowStyle) -> some ShapeStyle
}
@available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)
extension ShapeStyle where Self == AnyShapeStyle {
/// Returns a shape style that applies the specified shadow style to the
/// current style.
///
/// In most contexts the current style is the foreground, but not always.
/// For example, when setting the value of the background style, that
/// becomes the current implicit style.
///
/// The following example creates a circle filled with the current
/// foreground style that uses an inner shadow:
///
/// Circle().fill(.shadow(.inner(radius: 1, y: 1)))
///
/// - Parameter style: The shadow style to apply.
///
/// - Returns: A new shape style based on the current style that uses the
/// specified shadow style.
public static func shadow(_ style: ShadowStyle) -> some ShapeStyle
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ShapeStyle {
/// Maps a shape style's unit-space coordinates to the absolute coordinates
/// of a given rectangle.
///
/// Some shape styles have colors or patterns that vary
/// with position based on ``UnitPoint`` coordinates. For example, you
/// can create a ``LinearGradient`` using ``UnitPoint/top`` and
/// ``UnitPoint/bottom`` as the start and end points:
///
/// let gradient = LinearGradient(
/// colors: [.red, .yellow],
/// startPoint: .top,
/// endPoint: .bottom)
///
/// When rendering such styles, SwiftUI maps the unit space coordinates to
/// the absolute coordinates of the filled shape. However, you can tell
/// SwiftUI to use a different set of coordinates by supplying a rectangle
/// to the `in(_:)` method. Consider two resizable rectangles using the
/// gradient defined above:
///
/// HStack {
/// Rectangle()
/// .fill(gradient)
/// Rectangle()
/// .fill(gradient.in(CGRect(x: 0, y: 0, width: 0, height: 300)))
/// }
/// .onTapGesture { isBig.toggle() }
/// .frame(height: isBig ? 300 : 50)
/// .animation(.easeInOut)
///
/// When `isBig` is true — defined elsewhere as a private ``State``
/// variable — the rectangles look the same, because their heights
/// match that of the modified gradient:
///
/// ![Two identical, tall rectangles, with a gradient that starts red at
/// the top and transitions to yellow at the bottom.](ShapeStyle-in-1)
///
/// When the user toggles `isBig` by tapping the ``HStack``, the
/// rectangles shrink, but the gradients each react in a different way:
///
/// ![Two short rectangles with different coloration. The first has a
/// gradient that transitions top to bottom from full red to full yellow.
/// The second starts as red at the top and then begins to transition
/// to yellow toward the bottom.](ShapeStyle-in-2)
///
/// SwiftUI remaps the gradient of the first rectangle to the new frame
/// height, so that you continue to see the full range of colors in a
/// smaller area. For the second rectangle, the modified gradient retains
/// a mapping to the full height, so you instead see only a small part of
/// the overall gradient. Animation helps to visualize the difference.
///
/// - Parameter rect: A rectangle that gives the absolute coordinates over
/// which to map the shape style.
/// - Returns: A new shape style mapped to the coordinates given by `rect`.
@inlinable public func `in`(_ rect: CGRect) -> some ShapeStyle
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension ShapeStyle where Self == BackgroundStyle {
/// The background style in the current context.
///
/// Access this value to get the style SwiftUI uses for the background
/// in the current context. The specific color that SwiftUI renders depends
/// on factors like the platform and whether the user has turned on Dark
/// Mode.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static var background: BackgroundStyle { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ShapeStyle where Self == ForegroundStyle {
/// The foreground style in the current context.
///
/// Access this value to get the style SwiftUI uses for foreground elements,
/// like text, symbols, and shapes, in the current context. Use the
/// ``View/foregroundStyle(_:)`` modifier to set a new foreground style for
/// a given view and its child views.
///
/// For information about how to use shape styles, see ``ShapeStyle``.
public static var foreground: ForegroundStyle { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension ShapeStyle where Self.Resolved == Never {
/// Evaluate to a resolved shape style given the current `environment`.
public func resolve(in environment: EnvironmentValues) -> Never
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ShapeStyle where Self : View, Self.Body == _ShapeView<Rectangle, Self> {
/// A rectangular view that's filled with the shape style.
///
/// For a ``ShapeStyle`` that also conforms to the ``View`` protocol, like
/// ``Color`` or ``LinearGradient``, this default implementation of the
/// ``View/body-swift.property`` property provides a visual representation
/// for the shape style. As a result, you can use the shape style in a view
/// hierarchy like any other view:
///
/// ZStack {
/// Color.cyan
/// Text("Hello!")
/// }
/// .frame(width: 200, height: 50)
///
/// ![A screenshot of a cyan rectangle with the text hello appearing
/// in the middle of the rectangle.](ShapeStyle-body-1)
public var body: _ShapeView<Rectangle, Self> { get }
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
extension ShapeStyle where Self == TintShapeStyle {
/// A style that reflects the current tint color.
///
/// You can set the tint color with the `tint(_:)` modifier. If no explicit
/// tint is set, the tint is derived from the app's accent color.
public static var tint: TintShapeStyle { get }
}
/// A view that provides a shape that you can use for drawing operations.
///
/// Use this type with the drawing methods on ``Shape`` to apply multiple fills
/// and/or strokes to a shape. For example, the following code applies a fill
/// and stroke to a capsule shape:
///
/// Capsule()
/// .fill(.yellow)
/// .stroke(.blue, lineWidth: 8)
///
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
public protocol ShapeView<Content> : View {
/// The type of shape this can provide.
associatedtype Content : Shape
/// The shape that this type draws and provides for other drawing
/// operations.
var shape: Self.Content { get }
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension ShapeView {
/// Fills this shape with a color or gradient.
///
/// - Parameters:
/// - content: The color or gradient to use when filling this shape.
/// - style: The style options that determine how the fill renders.
/// - Returns: A shape filled with the color or gradient you supply.
public func fill<S>(_ content: S = .foreground, style: FillStyle = FillStyle()) -> FillShapeView<Self.Content, S, Self> where S : ShapeStyle
/// Traces the outline of this shape with a color or gradient.
///
/// The following example adds a dashed purple stroke to a `Capsule`:
///
/// Capsule()
/// .stroke(
/// Color.purple,
/// style: StrokeStyle(
/// lineWidth: 5,
/// lineCap: .round,
/// lineJoin: .miter,
/// miterLimit: 0,
/// dash: [5, 10],
/// dashPhase: 0
/// )
/// )
///
/// - Parameters:
/// - content: The color or gradient with which to stroke this shape.
/// - style: The stroke characteristics --- such as the line's width and
/// whether the stroke is dashed --- that determine how to render this
/// shape.
/// - Returns: A stroked shape.
public func stroke<S>(_ content: S, style: StrokeStyle, antialiased: Bool = true) -> StrokeShapeView<Self.Content, S, Self> where S : ShapeStyle
/// Traces the outline of this shape with a color or gradient.
///
/// The following example draws a circle with a purple stroke:
///
/// Circle().stroke(Color.purple, lineWidth: 5)
///
/// - Parameters:
/// - content: The color or gradient with which to stroke this shape.
/// - lineWidth: The width of the stroke that outlines this shape.
/// - Returns: A stroked shape.
public func stroke<S>(_ content: S, lineWidth: CGFloat = 1, antialiased: Bool = true) -> StrokeShapeView<Self.Content, S, Self> where S : ShapeStyle
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
extension ShapeView where Self.Content : InsettableShape {
/// Returns a view that's the result of insetting this view by half of its style's line width.
///
/// This method strokes the resulting shape with
/// `style` and fills it with `content`.
public func strokeBorder<S>(_ content: S = .foreground, style: StrokeStyle, antialiased: Bool = true) -> StrokeBorderShapeView<Self.Content, S, Self> where S : ShapeStyle
/// Returns a view that's the result of filling an inner stroke of this view with the content you supply.
///
/// This is equivalent to insetting `self` by `lineWidth / 2` and stroking the
/// resulting shape with `lineWidth` as the line-width.
public func strokeBorder<S>(_ content: S = .foreground, lineWidth: CGFloat = 1, antialiased: Bool = true) -> StrokeBorderShapeView<Self.Content, S, Self> where S : ShapeStyle
}
/// A gesture containing two gestures that can happen at the same time with
/// neither of them preceding the other.
///
/// A simultaneous gesture is a container-event handler that evaluates its two
/// child gestures at the same time. Its value is a struct with two optional
/// values, each representing the phases of one of the two gestures.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@frozen public struct SimultaneousGesture<First, Second> : Gesture where First : Gesture, Second : Gesture {
/// The value of a simultaneous gesture that indicates which of its two
/// gestures receives events.
@frozen public struct Value {
/// The value of the first gesture.
public var first: First.Value?
/// The value of the second gesture.
public var second: Second.Value?
}
/// The first of two gestures that can happen simultaneously.
public var first: First
/// The second of two gestures that can happen simultaneously.
public var second: Second
/// Creates a gesture with two gestures that can receive updates or succeed
/// independently of each other.
///
/// - Parameters:
/// - first: The first of two gestures that can happen simultaneously.
/// - second: The second of two gestures that can happen simultaneously.
@inlinable public init(_ first: First, _ second: Second)
/// The type of gesture representing the body of `Self`.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public typealias Body = Never
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension SimultaneousGesture.Value : Sendable where First.Value : Sendable, Second.Value : Sendable {
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension SimultaneousGesture.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: SimultaneousGesture<First, Second>.Value, b: SimultaneousGesture<First, Second>.Value) -> Bool
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment