AGENT SKILL

swiftui-sheet-in-sheet-uikit-present-bridge

UIActivityViewController (or any other UIKit present-based flow like UIDocumentPickerViewController) presented via .sheet(item:) from a SwiftUI view that is itself already presented as a sheet flashes on screen and self-dismisses within a single frame with zero user interaction — confirmed by a user who "didn't tap anything." The same bug class hits UIImagePickerController (camera picker), QLPreviewController (QuickLook preview) and MFMailComposeViewController (mail composer): the flow flashes and dismisses its PARENT sheet, or never appears. Use when triggering a system share sheet, document picker, or any UIKit present(_:animated:) flow from a screen that can itself be presented as a sheet (a very common architecture: Settings-as-sheet, detail-as-sheet).

License 许可
MIT
最近更新
2026-11-07
Stars
★ 1
Forks
1

01 前言 Front Matter

name
swiftui-sheet-in-sheet-uikit-present-bridge
description
UIActivityViewController (or any other UIKit present-based flow like UIDocumentPickerViewController) presented via .sheet(item:) from a SwiftUI view that is itself already presented as a sheet flashes on screen and self-dismisses within a single frame with zero user interaction — confirmed by a user who "didn't tap anything." The same bug class hits UIImagePickerController (camera picker), QLPreviewController (QuickLook preview) and MFMailComposeViewController (mail composer): the flow flashes and dismisses its PARENT sheet, or never appears. Use when triggering a system share sheet, document picker, or any UIKit present(_:animated:) flow from a screen that can itself be presented as a sheet (a very common architecture: Settings-as-sheet, detail-as-sheet).

03 SKILL.md 正文

SwiftUI Sheet-in-Sheet: UIKit Present Flashes and Self-Dismisses

Symptom

Export (CSV/JSON), label printing, and share flows all trigger UIActivityViewController via a SwiftUI .sheet(item:) binding from a view that is itself already presented as a sheet (Settings, a tag-editor sheet, a link-existing-item sheet). The share sheet flashes and tears itself down within a single frame, with zero user interaction — confirmed by the user ("I didn't tap anything"). The bug only reveals itself by tracing the actual runtime presentation hierarchy (which root view presents which screen as a sheet), not from reading the call site in isolation.

Root cause

SwiftUI's .sheet(item:) driving a UIKit-hosted UIActivityViewController from a second, nested sheet layer is fundamentally unreliable — SwiftUI's own sheet-presentation state machine fights the second nested presentation. The moment the presenting view is already inside one .sheet, adding another .sheet(item:) on top of it for a UIKit-bridged controller (rather than a pure-SwiftUI view) races against SwiftUI's internal bookkeeping for the first sheet, and the second presentation tears itself down before the user can interact with it.

Fix

Replace the .sheet(item:)-driven share flow with an imperative present: walk UIApplication.shared.connectedScenes → key window → follow .presentedViewController to the actual top-most UIKit view controller, and call present(_:animated:) on it directly, with iPad popover-source anchoring handled explicitly. This sidesteps SwiftUI's declarative sheet stack entirely for the share sheet / document picker and every other UIKit-presented system flow (see Generalization) that needs guaranteed top-of-hierarchy presentation regardless of how many SwiftUI sheets are already stacked:

enum ActivitySharePresenter {
    static func present(items: [Any], sourceView: UIView? = nil) {
        guard let windowScene = UIApplication.shared.connectedScenes
                .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene,
              let keyWindow = windowScene.windows.first(where: { $0.isKeyWindow }),
              var topController = keyWindow.rootViewController
        else { return }

        // Walk to the actual top-most presented controller, however deep.
        while let presented = topController.presentedViewController {
            topController = presented
        }

        let activityVC = UIActivityViewController(activityItems: items, applicationActivities: nil)
        if let popover = activityVC.popoverPresentationController {
            popover.sourceView = sourceView ?? topController.view
            popover.sourceRect = sourceView?.bounds ?? CGRect(x: topController.view.bounds.midX,
                                                                y: topController.view.bounds.midY,
                                                                width: 0, height: 0)
        }
        topController.present(activityVC, animated: true)
    }
}

// Call site — no .sheet(item:) binding needed:
Button("Export") {
    ActivitySharePresenter.present(items: [csvURL])
}

Evidence

Session 0017: "The nested sheet flashed and tore itself down within a frame — zero user interaction... Fixed by replacing ShareableFile/ ActivityShareSheet (.sheet(item:)-driven) with ActivitySharePresenter.present(items:) — an imperative present on the actual top-most UIKit view controller, walking UIApplication.shared.connectedScenes → key window → .presentedViewController chain, with iPad popover anchoring. 4 call sites migrated." Root cause confirmed by tracing the actual runtime presentation hierarchy (RootTabView.swift:42 presents Settings as a sheet), not from the call site in isolation.

Generalization

This is a CLASS of bug, not a share-sheet quirk. Four recurrences in one app (each initially treated as a new bug): share sheet, QuickLook, camera, mail composer. The camera case showed as a flash followed by the parent sheet being dismissed; an earlier incomplete fix had only removed an imperative dismiss call and left the underlying declarative race.

Rule: ANY UIKit present(_:animated:)-based system flow launched from a SwiftUI view that is — or can ever be — inside a .sheet/.fullScreenCover must go through an imperative top-most-view-controller presenter (walk connectedScenes → key window → .presentedViewController chain, as in ActivitySharePresenter above). Never drive it with a nested .sheet(item:), .fullScreenCover, or a UIViewControllerRepresentable mounted inside the second sheet layer — SwiftUI's sheet state machine races the nested presentation and tears down one side.

Review heuristic: when a diff adds a UIViewControllerRepresentable or a .sheet-presented UIKit controller, ask "can the presenting view itself be a sheet anywhere in the app?" — if yes, flag it; the bug only reproduces from the nested context, so the call site looks innocent in isolation and unit tests can't see it.

Related skills

  • navigationsplitview-single-stack-per-detail-column and realityview-fullscreencover-black-defer-mount are unrelated root causes but share the same debugging shape: a SwiftUI presentation/render bug that only reveals itself by tracing the actual runtime hierarchy, not by reading the call site in isolation.

04 同仓库更多 Skills

abhijitbansal
abhijitbansal/claude-skills

second-wind

Orchestrate long unattended Claude Code runs across multiple repos with the wind CLI. Use when the user wants to run Claude Code overnight, resume sessions after the 5-hour usage limit, run Claude in many repos at once via tmux, or says "set up second wind", "wind up", "overnight run", "resume after limit", "usage limit orchestrator".

★ 1
abhijitbansal
abhijitbansal/claude-skills

structured-output-adaptive-thinking-token-bloat

A Claude API call using output_config.format (json_schema structured outputs) with thinking:{type:"adaptive"} burns most of its output budget on thinking (observed ~21k of ~24k tokens) without improving JSON quality, making the run up to ~5x more expensive than the same call with thinking omitted — use when calling the Messages API with a json_schema output format for extraction, ranking, classification, or summarization tasks, or when a schema-constrained call's usage.output_tokens is far larger than the returned JSON.

★ 1
abhijitbansal
abhijitbansal/claude-skills

review

Apply a code-review lens to a diff, branch, or file — find correctness bugs, security issues, and quality problems, ranked by severity, with a concrete fix for each. Use when the user says "review this", "review my diff", "check this PR", "look this over before I commit", or "is this safe". Skip when the user wants the code written, not reviewed.

★ 1
abhijitbansal
abhijitbansal/claude-skills

refresh

Rebuild the prompt-craft command registry and usage profile, and print a summary of installed commands and your personalized recommendations. Use when you install or update plugins and want the advisor to pick them up immediately, or say "refresh prompt-craft", "rebuild the command registry".

★ 1
abhijitbansal
abhijitbansal/claude-skills

refactor

Apply a refactoring lens — restructure code without changing behavior, guarded by tests that pass before and after. Use when the user says "refactor", "clean this up", "extract this", "simplify this", "reduce duplication", or "make this readable" on existing working code. Skip when the change is meant to alter behavior (that's a feature or a fix).

★ 1
abhijitbansal
abhijitbansal/claude-skills

plan

Decompose a non-trivial task into an explicit, tracked plan with goals and per-step acceptance criteria before writing code. Use when the user says "plan this", "break this down", "what's the plan", or asks for a multi-step feature/refactor that touches more than one file. Pairs with plan mode. Skip for single-edit changes that need no decomposition.

★ 1