swiftui - SwiftUI - 倒计时结束时,跳转到另一个视图
问题描述
倒计时结束后,我想跳转到另一个视图。我尝试了navigationLink,但它没有用。
这是我的代码。
struct TimerView: View {
@State var timeRemaining = 5
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
Text("\(timeRemaining)")
.font(.largeTitle)
.onReceive(timer) { _ in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
}
}
}
}
解决方案
尝试一些变化:
struct TimerView: View {
@State var timeRemaining = 5
@State var jump = false
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
NavigationView {
VStack {
Text("\(timeRemaining)")
.font(.largeTitle)
.onReceive(timer) { _ in
if timeRemaining > 0 {
timeRemaining -= 1
} else {
jump = true
// optional stop the timer
timer.upstream.connect().cancel()
}
}
NavigationLink("", destination: Text("the other view"), isActive: $jump)
}
}
}
}