swift 从fullScreenCover返回时如何触发onAppear

jjhzyzn0  于 2023-09-30  发布在  Swift
关注(0)|答案(3)|浏览(137)

onAppear不会触发

struct ProfileView: View {
    @StateObject var viewModel = ProfileViewViewModel()
    var body: some View {
        NavigationView {
            VStack {
                if let user = viewModel.user {
                    profile(user: user)
                } else {
                    Text("Loading Profile...")
                }
            }
            .navigationTitle("Profile")
        }
        .onAppear {
            viewModel.fetchUser() //this is the problem
        }
        .fullScreenCover(isPresented: $viewModel.showingPreview) {
            PreviewAvatarView()
        }
    }
}

我意识到,当我关闭全屏时,onAppear并没有触发。

mtb9vblg

mtb9vblg1#

你可以使用task来代替onAppear

struct ProfileView: View {
    @StateObject var viewModel = ProfileViewViewModel()
    var body: some View {
        NavigationView {
            VStack {
                if let user = viewModel.user {
                    profile(user: user)
                } else {
                    Text("Loading Profile...")
                }
            }
            .navigationTitle("Profile")
        }
        .task(id: viewModel.showingPreview) {
            guard !viewModel.showingPreview else {return} //Check for false
    
            viewModel.fetchUser() //this is the problem
        }
        .fullScreenCover(isPresented: $viewModel.showingPreview) {
            PreviewAvatarView()
        }
    }
}

task将运行onAppear,当Boolfalse时。

pdkcd3nj

pdkcd3nj2#

onAppear不会触发,因为底层视图没有出现-覆盖它的视图消失了,这不是一回事。
但是,fullScreenCover有一个很少使用的可选参数onDismiss,它可以满足您的需求,例如:

.fullScreenCover(
  isPresented: $viewModel.showingPreview,
  onDismiss: { viewModel.fetchUser() }
) {
  PreviewAvatarView()
}

Apple documentation

t5fffqht

t5fffqht3#

你可以试试这个解决方案。

struct ProfileView: View {
    @StateObject var viewModel = ProfileViewViewModel()
    var body: some View {
        NavigationView {
            VStack {
                if let user = viewModel.user {
                    profile(user: user)
                } else {
                    Text("Loading Profile...")
                }
            }
            .navigationTitle("Profile")
        }
        .onAppear {
            viewModel.fetchUser() //this is the problem
        }
        .fullScreenCover(isPresented: $viewModel.showingPreview) {
            PreviewAvatarView()
        }
        .onChange(of: viewModel.showingPreview) { isFullScreenOpen in
            if !isFullScreenOpen {
                viewModel.fetchUser()
            }//Executed only when full screen cover is closed.
        }
    }
}

每当工作表关闭时,viewModel.fetchUser()将被执行。

相关问题