macos - 在 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].path
:Modifying state during view update, this will cause undefined behavior.
如何修改代码以显示选择的正确路径textfield
?
解决方案
在 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
}
}
推荐阅读
- nginx - 蓝/绿部署的零停机 nginx 动态重新加载
- python - 如何在 PYTHONHUNTER 环境变量中包含多个模块
- vb.net - 尝试在子项目任务上使用 LINQ 时出现 MissingMemberException
- react-hooks - 我们可以在 textarea react 中使用模式吗?
- mysql - 左连接 SQL 表
- hive - 在 hive 上对不同的时间范围进行分组
- python - 归一化双变量概率密度函数 - python
- azure - Azure DevOps Pipeline Flutter 安装任务错误
- python - 如何在python中输入curl命令?
- python - 如何在树莓派 3 上安装 Python 3.8.0