0

我想知道我应该如何在下面的视图中更改@State 属性包装器 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?谢谢。

4

1 回答 1

2

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

于 2020-02-06T21:08:29.347 回答