如何从嵌套视图更改@State 属性 包装器

How to change @State property wrapper from nested view

我想知道如何在下面的视图中更改@State 属性 wrapper showErrorAlert

struct SettingsView: View {
@State private var shouldPresent = false
@State var showErrorAlert = false
var body: some View {
    VStack {
        Form {
            Text("Settings")
                .font(.title)
            Button("Import source data") {
                self.shouldPresent.toggle()
            }
            .sheet(isPresented: $shouldPresent) {
                DocumentPicker()
            }
            Button("Show error alert") {
                self.showErrorAlert.toggle()
            }
            .alert(isPresented: $showErrorAlert, content: {
                Alert(title: Text("Error"))
            })
        }
    }
}
}

来自 DocumentPicker 结构代码,以防读取所选文件失败。

struct DocumentPicker: UIViewControllerRepresentable {

func makeCoordinator() -> DocumentPicker.Coordinator {
    return DocumentPicker.Coordinator(parent: self)
}

func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController {
    let picker = UIDocumentPickerViewController(documentTypes: [String(kUTTypeJSON)], in: .import)
    picker.allowsMultipleSelection = false
    picker.delegate = context.coordinator
    return picker
}

func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<DocumentPicker>) {
}

class Coordinator: NSObject, UIDocumentPickerDelegate {

    var myParent: DocumentPicker
    init(parent: DocumentPicker) {
        myParent = parent
    }

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        let fileURL = urls.first!
        do {
            let origFile = try String(contentsOf: fileURL)
            //File processing will be here
        } catch let error {
            print(error)
        }
    }
}
}

我的意思是如何将 属性 包装器值设置为 true 以显示警报。我应该改用@ObservedObject 还是@EnvironmentObject? 谢谢

要更改 DocumentPicker 结构中的包装器值,您可以定义一个 @Binding 变量并将您的值传递给它,这会在您的父视图上切换您的变量,但在显示警报之前您需要关闭文档选择器