### Toolbar Item Collection Example Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-alias-and-output.md An example implementation of the ViewOutputKey protocol for collecting ToolbarItem views. It appends new toolbar items to the existing collection. ```swift struct ToolbarItemKey: ViewOutputKey { typealias Content = ToolbarItem static func reduce( value: inout ViewOutputList, nextValue: () -> ViewOutputList ) { value.append(contentsOf: nextValue()) } } ``` -------------------------------- ### Size Tracking with PreferenceKeyReader Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-modifiers.md An example demonstrating how to track view size using a custom PreferenceKey and PreferenceKeyReader. ```swift struct SizeKey: PreferenceKey { static var defaultValue: CGSize = .zero static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } } var body: some View { PreferenceKeyReader(SizeKey.self) { size in Text("Size: \(size.width)x\(size.height)") } } ``` -------------------------------- ### Custom Styled View Example Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/primitive-views.md An example of a custom view conforming to PrimitiveView, demonstrating its use for custom styling. ```swift struct CustomStyledView: PrimitiveView { var configuration: CustomConfiguration var body: some View { Text("Styled") } } ``` -------------------------------- ### Custom StepperView Example Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-style-system.md An example demonstrating a custom `ViewStyledView` implementation for a `StepperView`. It includes a `StepperViewStyleConfiguration` and a `StepperViewBody` struct. ```swift struct StepperViewStyleConfiguration { struct Label: ViewAlias { } var label: Label { .init() } var onIncrement: () -> Void var onDecrement: () -> Void } struct StepperViewBody: ViewStyledView { var configuration: StepperViewStyleConfiguration static var defaultStyle: DefaultStepperViewStyle { DefaultStepperViewStyle() } } ``` -------------------------------- ### Custom Picker View Example Source: https://github.com/nathantannar4/engine/blob/main/README.md Demonstrates using VariadicViewAdapter to build a custom picker component. This example requires the Fruit enum and PickerView implementation. ```swift enum Fruit: Hashable, CaseIterable { ``` ```swift case apple ``` ```swift case orange ``` ```swift case banana ``` ```swift } ``` ```swift ``` ```swift struct FruitPicker: View { ``` ```swift @State var selection: Fruit = .apple ``` ```swift ``` ```swift var body: some View { ``` ```swift PickerView(selection: $selection) { ``` ```swift ForEach(Fruit.allCases, id: \.self) { ``` ```swift fruit in ``` ```swift Text(fruit.rawValue) ``` ```swift } ``` ```swift } ``` ```swift .buttonStyle(.plain) ``` ```swift } ``` ```swift } ``` ```swift ``` ```swift struct PickerView: View { ``` ```swift @Binding var selection: Selection ``` ```swift @ViewBuilder var content: Content ``` ```swift ``` ```swift var body: some View { ``` ```swift VariadicViewAdapter { ``` ```swift content ``` ```swift } content: { source in ``` ```swift ForEachSubview(source) { index, subview in ``` ```swift HStack { ``` ```swift // This works since the ForEach ID is the Fruit (ie Selection) type ``` ```swift let isSelected: Bool = selection == subview.id(as: Selection.self) ``` ```swift if isSelected { ``` ```swift Image(systemName: "checkmark") ``` ```swift } ``` ```swift ``` ```swift Button { ``` ```swift selection = subview.id(as: Selection.self)! ``` ```swift } label: { ``` ```swift subview ``` ```swift } ``` ```swift } ``` ```swift } ``` ```swift } ``` ```swift } ``` ```swift } ``` -------------------------------- ### Code Example Standards Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/MANIFEST.md Guidelines for code examples, emphasizing full method signatures, type parameters, actual import paths, and realistic usage patterns. ```markdown Code block with realistic usage. ``` -------------------------------- ### Example: Implementing a Custom GridLayout Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/variadic-views.md Provides an example of a custom layout conforming to VariadicViewLayout, arranging subviews into a grid with a specified number of columns. It iterates through children and groups them into rows. ```swift struct GridLayout: VariadicViewLayout { let columns: Int = 2 func body(children: VariadicView) -> some View { VStack { ForEachSubview(children) { index, subview in if index % columns == 0 { HStack { ForEachSubview(children[index.. some View { content.modifier( EnvironmentKeyWritingModifier(\.customColor, value: color) ) } } ``` -------------------------------- ### Example: Processing Sections with VariadicViewAdapter Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/variadic-views.md Demonstrates how to use VariadicViewAdapter to process and display sections, including their headers and content. This is useful for dynamic list or grid layouts. ```swift VariadicViewAdapter { Section { Text("Item 1") } header: { Text("Section 1") } Section { Text("Item 2") } header: { Text("Section 2") } } content: { source in VStack { ForEach(source.sections) { section in VStack { section.header section.content section.footer } } } } ``` -------------------------------- ### Custom Picker Example with VariadicViewAdapter Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/variadic-views.md Demonstrates how to use VariadicViewAdapter to create a custom picker. It iterates through subviews provided by the adapter to build interactive elements. ```swift struct FruitPicker: View { @State var selection: Fruit = .apple var body: some View { VariadicViewAdapter { ForEach(Fruit.allCases, id: \.self) { fruit in Text(fruit.name) } } content: { source in VStack { ForEachSubview(source) { index, subview in Button { selection = subview.id(as: Fruit.self)! } label: { HStack { if selection == subview.id(as: Fruit.self) { Image(systemName: "checkmark") } subview } } } } } } } ``` -------------------------------- ### Example: Selection Handling with VariadicViewAdapter Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/variadic-views.md Illustrates how to use VariadicViewAdapter to iterate through subviews and handle item selections, extracting typed IDs for each item. ```swift VariadicViewAdapter { ForEach([1, 2, 3], id: \.self) { Text("Item \(n)") } } content: { source in VStack { ForEachSubview(source) { index, subview in let itemID: Int? = subview.id(as: Int.self) Button(action: {}) { subview } } } } ``` -------------------------------- ### Example: Using VersionedView with Grid API Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/versioned-views.md Demonstrates implementing the VersionedView protocol to provide a native Grid for iOS 16+ and a custom VStack-based layout for earlier versions. Only implement the versions you need. ```swift struct ContentView: VersionedView { var items: [Item] // iOS 16+ native Grid @available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) var v4Body: some View { Grid { ForEach(items) { item in GridRow { Text(item.name) Text(item.description) } } } } // iOS 15 and earlier custom grid var v1Body: some View { VStack { ForEach(items) { item in HStack { Text(item.name) Text(item.description) } } } } } ``` -------------------------------- ### Custom Styled Button Example Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/primitive-views.md Illustrates the creation of a custom styled button using primitive views, style protocols, and configuration structs. This includes defining the button's configuration, style protocol, a default style, and the styled view itself, followed by usage. ```swift // Configuration struct ButtonConfiguration { struct Label: ViewAlias { } var label: Label { .init() } var action: () -> Void var isEnabled: Bool = true } // Style protocol protocol ButtonStyle: ViewStyle where Configuration == ButtonConfiguration { } // Default style struct DefaultButtonStyle: ButtonStyle { func makeBody(configuration: ButtonConfiguration) -> some View { Button(action: configuration.action) { configuration.label } .disabled(!configuration.isEnabled) } } // Styled view struct CustomButton: PrimitiveView { var configuration: ButtonConfiguration var body: some View { CustomButtonBody(configuration: configuration) } } struct CustomButtonBody: ViewStyledView { var configuration: ButtonConfiguration static var defaultStyle: DefaultButtonStyle { .init() } } // Usage CustomButton( configuration: .init( action: { print("Pressed") }, isEnabled: true ) ) .viewAlias(ButtonConfiguration.Label.self) { Text("Tap Me") } .styledViewStyle( CustomButtonBody.self, style: CustomButtonStyle() ) ``` -------------------------------- ### Example Usage of @StyledView Macro Source: https://github.com/nathantannar4/engine/blob/main/README.md Demonstrates creating a LabeledView with @StyledView and defining custom styles like VerticalLabeledViewStyle and BorderedLabeledViewStyle. Includes an extension for applying label view styles. ```swift import EngineMacros @StyledView struct LabeledView: StyledView { var label: Label var content: Content var body: some View { HStack { label content } } } extension View { func labelViewStyle(_ style: Style) -> some View { modifier(LabelViewStyleModifier(style)) } } struct VerticalLabeledViewStyle: LabeledViewStyle { func makeBody(configuration: LabeledViewStyleConfiguration) -> some View { VStack { configuration.label configuration.content } } } struct BorderedLabeledViewStyle: LabeledViewStyle { func makeBody(configuration: LabeledViewStyleConfiguration) -> some View { LabeledView(configuration) .border(Color.red) } } ``` -------------------------------- ### Implement PercentageTransform Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/environment-and-state.md An example implementation of the BindingTransform protocol for converting between a Double representing a percentage (0-100) and a Double representing a decimal (0-1). ```swift struct PercentageTransform: BindingTransform { static func get(_ input: Double) -> Double { input * 100 // 0.5 -> 50 } static func set(_ output: Double, input: inout Double) { input = output / 100 // 50 -> 0.5 } } ``` ```swift @State var decimal: Double = 0.5 var body: some View { Slider( value: $decimal.transform(PercentageTransform.self) ) // Slider shows 0-100, binding uses 0-1 } ``` -------------------------------- ### Responsive Layout with LayoutThatFits Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/layout-and-shapes.md Implements a responsive layout that attempts to use provided layouts in order until one fits. This example tries an HStackLayout first, then falls back to a VStackLayout. ```swift struct ResponsiveContent: View { var body: some View { LayoutThatFits([ AnyLayout(HStackLayout()), // Try horizontal AnyLayout(VStackLayout()) // Fall back to vertical ]) { Text("Item 1") Text("Item 2") Text("Item 3") } } } ``` -------------------------------- ### Accessing Subviews with VariadicViewAdapter Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/variadic-views.md Example demonstrating how to access individual subviews within a VariadicViewAdapter's content closure using array-like indexing. ```swift VariadicViewAdapter { Text("A") Text("B") Text("C") } content: { source in VStack { HStack { source[0] // "A" source[1] // "B" } source[2] // "C" } } ``` -------------------------------- ### Interactive Versioned View with State and Environment Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/versioned-views.md Demonstrates how to use @State and @Environment property wrappers within a VersionedView. This example shows a counter that increments on tap, with different UI for v1 and v4. ```swift struct InteractiveVersionedView: VersionedView { @State var count = 0 @Environment(\.colorScheme) var scheme @available(iOS 16.0, *) var v4Body: some View { Text("Count: \(count)") .onTapGesture { count += 1 } } var v1Body: some View { Button("Tap (Count: \(count))") { count += 1 } } } ``` -------------------------------- ### Implement VersionedView in ContentView Source: https://github.com/nathantannar4/engine/blob/main/README.md Example of implementing VersionedView to provide a Grid for iOS 16+ and a CustomGridView for older versions. ```swift struct ContentView: VersionedView { @available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) var v4Body: some View { Grid { // ... } } var v1Body: some View { CustomGridView { // ... } } } ``` -------------------------------- ### Example: Custom Submit Button Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/environment-and-state.md Shows how to use the `submitAction` environment value to trigger form submission from a custom button. The button's action calls the `submit()` function obtained from the environment. ```swift struct CustomSubmitForm: View { @Environment(\.submitAction) var submit var body: some View { Form { TextField("Name", text: $name) Button("Submit") { submit() } } } } ``` -------------------------------- ### Default Custom Style Implementation Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-style-system.md Provides an example of a default style implementation for a custom view. This style is used when no explicit style is applied to the view. ```swift struct DefaultCustomStyle: CustomViewStyle { func makeBody(configuration: Configuration) -> some View { configuration.content } } ``` -------------------------------- ### Custom Button Style Implementation Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-style-system.md An example of a custom `ViewStyle` implementation for a button. This style applies padding, a background color, and corner radius to the button's label. ```swift struct RoundedButtonStyle: ViewStyle { var backgroundColor: Color = .accentColor typealias Configuration = RoundedButtonStyleConfiguration func makeBody(configuration: Configuration) -> some View { configuration.label .padding(.horizontal, 16) .padding(.vertical, 8) .background(backgroundColor) .cornerRadius(8) } } ``` -------------------------------- ### Menu Item Collection Example Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-alias-and-output.md Demonstrates collecting MenuItem views using a custom ContextMenuKey. It defines a MenuItem struct and an ItemView that uses the viewOutput modifier to collect menu items. ```swift struct ContextMenuKey: ViewOutputKey { typealias Content = MenuItem static func reduce( value: inout ViewOutputList, nextValue: () -> ViewOutputList ) { value.append(contentsOf: nextValue()) } } struct MenuItem: View { var title: String var action: () -> Void var body: some View { Button(title, action: action) } } struct ItemView: View { var body: some View { Text("Item") .viewOutput(ContextMenuKey.self) { MenuItem(title: "Edit") { print("Edit") } MenuItem(title: "Delete") { print("Delete") } } } } ``` -------------------------------- ### ColorMatrix Example: Grayscale Effect Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/layout-and-shapes.md Demonstrates how to create a ColorMatrix instance to apply a grayscale effect to an image or view. This matrix adjusts RGB values based on luminance. ```swift let grayscaleMatrix = ColorMatrix( m11: 0.299, m12: 0.587, m13: 0.114, m14: 0, m15: 0, m21: 0.299, m22: 0.587, m23: 0.114, m24: 0, m25: 0, m31: 0.299, m32: 0.587, m33: 0.114, m34: 0, m35: 0, m41: 0, m42: 0, m43: 0, m44: 1, m45: 0 ) ``` -------------------------------- ### OffsetEffect Sliding Animation Example Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/layout-and-shapes.md Demonstrates how to use OffsetEffect to create a sliding animation for a Text view. The animation is triggered by a tap gesture. ```swift struct SlidingView: View { @State var isSliding = false var body: some View { Text("Sliding") .modifier(OffsetEffect( offset: isSliding ? CGSize(width: 100, height: 0) : .zero )) .animation(.easeInOut, value: isSliding) .onTapGesture { isSliding.toggle() } } } ``` -------------------------------- ### Define HostingRootView in Swift Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/hosting-views.md Defines a generic SwiftUI View that acts as the root of a hosting view hierarchy. It's useful for starting SwiftUI hierarchies or integrating with UIKit. ```swift public struct HostingRootView: View { public var content: Content @inlinable public init(@ViewBuilder content: () -> Content) public var body: some View { content } } ``` -------------------------------- ### ButtonConfiguration with Label Alias Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-alias-and-output.md Example of defining a ButtonConfiguration struct that uses a ViewAlias for its label. This allows the label to be a placeholder resolved later. ```swift struct ButtonConfiguration { struct Label: ViewAlias { } var label: Label { .init() } var action: () -> Void } ``` -------------------------------- ### Create Styled Attributed String Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/text-and-attributes.md Example of creating a styled attributed string by combining plain text with attributes like font and foreground color. Use this to build complex text layouts. ```swift var attributedString: AttributedString { var result = AttributedString("Hello ") var emphasized = AttributedString("World") emphasized.font = .headline emphasized.foregroundColor = .blue result.append(emphasized) return result } var body: some View { AttributedText(attributedString) } ``` -------------------------------- ### EnvironmentValueReader Example: Colorful Text Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/environment-and-state.md Shows how to use EnvironmentValueReader to apply a foreground color to a Text view based on the environment's foreground color setting. It defaults to black if the environment color is not set. ```swift struct AdaptiveText: View { var text: String var body: some View { EnvironmentValueReader(\.foregroundColor) { color in Text(text) .foregroundColor(color ?? .black) } } } ``` -------------------------------- ### Example: Primary Action Alias Usage Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-alias-and-output.md Demonstrates how to use the viewOutputAlias modifier to bind specific views (like buttons) to defined output aliases within a dialog structure. This is useful for managing distinct actions within a UI component. ```swift struct DialogConfiguration { struct PrimaryAction: ViewOutputAlias { var defaultBody: some View { EmptyView() } } var primaryAction: PrimaryAction { .init() } struct SecondaryAction: ViewOutputAlias { var defaultBody: some View { EmptyView() } } var secondaryAction: SecondaryAction { .init() } } struct ConfirmDialog: View { var message: String var configuration: DialogConfiguration var body: some View { VStack { Text(message) HStack { configuration.secondaryAction configuration.primaryAction } } } } // Usage ConfirmDialog(message: "Delete this item?", configuration: .init()) .viewOutputAlias(DialogConfiguration.PrimaryAction.self) { Button("Delete") { /* delete */ } } .viewOutputAlias(DialogConfiguration.SecondaryAction.self) { Button("Cancel") { /* cancel */ } } ``` -------------------------------- ### Conditional Modifier Example Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/primitive-views.md An example of a custom modifier conforming to PrimitiveViewModifier, showing conditional application of padding. ```swift struct OptionalModifier: PrimitiveViewModifier { var isEnabled: Bool func body(content: Content) -> some View { if isEnabled { content.padding() } else { content } } } ``` -------------------------------- ### Conditional Clipping Example Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/layout-and-shapes.md This example shows how to use ConditionalShape to clip a RoundedRectangle into either a Circle or a Rectangle based on a boolean variable. ```swift var isCircle = false RoundedRectangle(cornerRadius: 8) .clipShape( ConditionalShape( condition: isCircle, then: { Circle() }, otherwise: { Rectangle() } ) ) ``` -------------------------------- ### UnderlineModifier Example Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/versioned-views.md An example of a VersionedViewModifier that applies an underline. It uses the native underline modifier for iOS 16+ and a custom rectangle overlay for older versions. ```swift struct UnderlineModifier: VersionedViewModifier { // Use native underline (iOS 16+) @available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) func v4Body(content: Content) -> some ViewModifier { content.underline() } // Custom underline for older systems func v1Body(content: Content) -> some ViewModifier { content .overlay(alignment: .bottom) { Rectangle() .frame(height: 1) } } } // Usage Text("Underlined") .modifier(UnderlineModifier()) ``` -------------------------------- ### AlignmentGuideOffsetModifier Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-modifiers.md Offsets alignment guides for custom layout. This modifier allows you to adjust the position of elements based on specific horizontal or vertical alignment guides. ```swift public struct AlignmentGuideOffsetModifier: ViewModifier { public init( _ guide: HorizontalAlignment, offset: CGFloat ) public init( _ guide: VerticalAlignment, offset: CGFloat ) public func body(content: Content) -> some View } ``` ```swift struct CustomAlignedView: View { var body: some View { HStack { Text("Left") .modifier(AlignmentGuideOffsetModifier(.leading, offset: 10)) Text("Right") .modifier(AlignmentGuideOffsetModifier(.trailing, offset: -10)) } } } ``` -------------------------------- ### Line Definition Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/types.md Represents a straight line shape defined by its start and end points. ```swift @frozen public struct Line: Shape ``` -------------------------------- ### Line Shape Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/layout-and-shapes.md Defines a straight line shape with customizable start and end points. ```APIDOC ## Line Shape ### Description A shape that draws a straight line. ### Properties - `start` (UnitPoint) - Required - Starting point - `end` (UnitPoint) - Required - Ending point ### Initializer - `init(from: UnitPoint = .topLeading, to: UnitPoint = .bottomTrailing)` - `from` (UnitPoint) - Optional - Line start - `to` (UnitPoint) - Optional - Line end ### Example ```swift ZStack { Color.white Line(from: .topLeading, to: .bottomTrailing) .stroke(Color.red, lineWidth: 2) } .frame(height: 200) ``` ``` -------------------------------- ### Traditional Approach with @available Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/versioned-views.md Demonstrates the traditional SwiftUI approach using @available, which requires wrapping in AnyView and can lead to a loss of type information. ```swift var body: some View { if #available(iOS 16.0, *) { Grid { /* ... */ } } else { VStack { /* ... */ } } // Compiler wraps in AnyView, loses type information } ``` -------------------------------- ### Accessing SwiftUI Environment in Hosted Views Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/hosting-views.md Demonstrates how to access environment values like color scheme, size category, and layout direction within a hosted SwiftUI view. ```swift @Environment(\colorScheme) var colorScheme @Environment(\sizeCategory) var sizeCategory @Environment(\layoutDirection) var layoutDirection var body: some View { Text(colorScheme == .dark ? "Dark" : "Light") } ``` -------------------------------- ### Create and Apply a Custom StepperView Component Source: https://github.com/nathantannar4/engine/blob/main/README.md This snippet demonstrates how to define the StepperView component itself, including its initializer and body, and how to extend `View` to apply custom styles. It also shows how to define the component as a `ViewStyledView` for default styling. ```swift // 5. Add an extension to set the styles extension View { func stepperViewStyle(_ style: Style) -> some View { styledViewStyle(StepperViewBody.self, style: style) } } // 6. Define the component struct StepperView: View { var label: Label var onIncrement: () -> Void var onDecrement: () -> Void init( @ViewBuilder label: () -> Label, onIncrement: @escaping () -> Void, onDecrement: @escaping () -> Void ) { self.label = label() self.onIncrement = onIncrement self.onDecrement = onDecrement } var body: some View { StepperViewBody( configuration: .init( onIncrement: onIncrement, onDecrement: onDecrement ) ) .viewAlias(StepperViewStyleConfiguration.Label.self) { label } } } extension StepperView where Label == StepperViewStyleConfiguration.Label { init(_ configuration: StepperViewStyleConfiguration) { self.label = configuration.label self.onIncrement = configuration.onIncrement self.onDecrement = configuration.onDecrement } } // 7. Define the component as a `ViewStyledView`. struct StepperViewBody: ViewStyledView { var configuration: StepperViewStyleConfiguration // Implementing `body` is optional and only neccesary if you would // like some default styling or modifiers that would be applied // regardless of the style used var body: some View { StepperView(configuration) // This styling will apply to every `StepperView` regardless of the style used .padding(4) .background( RoundedRectangle(cornerRadius: 8) .stroke(Color.secondary) ) } static var defaultStyle: DefaultStepperViewStyle { DefaultStepperViewStyle() } } ``` -------------------------------- ### Async Menu Content Initialization Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-modifiers.md Enables the creation of a Menu with asynchronously loaded content. Uses view builders for both the main content and the label. ```swift extension Menu { /// Create menu with async content public init( @ViewBuilder content: @escaping () -> Content, @ViewBuilder label: () -> Label ) } ``` -------------------------------- ### BindingTransform Protocol Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/environment-and-state.md The BindingTransform protocol defines the interface for transforming binding values. It includes methods for converting values in both directions (get and set). ```APIDOC ## Protocol: BindingTransform ### Description A protocol for transforming binding values. ### Associated Types - `Input`: The original binding value type. - `Output`: The transformed value type. ### Methods #### `get(_ input: Input) -> Output` - **Description**: Converts input to output. - **Parameters**: - `input` (Input) - The value to transform. - **Returns**: `Output` - The transformed value. #### `set(_ output: Output, input: inout Input)` - **Description**: Converts output back to input. - **Parameters**: - `output` (Output) - The transformed value. - `input` (inout Input) - The original binding value to be updated. - **Returns**: `Void` ### Example: Percentage Transformer ```swift struct PercentageTransform: BindingTransform { static func get(_ input: Double) -> Double { input * 100 // 0.5 -> 50 } static func set(_ output: Double, input: inout Double) { input = output / 100 // 50 -> 0.5 } } @State var decimal: Double = 0.5 var body: some View { Slider( value: $decimal.transform(PercentageTransform.self) ) // Slider shows 0-100, binding uses 0-1 } ``` ``` -------------------------------- ### Create a Diagonal Line Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/layout-and-shapes.md Example of creating and styling a diagonal line using the Line shape. The line is stroked with red color and a width of 2. ```swift ZStack { Color.white Line(from: .topLeading, to: .bottomTrailing) .stroke(Color.red, lineWidth: 2) } .frame(height: 200) ``` -------------------------------- ### AnyHostingController Protocol Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/hosting-views.md Protocol for view controllers that host SwiftUI views. It facilitates hosting SwiftUI within view controller hierarchies and enables seamless mixing of UIKit/SwiftUI. ```APIDOC ## AnyHostingController Protocol ### Description Protocol for view controllers that host SwiftUI views. It enables hosting SwiftUI content within view controller hierarchies, supports navigation and lifecycle integration, and allows for mixing UIKit/SwiftUI. ### Type Definition ```swift @MainActor public protocol AnyHostingController: PlatformViewController { associatedtype Content: View var content: Content { get set } } ``` ### Associated Types #### Content - **Type**: `View` - **Description**: The SwiftUI view being hosted. ### Properties #### content - **Type**: `Content` - **Description**: The SwiftUI content to display. This property can be updated dynamically. ### Purpose - Host SwiftUI in view controller hierarchies - Support navigation and lifecycle integration - Enable UIKit/SwiftUI mixing ``` -------------------------------- ### State Management in Hosted SwiftUI Views Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/hosting-views.md Shows how to manage state using @State within a hosted SwiftUI view, including handling user input and conditional UI updates. ```swift struct HostedForm: View { @State var name = "" @State var isValid = false var body: some View { Form { TextField("Name", text: $name) if isValid { Text("Valid!") } } .onChange(of: name) { newValue in isValid = newValue.count > 0 } } } ``` -------------------------------- ### Supported Property Wrappers in PrimitiveView Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/primitive-views.md Demonstrates the various property wrappers available for use within a `PrimitiveView`, including state, environment, observed objects, bindings, focus, and namespaces. ```swift struct AdvancedView: PrimitiveView { @State var count = 0 @Environment(\.colorScheme) var scheme @EnvironmentObject var model: ViewModel @ObservedObject var observable: ObservableObject @Binding var externalState: Bool @FocusState var focusedField: Field? @Namespace var animation var body: some View { // All properties available Text("\(count)") } } ``` -------------------------------- ### Two-Version Support Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/versioned-views.md Provide support for two distinct OS versions. This pattern is useful when introducing a new feature that requires a minimum OS version, while maintaining a fallback for older versions. ```swift struct DualView: VersionedView { @available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) var v4Body: some View { // Modern implementation Grid { } } var v1Body: some View { // Legacy implementation VStack { } } } ``` -------------------------------- ### Implement Custom View Styles Manually with ViewStyle Protocol Source: https://github.com/nathantannar4/engine/blob/main/README.md Provides the protocol definitions for ViewStyle and ViewStyledView, allowing manual implementation for advanced features like a root implementation for styles. This approach is performant and avoids AnyView. ```swift public protocol ViewStyle { associatedtype Configuration associatedtype Body: View @ViewBuilder func makeBody(configuration: Configuration) -> Body } public protocol ViewStyledView: View { associatedtype Configuration var configuration: Configuration { get } associatedtype DefaultStyle: ViewStyle where DefaultStyle.Configuration == Configuration static var defaultStyle: DefaultStyle { get } } ``` -------------------------------- ### HostingRootView Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/hosting-views.md The HostingRootView is a SwiftUI View that acts as the entry point for a hosting view hierarchy. It's designed to be the root of your SwiftUI content, facilitating integration with other frameworks or containers. ```APIDOC ## HostingRootView ### Description A SwiftUI view that serves as the root of a hosting view hierarchy. It's the starting point for SwiftUI hierarchies and integrates with UIKit containers. ### Type Parameters - `Content` (View): The root content view. ### Initializer - `init(@ViewBuilder content: () -> Content)`: Initializes the HostingRootView with a content closure that returns the root view. ### Properties - `content` (Content): The hosted content view. ### Use Cases - Starting point for SwiftUI hierarchies - Integration with UIKit containers - Lifecycle management ``` -------------------------------- ### Custom Attributed String Rendering Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/text-and-attributes.md Example of using AttributedStringReader to process an attributed string and render it with custom views. The closure receives the attributed string for manipulation before display. ```swift struct ProcessedAttributedText: View { var text: AttributedString var body: some View { AttributedStringReader(text) { processed in VStack { Text(processed) Text("Processed") .font(.caption) } } } } ``` -------------------------------- ### Menu Async Support Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-modifiers.md Creates a menu with asynchronous content, allowing for dynamic menu item generation. ```APIDOC ## Menu Extensions ### Menu Async Support ```swift extension Menu { /// Create menu with async content public init( @ViewBuilder content: @escaping () -> Content, @ViewBuilder label: () -> Label ) } ``` ``` -------------------------------- ### Version-Specific Environment Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/versioned-views.md Use this pattern to conditionally render UI elements based on the OS version. The `@available` attribute ensures compatibility, and the `VersionedView` protocol handles the selection logic. ```swift struct AdaptiveView: VersionedView { @Environment(\.horizontalSizeClass) var sizeClass @available(iOS 16.0, *) var v4Body: some View { // Use iOS 16+ features GridLayout() } var v1Body: some View { // Fallback for earlier versions StackLayout() } } ``` -------------------------------- ### Adapt Views for OS Versions (Swift) Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/README.md Create views that adapt to different OS versions using `VersionedView`, providing distinct bodies for specific OS targets without runtime checks. ```swift struct AdaptiveView: VersionedView { @available(iOS 16.0, *) var v4Body: some View { Grid { /* Use iOS 16 Grid */ } } var v1Body: some View { VStack { /* Fallback for iOS 13-15 */ } } } ``` -------------------------------- ### SwiftUI Lifecycle Integration for Primitive Views Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/primitive-views.md Demonstrates how a primitive view integrates with SwiftUI's lifecycle events like onAppear and onDisappear. Use this pattern to manage state changes based on view visibility. ```swift struct LifecycleView: PrimitiveView { @State var initialized = false var body: some View { Text("Content") .onAppear { initialized = true } .onDisappear { initialized = false } } } ``` -------------------------------- ### Conditional Shapes with AnyShape Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/layout-and-shapes.md Demonstrates how to use AnyShape to conditionally apply different shapes based on a style. This allows for runtime selection of shapes. ```swift var dynamicShape: AnyShape { switch style { case .circle: return AnyShape(shape: Circle()) case .rectangle: return AnyShape(shape: Rectangle()) case .rounded: return AnyShape(shape: RoundedRectangle(cornerRadius: 8)) } } var body: some View { Color.blue .clipShape(dynamicShape) } ``` -------------------------------- ### Define BindingTransform Protocol Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/environment-and-state.md The BindingTransform protocol defines the interface for transforming binding values. It requires associated types for Input and Output, and static methods for getting and setting transformed values. ```swift @MainActor @preconcurrency public protocol BindingTransform: Sendable { associatedtype Input associatedtype Output @MainActor @preconcurrency static func get(_ input: Input) -> Output @MainActor @preconcurrency static func set(_ output: Output, input: inout Input) } ``` -------------------------------- ### Accessibility Integration in Hosted SwiftUI Views Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/hosting-views.md Illustrates how to integrate platform accessibility features, such as accessibility labels and hints, into hosted SwiftUI views. ```swift struct AccessibleHosted: View { var body: some View { VStack { Text("Content") .accessibility(label: Text("Main content")) Button(action: {}) { Text("Action") } .accessibility(hint: Text("Performs action")) } } } ``` -------------------------------- ### AnyHostingView Protocol Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/hosting-views.md Protocol for views that host SwiftUI content in UIKit/AppKit. It allows for type-safe access and dynamic updates of the hosted SwiftUI view. ```APIDOC ## AnyHostingView Protocol ### Description Protocol for views that host SwiftUI content in UIKit/AppKit. It bridges SwiftUI to UIView/NSView hierarchies, maintains type-safe content access, and supports dynamic content updates. ### Type Definition ```swift @MainActor public protocol AnyHostingView: PlatformView { associatedtype Content: View var content: Content { get set } } ``` ### Associated Types #### Content - **Type**: `View` - **Description**: The SwiftUI view being hosted. ### Properties #### content - **Type**: `Content` - **Description**: The SwiftUI content to display. This property can be updated dynamically. ### Purpose - Bridge SwiftUI to UIView/NSView hierarchies - Maintain type-safe content access - Support dynamic content updates ``` -------------------------------- ### Generic Versioned Views Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/versioned-views.md Demonstrates how Versioned Views support generic type parameters, allowing for reusable versioned components with customizable content. ```swift struct GenericVersionedView: VersionedView { var content: Content @available(iOS 16.0, *) var v4Body: some View { content .modifier(ModernModifier()) } var v1Body: some View { content .modifier(LegacyModifier()) } } ``` -------------------------------- ### EnvironmentOrValue Example: Font with Fallback Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/environment-and-state.md Demonstrates how to use the EnvironmentOrValue property wrapper to apply a font to a Text view. The font will use the environment's font if set, otherwise it falls back to the default .body font. ```swift struct CustomText: View { @EnvironmentOrValue(.body) var font: Font var body: some View { Text("Content") .font(font) // Uses environment if set, else .body } } // Usage CustomText() .environment(\.font, .headline) // Overrides default ``` -------------------------------- ### Complete Version Stack Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/versioned-views.md Implement a complete version stack to support a wide range of OS versions, from the latest to a minimum baseline. Each `vXBody` property targets a specific OS version or range. ```swift struct CompleteView: VersionedView { @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *) var v5Body: some View { // Latest features Text("v5") } @available(iOS 16.0, *) var v4Body: some View { // iOS 16 features Text("v4") } @available(iOS 15.0, *) var v3Body: some View { // iOS 15 features Text("v3") } @available(iOS 14.0, *) var v2Body: some View { // iOS 14 features Text("v2") } var v1Body: some View { // iOS 13 minimum Text("v1") } } ``` -------------------------------- ### Define and Implement StepperView Styles Source: https://github.com/nathantannar4/engine/blob/main/README.md This snippet defines the necessary protocols, configurations, and concrete styles for a customizable StepperView. It includes defining the style protocol, its configuration, a default style, and a custom inline style. ```swift // 1. Define the style protocol StepperViewStyle: ViewStyle where Configuration == StepperViewStyleConfiguration { } // 2. Define the style's configuration struct StepperViewStyleConfiguration { struct Label: ViewAlias { } // This lets the `StepperView` type erase the `Label` when used with a `StepperViewStyle` var label: Label { .init() } var onIncrement: () -> Void var onDecrement: () -> Void } // 3. Define the default style struct DefaultStepperViewStyle: StepperViewStyle { func makeBody(configuration: StepperViewStyleConfiguration) -> some View { Stepper { configuration.label } onIncrement: { configuration.onIncrement() } onDecrement: { configuration.onDecrement() } } } // 4. Define your custom styles struct InlineStepperViewStyle: StepperViewStyle { func makeBody(configuration: StepperViewStyleConfiguration) -> some View { HStack { Button { configuration.onDecrement() } label: { Image(systemName: "minus.circle.fill") } configuration.label Button { configuration.onIncrement() } label: { Image(systemName: "plus.circle.fill") } } .accessibilityElement(children: .combine) .accessibilityAdjustableAction { switch direction { case .increment: configuration.onIncrement() case .decrement: configuration.onDecrement() default: break } } } } ``` ```swift // 8. Define a default style based on the `StyleContext` (Optional) struct AutomaticStepperViewStyle: StepperViewStyle { func makeBody(configuration: StepperViewStyleConfiguration) -> some View { StepperView(configuration) .styledViewStyle( StepperViewBody.self, style: InlineStepperViewStyle(), predicate: .scrollView // Use the inline style when in a ScrollView ) .styledViewStyle( StepperViewBody.self, style: DefaultStepperViewStyle() // If no predicate matches, use the default ) } } ``` -------------------------------- ### Styled DatePicker Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-modifiers.md Initializes a DatePicker with custom styling and a label. ```APIDOC ## DatePicker Extensions ### DatePicker Style Support ```swift extension DatePicker { /// Create styled date picker public init( selection: Binding, @ViewBuilder label: () -> Label ) } ``` ``` -------------------------------- ### Spring Animation Shortcut Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-modifiers.md Provides a static method to create a spring animation with customizable parameters. ```swift extension Animation { /// Create spring animation public static func spring( response: Double = 0.55, dampingFraction: Double = 0.825, blendDuration: Double = 0.001 ) -> Animation } ``` -------------------------------- ### SwiftUI Output Collection with Reduction Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-alias-and-output.md Demonstrates collecting `ToolbarItem` outputs from child views using a custom `ToolbarItemKey` that reduces (appends) all emitted items. This pattern is useful for aggregating specific view components from a hierarchy. ```swift struct ToolbarItemKey: ViewOutputKey { typealias Content = ToolbarItem static func reduce( value: inout ViewOutputList, nextValue: () -> ViewOutputList ) { value.append(contentsOf: nextValue()) } } // Child views emit outputs @ViewBuilder var body: some View { Text("Content") .viewOutput(ToolbarItemKey.self) { ToolbarItem(placement: .navigationBarTrailing) { Button("Edit") { } } } } // Parent collects outputs @ViewInputs var inputs let toolbarItems = inputs[ToolbarItemKey.self] ``` -------------------------------- ### Styled DatePicker Initialization Source: https://github.com/nathantannar4/engine/blob/main/_autodocs/api-reference/view-modifiers.md Provides an initializer for DatePicker that allows for custom styling. Requires a binding to a Date and a view builder for the label. ```swift extension DatePicker { /// Create styled date picker public init( selection: Binding, @ViewBuilder label: () -> Label ) } ```