【问题标题】:How to navigate another view in onReceive timer closure SwiftUI iOS如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图
【发布时间】:2020-08-03 23:58:32
【问题描述】:

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

我的代码:

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

【问题讨论】:

    标签: ios swift timer swiftui swiftui-navigationlink


    【解决方案1】:

    这是可能的方法(当然假设 TwitterWebView 在父母的某处有 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
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多