首页 > 解决方案 > 在 MACOS 上使用 Catalyst 的 UIDocumentPickerViewController

问题描述

我在 MacOS 中使用 Catalyst 显示选择器的代码:

final class DocumentPicker: NSObject, UIViewControllerRepresentable, ObservableObject {
    typealias UIViewControllerType = UIDocumentPickerViewController
    @Published var urlsPicked = [URL]()

    lazy var viewController:UIDocumentPickerViewController = {
        // For picked only folder
        let vc = UIDocumentPickerViewController(documentTypes: ["public.folder"], in: .open)
        vc.allowsMultipleSelection = false
        vc.delegate = self
        return vc
    }()        
    ........

和:

struct ContentView: View {
    @ObservedObject var picker = DocumentPicker()
    @State private var urlPick = ""

    var body: some View {
        HStack {
            Text(urlPicked())
                .padding()
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(Color.white, lineWidth: 1)
                )
            TextField("", text: $urlPick)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .font(.system(size: 10))
                .disabled(true)
            Spacer()
            Button(action: {
                #if targetEnvironment(macCatalyst)
                let viewController = UIApplication.shared.windows[0].rootViewController!
                viewController.present(self.picker.viewController, animated: true)
                self.picker.objectWillChange.send()
                #endif
                print("Hai premuto il pulsante per determinare il path della GeoFolder")
            }) {
                Image(systemName: "square.and.arrow.up")
            }
        }
        .padding()
    }

    private func urlPicked() -> String {
        var urlP = ""
        if picker.urlsPicked.count > 0 {
            urlP = picker.urlsPicked[0].path
            urlPick = picker.urlsPicked[0].path
        }
        return urlP
    }
}

如果我运行上面的代码,我会得到选择的正确路径text,而什​​么textfield都没有,而且我也有错误urlPick = picker.urlsPicked[0].pathModifying state during view update, this will cause undefined behavior. 如何修改代码以显示选择的正确路径textfield

标签: macosswiftuimac-catalyst

解决方案


在 urlPick = picker.urlsPicked[0].path: Modifying state during view update 中有错误,这将导致未定义的行为。如何修改代码以显示在文本字段中选择的正确路径?

尝试以下

    if picker.urlsPicked.count > 0 {
        urlP = picker.urlsPicked[0].path
        DispatchQueue.main.async {
            urlPick = picker.urlsPicked[0].path
        }
    }

推荐阅读