SwiftUI:工作表关闭后如何显示警报?

时间:2020-09-19 11:41:02

标签: swiftui

我正在尝试显示由模式表触发的警报。这是一个小型演示项目:

import SwiftUI

struct ContentView: View {
    @State private var showSheet = false
    @State private var showAlert = false

    var body: some View {
        Button("Press") {
            showSheet = true
        }
        .sheet(isPresented: $showSheet) {
            Button("Close with alert") {
                showSheet = false
                showAlert = true
            }
        }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("Alert"))
        }
    }
}

单击“按下”按钮后,将出现一个带有“关闭并警告”按钮的模式表。如果按下此按钮,则工作表将关闭,并且什么也不会发生。我希望显示警报。

似乎隐藏表格的动画引起了问题,因为在设置showSheet = false之后,SwiftUI似乎没有将表格视为已关闭。出现以下警告,支持此理论:

[演示文稿]尝试呈现亮 << em> TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier _: 0x7fbbaa60b7d0>(来自 << em> TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier _: 0x7fbbaa60b7d0>)已在显示 << em> TtGC7SwiftUI22SheetHostingControllerVS_7AnyView :0x7fbbaa413200>。

2 个答案:

答案 0 :(得分:3)

您可以使用onDismiss

以下是一些基于何时要显示警报的示例:

  1. 始终关闭并显示警报:
struct ContentView: View {
    @State private var showSheet = false
    @State private var showAlert = false

    var body: some View {
        Button("Press") {
            showSheet = true
        }
        .sheet(isPresented: $showSheet, onDismiss: {
            showAlert = true
        }) {
            Button("Close") {
                showSheet = false
            }
        }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("Alert"))
        }
    }
}
  1. 关闭并在仅单击按钮时发出警报:
struct ContentView: View {
    @State private var showSheet = false
    @State private var showAlert = false
    @State private var closeSheetWithAlert = false

    var body: some View {
        Button("Press") {
            showSheet = true
            closeSheetWithAlert = false
        }
        .sheet(isPresented: $showSheet, onDismiss: {
            showAlert = closeSheetWithAlert
        }) {
            Button("Close") {
                closeSheetWithAlert = true
                showSheet = false
            }
        }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("Alert"))
        }
    }
}

答案 1 :(得分:0)

您需要花些时间关闭工作表,所以要像这样

    .sheet(isPresented: $showSheet) {
        Button("Close with alert") {
            showSheet = false
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
               showAlert = true
            } 
        }
    }

注意:同样值得考虑在onDismiss工作表回调中执行此操作,但这需要您的状态模型重新考虑。