fatbobman/SwiftUIOverlayContainer
소개
SwiftUI Overlay Container는 SwiftUI용 뷰 컨테이너 구성 요소입니다. 사용자 지정이 가능하며, 효율적이고 편리한 뷰 관리자입니다.
웹 및 앱 개발측정된 스타 증가
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- +1
- in 1 month
- 기록 수집 중
서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.
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.
관련 프로젝트 살펴보기
불러오는 중…