[英]SwiftUI: NavigationLink doesn't show animation if setting after background task
我正在嘗試將新的異步/等待並發代碼與 SwiftUI 視圖一起使用,以在單擊按鈕后執行一些基本的異步數據加載,以顯示微調器視圖,並在完成后轉換到新頁面。 我使用枚舉來標記視圖的狀態,並將其與 NavigationLink 一起使用以前進到新視圖。 這有效,並在“推送”到下一個視圖之前顯示“正在加載”文本視圖一秒鍾,但是當新視圖被推送時沒有動畫。 這是我正在使用的代碼:
import SwiftUI
enum ContinueActionState: Int {
case ready = 0
case showProgressView = 1
case pushToNextPage = 2
case readingError = 3
case error = 4
}
struct ContentView: View {
@State var actionState: ContinueActionState? = .ready
var body: some View {
NavigationView {
VStack {
Text("Test the Button!")
if (actionState == .showProgressView) {
ProgressView("Loading Data")
} else if (actionState == .error || actionState == .readingError) {
Text("Error in loading something")
}
else {
NavigationLink(destination: DetailPageView(), tag: .pushToNextPage, selection: $actionState) {
Button(action: {
Task {
print("on buttonClick isMain =\(Thread.isMainThread)")
self.actionState = .showProgressView
await self.startProcessingData()
//self.actionState = .pushToNextPage // animation works if only this is used
}
}) {
Text("Continue")
}
.tint(.blue)
.buttonStyle(.borderedProminent)
.buttonBorderShape(.roundedRectangle(radius: 5))
.controlSize(.large)
}
}
}.navigationTitle("Test Async")
}
}
func startProcessingData() async {
Task.detached {
print("startProcessingData isMain =\(Thread.isMainThread)")
try await Task.sleep(nanoseconds: 1_000_000_000)
//await MainActor.run {
self.actionState = .pushToNextPage
//}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct DetailPageView: View {
var body: some View {
Text("Detail page")
}
}
如果我只是放棄異步調用並在按鈕單擊時立即設置為.pushToNextPage
狀態,則動畫效果很好。
在后台隊列任務中的處理完成后,有什么方法可以讓它與流暢的動畫一起工作?
如果您將NavigationLink
從if
語句中移出,它對我來說很好:
NavigationView {
VStack {
Text("Test the Button!")
NavigationLink(destination: DetailPageView(), tag: .pushToNextPage, selection: $actionState) { Text("") } // here
if (actionState == .showProgressView) {
ProgressView("Loading Data")
} else if (actionState == .error || actionState == .readingError) {
Text("Error in loading something")
}
else {
Button(action: {
Task {
print("on buttonClick isMain =\(Thread.isMainThread)")
self.actionState = .showProgressView
await self.startProcessingData()
}
}) {
Text("Continue")
}
.tint(.blue)
.buttonStyle(.borderedProminent)
.buttonBorderShape(.roundedRectangle(radius: 5))
.controlSize(.large)
}
}.navigationTitle("Test Async")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.