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

SwiftUI中重试操作无法再次触发Alert弹窗问题求助

问题原因

你遇到的问题是:第一次弹出Alert后,shouldPresentAlert的状态已经是true,第二次调用performPotentiallyThrowingFunction时直接将它设为true,SwiftUI检测不到状态变化,因此不会重新触发Alert。

解决方案

有两种简单的修复方式:

方法一:强制触发状态变化

在设置shouldPresentAlert = true前,先将其设为false,并用异步队列确保状态更新被SwiftUI捕获:

import SwiftUI

struct SplashScreen: View {
    @State private var shouldPresentAlert = false

    var body: some View {
        ProgressView()
            .onAppear {
                performPotentiallyThrowingFunction()
            }
            .alert("Thrown", isPresented: $shouldPresentAlert) {
                Button("Retry", role: .cancel) {
                    performPotentiallyThrowingFunction()
                }
            } message: {
                Text("Something went wrong")
            }
    }

    private func performPotentiallyThrowingFunction() {
        do {
            throw URLError(.badURL)
        } catch {
            // 先重置状态,再异步触发Alert
            shouldPresentAlert = false
            DispatchQueue.main.async {
                shouldPresentAlert = true
            }
        }
    }
}

方法二:使用alert(item:)(更符合SwiftUI规范)

用一个可选的可识别错误对象控制Alert显示,每次抛出错误时生成新对象,自然触发状态变化:

import SwiftUI

// 定义符合Identifiable的错误类型
struct AppError: Identifiable {
    let id = UUID()
    let message: String
}

struct SplashScreen: View {
    @State private var currentError: AppError?

    var body: some View {
        ProgressView()
            .onAppear {
                performPotentiallyThrowingFunction()
            }
            .alert(item: $currentError) { _ in
                Button("Retry", role: .cancel) {
                    performPotentiallyThrowingFunction()
                }
            } message: { error in
                Text(error.message)
            }
    }

    private func performPotentiallyThrowingFunction() {
        do {
            throw URLError(.badURL)
        } catch {
            currentError = AppError(message: "Something went wrong")
        }
    }
}

方法二更适合后续扩展(比如展示不同错误信息),状态管理也更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 19:43:13