ios - 如何在 onReceive 定时器关闭 SwiftUI iOS 中导航另一个 View

标签 ios swift timer swiftui swiftui-navigationlink

当计时器到达特定时间时,我试图实现到另一个 View 的导航。例如,我想在 5 分钟后导航到另一个 View 。在 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
            }
        }
    }
}

最佳答案

这是可能的方法(当然假设 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
            }
        }
    }
}

关于ios - 如何在 onReceive 定时器关闭 SwiftUI iOS 中导航另一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63238476/

相关文章:

ios - 在 iOS 中测试 IAP 边界情况(例如 : missing credit card info, 等)

ios - 在数据库中进行一系列插入后内存不会减少

ios - 辅助功能 VoiceOver 不适用于 UILabel

ios - 为什么 NSURLProtocol 子类中请求的 HTTPBody 始终为零?

ios - Facebook SDK 登录不适用于 iOS 10、Xcode 8 上的模拟器

android - 计时器格式更改为 0 :0 to 00:00?

Swift SpriteKit 将计时器添加到 GameScene

ios - 为 UItableview swift 中的每一行添加新的(不可重复使用的)单元格

java - JPanel Image仅在paintComponent循环结束后更新

ios - 无法将类型 'Int' 的值转换为预期的参数类型 'UInt32'