如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图 [英] How to navigate another view in onReceive timer closure SwiftUI iOS

查看:44
本文介绍了如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在计时器达到特定时间时导航到另一个视图.例如,我想在 5 分钟后导航到另一个视图.在 swift 中,我可以轻松实现这一点,但我是 SwiftUI 的新手,我们将不胜感激.

I am trying to achieve a navigation to another view when timer hits a specific time. For example I want to navigate to another view after 5 minutes. In swift i can easily achieve this but I am new to SwiftUI and little help will be highly appreciated.

我的代码:

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 在父级的某处有 NavigationView)

Here is possible approach (of course assuming that TwitterWebView has NavigationView somewhere in parents)

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
            }
        }
    }
}

这篇关于如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆