You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中Sheet内ConfirmationDialog点击取消后异常闪现求助

解决Sheet中ConfirmationDialog取消时闪回的问题

问题原因

你遇到的弹窗闪回问题,核心是手动重复设置弹窗状态引发的SwiftUI状态冲突:带.cancel角色的按钮会自动将confirmationDialog绑定的isPresented状态设为false,但你又在Cancel按钮的action里手动执行了showDeletionConfirmation = false,两次状态变更叠加Sheet的视图渲染逻辑,就出现了弹窗先关闭再闪回一秒的现象。而Alert对这种重复赋值的兼容性更好,所以替换后功能正常。

解决方案

直接移除Cancel按钮action里的手动状态赋值,让系统自动处理弹窗关闭:

@State private var item: ItemDTO?
@State private var showDeletionConfirmation = false

...

ItemListView(
    items: viewModel.items,
    editAction: { editItem in
        item = editItem
    }
)
.sheet(item: $item) { editItem in
    ItemView(
        item: editItem,
        deleteAction: { showDeletionConfirmation = true }
    )
    .confirmationDialog(
        "Sure?",
        isPresented: $showDeletionConfirmation,
        actions: {
            Button("Yes", role: .destructive) {
                print("Deleting...")
                item = nil
            }
            // 移除手动设置状态的代码,系统会自动关闭弹窗
            Button("Cancel", role: .cancel) {}
        },
        message: {
            Text("Do you want to continue?")
        }
    )

如果需要在取消时执行额外逻辑,可保留action但不要重复设置弹窗状态:

Button("Cancel", role: .cancel) {
    // 这里添加你的取消逻辑,比如清理临时数据等
    // 无需添加 showDeletionConfirmation = false
}

内容的提问来源于stack exchange,提问作者Sebastian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 22:17:16