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

SwiftUI中confirmationDialog报错修复及用法咨询

SwiftUI confirmationDialog 错误修复

你的代码报错是因为confirmationDialog的闭包内不能直接放置Alert组件——confirmationDialog的内容区域需要的是操作按钮(Button),而非独立的Alert弹窗,这俩是SwiftUI里不同的交互组件,不能混用。

正确用法说明

confirmationDialog用来展示一组操作选项,你需要在它的闭包里添加不同类型的按钮(比如确认、取消、破坏性操作按钮),通过按钮的action来处理对应的逻辑。

修复后的完整代码

import SwiftUI

struct ContentView: View {
    
    @State var isError = false
    
    var body: some View {
        Button {
            isError = true
        } label: {
            Text("CHMO")
                .background(Color.orange)
                .cornerRadius(10)
        }
        .confirmationDialog("are you sure", isPresented: $isError) {
            // 替换原来的Alert,添加操作按钮
            Button("Yes", role: .destructive) {
                // 这里写"Yes"按钮的点击逻辑
                print("执行确认操作")
            }
            Button("No", role: .cancel) {
                // 这里写"No"按钮的点击逻辑
                print("取消操作")
            }
        } message: {
            // 可选:添加对话框的说明文本
            Text("No More")
        }
        
        VStack {
            Image(systemName: "globe")
                .imageScale(.medium)
                .foregroundStyle(.brown)
            Text("Hello, world!")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

关键修改点

  • 移除了闭包里的Alert,换成了两个Button,分别对应原Alert里的"Yes"和"No"选项
  • 给按钮添加了role参数(.destructive对应危险操作,.cancel对应取消),让系统自动处理按钮的排序和样式
  • 可选添加了message参数,用来展示对话框的说明文本,对应原Alert里的message内容

内容的提问来源于stack exchange,提问作者Даниил Волошин

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 08:07:35