我有 List
的屏幕的意见其中之一是 NavigationLink
导航到单独的屏幕 DocumentPreviewView
显示 PDF 文档的位置。
这个PDF文档需要在点击按钮后在第一屏异步下载,需要传递给DocumentPreviewView
屏幕。
我来到了工作解决方案,但我正在寻找更优雅的方式和更多的 SwiftUI 方式。
也许文档应该是某种可观察的对象。
这是我目前的解决方案。如您所见,我使用了隐藏的 NavigationLink,它是由按钮操作的回调触发的,我还下载了需要呈现的文档。
@State private var document = PDFDocument()
@State private var docState: DocState? = .setup
enum DocState: Int {
case setup = 0
case ready = 1
}
var body: some View {
List {
/// some other views
Button(action: {
someAsyncFunction { doc, error in
self.document = doc
self.docState = .ready
}
}) {
Text("Show Document")
}
/// some other views
}
NavigationLink(
destination: DocumentPreviewView(pdfDocument: document),
tag: .ready,
selection: $docState) {
EmptyView()
}
}
最佳答案
可能的解决方案
struct ContentView: View {
@State private var docState: DocState? = .setup
enum DocState: Int {
case setup = 0
case ready = 1
}
var body: some View {
NavigationView {
ZStack {
NavigationLink(
destination: Text("Preview"),
tag: .ready,
selection: $docState) {
Button(action: {
someTask() { isTaskDone in
docState = .ready
}
}) {
Text("Download")
}
}
}
}
}
func someTask(_ completion: @escaping ((Bool)->())) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
completion(true)
}
}
}
关于ios - 异步任务后 SwiftUI 中的正确导航方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65643188/