Home > OS >  Swiftui NavigationView timer delay
Swiftui NavigationView timer delay

Time:10-06

In my app I navigate to a page (say, page 2), then wish to show an animation (and nothing else) on the page, before executing and moving to a new view using NavigationView. In other words, I'd like the NavigationView destination view to load after a delay timer (say 3 seconds), without the user having to click a button. During that 3 seconds, the animation will be running. The animation and the NavigationView work fine on their own, but my current solution requires the user to click a button/text to move to the destination view, which is a little clunky. I can't find a solution anywhere. Any help would be greatly appreciated. Thanks!

CodePudding user response:

This should work:

struct MyView: View {
    @State var pushNewView: Bool = false
    
    var body: some View {
        NavigationView {
            NavigationLink(isActive: $pushNewView) {
                Text("Second View")
            } label: {
                Text("First View") //Replace with some animation content
            }
        }
        .onAppear {
            Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { _ in
                pushNewView = true
            }
        }
    }
}

CodePudding user response:

Alternatively:

struct MyView: View {
    @State var pushNewView: Bool = false
    
    var body: some View {
        NavigationView {
            NavigationLink(isActive: $pushNewView) {
                Text("Second View")
            } label: {
                Text("First View") //Replace with some animation content
            }
        }
        .onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now()   3) {
                pushNewView = true
            }
        }
    }
}
  • Related