Fixing SwiftUI fileExporter Not Appearing
原則:同一個 View,或同一條 SwiftUI modifier chain,不要掛多個 .fileExporter。需要多個匯出入口時,把每個 .fileExporter 掛到各自的 sibling view。
1
2
3
4
5
NavigationStack {
List { ... }
}
.fileExporter(isPresented: $viewModel.isCollectionProgressExporterPresented, item: ...)
.fileExporter(isPresented: $viewModel.isIconExporterPresented, item: ...)
查到的案例指出,多個 .fileExporter 在同一條 view tree 分支時,只有其中一個會呈現;另一個按了就像沒反應。解法是把 exporter 拆到各自的 sibling view,讓每個按鈕管理自己的 presentation modifier。1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Button {
viewModel.prepareCollectionProgressExport(modelContext: modelContext)
} label: {
Label("収集進捗を書き出し", systemImage: "doc.badge.arrow.up")
}
.fileExporter(
isPresented: $viewModel.isCollectionProgressExporterPresented,
item: viewModel.collectionProgressExportFile,
contentTypes: [.json],
defaultFilename: viewModel.collectionProgressExportDefaultFilename,
onCompletion: viewModel.collectionProgressExportCompleted,
onCancellation: viewModel.collectionProgressExportCancelled
)
Button {
viewModel.prepareIconExport(modelContext: modelContext)
} label: {
Label("画像を書き出し", systemImage: "photo.on.rectangle.angled")
}
.fileExporter(
isPresented: $viewModel.isIconExporterPresented,
item: viewModel.iconExportFile,
contentTypes: [.zip],
defaultFilename: viewModel.iconExportDefaultFilename,
onCompletion: viewModel.iconExportCompleted,
onCancellation: viewModel.iconExportCancelled
)
Apple 文件也說 fileExporter 是由 isPresented binding 觸發;完成或取消時,系統會把 binding 設回 false 並呼叫 callback。2 這次 log 沒有 completion/cancel,表示 presentation 根本沒有成功啟動。
This post is licensed under CC BY 4.0 by the author.