NavigationStackView、Sheet等产生的次级界面,可使用 @Environment(\.dismiss) var dismiss 自行控制消失。

struct DetailView: View {
    @Environment(\.dismiss) var dismiss

    var body: some View {
        Button("关闭 DetailView") {
            dismiss()
        }
    }
}

struct ContentView: View {
    @State private var showingDetail = false

    var body: some View {
        Button("显示 DetailView") {
            showingDetail = true
        }
        .sheet(isPresented: $showingDetail) {
            DetailView()
        }
    }
}

传递binding参数

除了使用dismiss环境变量,另一种同样常用的方式是,向次级界面传递binding参数。

struct DetailView: View {
    @Binding var isPresented: Bool

    var body: some View {
        Button("关闭 DetailView") {
            isPresented = false
        }
    }
}

struct ContentView: View {
    @State private var showingDetail = false

    var body: some View {
        Button("显示 DetailView") {
            showingDetail = true
        }
        .sheet(isPresented: $showingDetail) {
            DetailView(isPresented: $showingDetail)
        }
    }
}