如何在工作表关闭时触发 onApper 方法?

Tio*_*Tio 0 swiftui

我目前正在使用 SwiftUI 开发一个应用程序。

我想在从同一结构创建的对象关闭时使用一种onAppear方法。sheet

有什么办法可以做到这一点吗?


以下是代码:

BaseView.swift

import SwiftUI

struct BaseView: View {
    
    @State var isSheet:Bool = false
    
    var body: some View {
        VStack{
            VStack{
                Text("BaseView")

                Button(action:{
                    isSheet = true
                }){
                    Text("SHEET")
                }
            }
            .onAppear(){
                print("onAppear fiered")
            }
            .sheet(isPresented: $isSheet){
                Sheet()
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sheet.swift

import SwiftUI

struct Sheet: View {
    
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {

        Button(action: {
            self.presentationMode.wrappedValue.dismiss()
        }) {
            Text("CLOSE")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Xcode:版本12.0.1

Asp*_*eri 8

只需将所有内容移至onAppear单独的函数中,并在工作表上调用该函数即可,例如

var body: some View {
    VStack{
        VStack{
            Text("BaseView")

            Button(action:{
                isSheet = true
            }){
                Text("SHEET")
            }
        }
        .onAppear(){
            foo()       // << here !!
        }
        .sheet(isPresented: $isSheet, onDismiss: {
            foo()       // << and here !!
        }){
            Sheet()
        }
    }
}

func foo() {
   print("do some here")
}
Run Code Online (Sandbox Code Playgroud)