Skip to content
Projekte

fatbobman/SwiftUIOverlayContainer

Auf GitHub ansehen

Über uns

SwiftUI Overlay Container ist eine View-Container-Komponente für SwiftUI. Sie ist anpassbar und ermöglicht eine effiziente und einfache Verwaltung von Views.

Web- und App-Entwicklung

So werden diese Zahlen gemessen

Gemessener Sternzuwachs

in 24h
0
in 7 days
0
in 15 days
+1
in 1 month
Verlauf wird gesammelt

Nettoänderungen in überlappenden Zeiträumen, keine Tagessummen. Fehlende Messwerte bleiben leer. Sterne zeigen Interesse, nicht Qualität.

README.md

Original

SwiftUI Overlay Container 3.0

Swift 6.2+ Platforms SPM Zero Dependencies License

简体中文

A deterministic overlay orchestration and lifecycle runtime for SwiftUI — not a pre-styled toast or popup widget library.

You bring any SwiftUI view. SwiftUIOverlayContainer owns everything that breaks when naive .overlay modifiers hit production: concurrent queues, capacity limits, refill pacing, debouncing, atomic in-place replacement, slot-level backdrop compositing, dismissal gestures, animation-verified lifecycle receipts, multi-window isolation, and scene reconnect recovery.

Built for Swift 6 (@MainActor + @Observable), iOS / iPadOS 17+, and macOS 14+, with zero external dependencies.


Why not just .overlay or .sheet?

Showing one toast in SwiftUI takes five lines of .overlay. Maintaining overlays across a real app fails on everything that comes next:

  • Concurrent requests and atomic replacement: Network errors, copy confirmations, and upload indicators arrive from different parts of your app at once. You need queueing (.oneByOne, .oneByOneWaitFinish, .multiple), capacity caps, refill delays, debouncing, and atomic in-place replacement (Uploading… → Uploaded) without a dismiss-then-reappear flicker.
  • Exact animation receipts instead of Task.sleep: SwiftUI's .onDisappear can trail visual removal by nearly a second, and guessing animation durations causes overlapping slots or premature dismissal. Each presentation returns an OverlayHandle that distinguishes mounted, presented (entry transition finished), and removed(reason) (exit transition actually finished), and exposes waitUntilPresented() and waitUntilFinished(). Built-in auto-dismiss counts only active window time.
  • Declarative SwiftUI and imperative architecture on the same queue: Views can bind overlays with isPresented: or item: (honoring withTransaction(\.disablesAnimations, true)), while reducers, services, or external schedulers drive the exact same container via OverlayController and OverlayHandle — with deterministic bidirectional binding write-back.
  • True multi-window isolation and floating overlay panels: Wrap a WindowGroup in .overlayContainerScope() so every window reuses the same logical address (.toast) with isolated queues, or inject one shared OverlayController into both your main window and an independent floating HUD panel (including non-activating macOS NSPanel windows). Queues and handles survive temporary host detachment and reconnect.
  • Layout, backdrop, and gesture mechanics without visual lock-in: Switch between .stacking, .vertical, and .horizontal (with dynamic card resizing, RTL mirroring, per-card composited shadows, per-slot backdrop handoff, and child-priority dismissal gestures) while keeping full control over your card views.

When to use (and when not to)

Skip this library if you only need a standard modal sheet, system alert, popover, or a single local banner on one screen — native SwiftUI .sheet, .popover, .alert, or .overlay is simpler and lighter.

Use SwiftUIOverlayContainer when you are building:

  • A global toast, notice, or banner lane fed by multiple views or services
  • Stacked or queued non-modal cards with capacity limits, refill spacing, or debouncing
  • Progress-to-result transitions that must swap atomically in place (try handle.replace { … })
  • An external scheduler or reducer (such as a priority queue or VoiceOver-aware notification controller) that needs exact presented and removed receipts
  • Multi-window iPadOS / macOS apps or independent floating HUD / overlay windows that require strict window isolation and active-time timers

Mental model in 30 seconds

  1. Controller & Scope (OverlayController, .overlayContainerScope) — Defines the ownership and isolation boundary (one per window via .overlayContainerScope(), explicit injection for cross-window HUDs, or OverlayController.shared for simple single-window apps).
  2. Container (.overlayContainer / OverlayContainer) — A named presentation lane (OverlayContainerID) hosted on a view or standalone canvas. It owns the layout, queue policy, alignment, display order, debounce, safe areas, and default presentation style.
  3. Presentation & Handle (.overlayPresentation / try controller.show / OverlayHandle) — Each admitted request gets a stable OverlayHandle representing that single presentation instance, with synchronous state, atomic replace, dismiss, event callbacks, and async waitUntilPresented() / waitUntilFinished().

Quick taste

1. Declare a window-scoped container and drive it declaratively

import SwiftUI
import SwiftUIOverlayContainer

extension OverlayContainerID {
    static let toast: Self = "toast"
}

extension OverlayContainerConfiguration {
    static let toastLane = Self(
        layout: .stacking,
        queue: .oneByOne,
        alignment: .bottom,
        presentationDefaults: .init(
            transition: .opacity,
            autoDismiss: .after(.seconds(3))
        )
    )
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            EditorView()
                .overlayContainer(.toast, configuration: .toastLane)
                .overlayContainerScope()
        }
    }
}

struct EditorView: View {
    @State private var notice: Notice?

    var body: some View {
        DocumentCanvas(notice: $notice)
            .overlayPresentation(item: $notice, in: .toast) { notice in
                NoticeCard(notice)
            }
    }
}

2. Orchestrate the same lane imperatively from a reducer or service

@MainActor
func uploadDocument(using overlays: OverlayController) async throws {
    try Task.checkCancellation()
    let progress = try overlays.show(
        in: .toast,
        presentation: .init(autoDismiss: .disabled)
    ) {
        UploadProgressCard()
    }
    defer { progress.dismiss() }

    try await performUpload()
    try Task.checkCancellation()

    // Swap progress -> result atomically in the same slot without a dismiss/reappear gap.
    let done = try progress.replace(transition: .identity) {
        UploadSucceededCard()
    }

    _ = try await done.waitUntilFinished()
}

The deferred dismissal cleans up the progress card if the upload fails, the task is cancelled, or replace throws. After a successful replacement, the result card has its own handle and follows the container's auto-dismiss configuration.

Need to skip animation for a single declarative update? Wrap the binding write in withTransaction(\.disablesAnimations, true) { … }. Read overlays.snapshot(in: .toast) on @MainActor for the current presentation and waiting queues, occupied slot count, and host status (isMounted, isActive). Observation tracks changes per container.


Requirements and installation

3.0 is a breaking upgrade. If you are upgrading from 2.x, start with the migration guide.

  • Platforms: iOS / iPadOS 17.0+, macOS 14.0+
  • Toolchain: Swift 6.2+ (Swift 6 language mode)
  • Dependencies: None

In Xcode, add https://github.com/fatbobman/SwiftUIOverlayContainer.git as a Swift package. Choose Up to Next Major Version from 3.0.0 and add the SwiftUIOverlayContainer product to your target. To try the candidate before the tag is available, add a local checkout of the 3.0 branch.

Projects targeting earlier OS versions, tvOS, or watchOS can stay on 2.4.3.


Documentation & Demo

Once you decide the architecture fits your app, dive into the exact specifications and runnable examples:

  • API Reference & Examples: Docs/v3-api.md (Chinese) — public signatures, configuration inheritance, lifecycle receipts, and window cleanup.
  • Migrating from 2.4.3: Docs/v3-migration.md (Chinese) — moving from ContainerManager & protocol configs to OverlayController, value configs, unified Logger, and updated linear ordering.
  • Multi-platform Demo (iPhone, iPad, Mac): Demo/README.md — install Tuist, run tuist generate --path Demo, and run the OverlayDemo scheme.
  • Legacy 2.4.3: Version 2.4.3 tree

Stay Connected & Support

  • Fatbobman's Swift Weekly: Subscribe to curated weekly articles, tools, and reflections on Swift, SwiftUI, and Apple platforms at weekly.fatbobman.com, or read in-depth posts at fatbobman.com.
  • Feedback: Open a GitHub Issue for bug reports and feature discussions, or reach out on X / Twitter @fatbobman.
  • Sponsor: If this library saves you time in production, consider buying me a coffee:

Buy Me A Coffee

License

Released under the MIT License.

Ähnliche Projekte entdecken

Wird geladen…