fatbobman/SwiftUIOverlayContainer
Acerca de
SwiftUI Overlay Container es un componente contenedor de vistas para SwiftUI. Es un gestor de vistas personalizable, eficiente y práctico.
Desarrollo web y de aplicacionesCrecimiento de estrellas medido
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- +1
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
OriginalSwiftUI Overlay Container 3.0
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.onDisappearcan trail visual removal by nearly a second, and guessing animation durations causes overlapping slots or premature dismissal. Each presentation returns anOverlayHandlethat distinguishesmounted,presented(entry transition finished), andremoved(reason)(exit transition actually finished), and exposeswaitUntilPresented()andwaitUntilFinished(). Built-in auto-dismiss counts only active window time. - Declarative SwiftUI and imperative architecture on the same queue: Views can bind overlays with
isPresented:oritem:(honoringwithTransaction(\.disablesAnimations, true)), while reducers, services, or external schedulers drive the exact same container viaOverlayControllerandOverlayHandle— with deterministic bidirectional binding write-back. - True multi-window isolation and floating overlay panels: Wrap a
WindowGroupin.overlayContainerScope()so every window reuses the same logical address (.toast) with isolated queues, or inject one sharedOverlayControllerinto both your main window and an independent floating HUD panel (including non-activating macOSNSPanelwindows). 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
presentedandremovedreceipts - 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
- Controller & Scope (
OverlayController,.overlayContainerScope) — Defines the ownership and isolation boundary (one per window via.overlayContainerScope(), explicit injection for cross-window HUDs, orOverlayController.sharedfor simple single-window apps). - 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. - Presentation & Handle (
.overlayPresentation/try controller.show/OverlayHandle) — Each admitted request gets a stableOverlayHandlerepresenting that single presentation instance, with synchronousstate, atomicreplace,dismiss, event callbacks, and asyncwaitUntilPresented()/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) { … }. Readoverlays.snapshot(in: .toast)on@MainActorfor 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 toOverlayController, value configs, unifiedLogger, and updated linear ordering. - Multi-platform Demo (iPhone, iPad, Mac): Demo/README.md — install Tuist, run
tuist generate --path Demo, and run theOverlayDemoscheme. - 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:
License
Released under the MIT License.
Explorar proyectos relacionados
Cargando…