如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图

2024-01-02

我试图在计时器达到特定时间时实现到另一个视图的导航。例如,我想在 5 分钟后导航到另一个视图。在 Swift 中,我可以轻松实现这一点,但我是 SwiftUI 的新手,非常感谢一些帮助。

My code:

struct TwitterWebView: View {
    
    @State var timerTime : Float
    @State var minute: Float = 0.0
    @State private var showLinkTarget = false
    let timer = Timer.publish(every: 60.0, on: .main, in: .common).autoconnect()
    
    var body: some View {
        
        WebView(url: "https://twitter.com/")
        .navigationBarTitle("")
        .navigationBarHidden(true)
        
        .onReceive(timer) { _ in
            if self.minute == self.timerTime {
                print("Timer completed navigate to Break view")
                NavigationLink(destination: BreakView()) {
                    Text("Test")
                }
                self.timer.upstream.connect().cancel()
            } else {
                self.minute += 1.0
            }
        }
    }
}

这是可能的方法(当然假设TwitterWebView has NavigationView父母的某个地方)

struct TwitterWebView: View {

    @State var timerTime : Float
    @State var minute: Float = 0.0
    @State private var showLinkTarget = false
    let timer = Timer.publish(every: 60.0, on: .main, in: .common).autoconnect()

    @State private var shouldNavigate = false

    var body: some View {

        WebView(url: "https://twitter.com/")
        .navigationBarTitle("")
        .navigationBarHidden(true)

        .background(
            NavigationLink(destination: BreakView(), 
                              isActive: $shouldNavigate) { EmptyView() }
        )

        .onReceive(timer) { _ in
            if self.minute == self.timerTime {
                print("Timer completed navigate to Break view")
                self.timer.upstream.connect().cancel()

                self.shouldNavigate = true      // << here
            } else {
                self.minute += 1.0
            }
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图 的相关文章

随机推荐