重试操作不会再次触发警报

问题描述 投票:0回答:1

我一直在尝试创建一个可以在显示警报后重试的函数,但由于某种原因,该函数第二次运行时,警报没有显示。我希望在重试操作中重新运行投掷函数。

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 {
            shouldPresentAlert = true
        }
    }
}
swift swiftui alert
1个回答
0
投票

警报尚未关闭,因此再次将其设置为

true
没有任何效果。

要使其按预期工作,您可以通过将

Alert
设置为
shouldPresentAlert
来关闭
false
,然后在下一个运行循环或稍后,将其设置为
true

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

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

    private func performPotentiallyThrowingFunction() {
        do {
            throw URLError(.badURL)
        } catch {
            shouldPresentAlert = true
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.