swiftUI 未在较低层级中刷新 ui

swiftUI is not refresh ui in lower hierarchy

我在 viewmodel 中有一个 @Published var showDialog: Bool = false,一旦它是 true,我想显示一个对话框,但是对于某些 resone 它不显示任何,如果我在上层 Uis 中更改 showDialog 则相同的代码可以工作

我的主视图

 @StateObject  var viewModel = ViewModel.instance


    UploadlingImages( )
     .alert(isPresented: $ViewModel.showDialog) {
      Alert(title:  Text("Content View Alert"),
      message:  Text("Content View Alert"),
    dismissButton: .default(Text("OK")))
    }

内部视图使用的代码,这是画廊选择器

struct ImagePickerSwiftUI: UIViewControllerRepresentable {
    @SwiftUI.Environment(\.presentationMode) private var presentationMode
   
    @StateObject  var viewModel = ViewModel.instance
    
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePickerSwiftUI>) -> UIImagePickerController {
     
        let imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = false
        imagePicker.sourceType = sourceType
        imagePicker.delegate = context.coordinator

        return imagePicker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePickerSwiftUI>) {

    }

    func makeCoordinator() -> Coordinator {
     
      return  Coordinator(self)
    }

    final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

        var parent: ImagePickerSwiftUI

        init(_ parent: ImagePickerSwiftUI) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
  
            parent.presentationMode.wrappedValue.dismiss()
            
           viewModel.showDialog = true // this line in not updateing ui
        
        }

    }
}

假设ViewModel.instance是共享单例并且showDialog被发布属性,原因可能是close/open sheet流程(演示)冲突,所以试试

parent.presentationMode.wrappedValue.dismiss()

// delay for previous presentation get closed !!
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
   ViewModel.instance.showDialog = true
}