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

时间:2020-02-06 20:56:56

标签: state swiftui property-wrapper

我想知道如何在下面的视图中更改@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代替? 谢谢。

1 个答案:

答案 0 :(得分:2)

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