Saturday, November 21, 2026
HomeiOS Developmentios - SwiftUI: Timer.TimerPublisher nonetheless firing from mother or father view after...

ios – SwiftUI: Timer.TimerPublisher nonetheless firing from mother or father view after navigation

[ad_1]

I’m making a recreation and I observed some conduct of NavigationLink() which I do not perceive. Right here is my code:

struct ParentView: View {
    @State var motion: Int? = 0 // to make use of for navigationLink
    @State var refreshView: Bool? = false
    @State var counter = 0
    
    init (_ counter: Int = 0) {
        self.counter = counter
    }
    
    var physique: some View {
        NavigationView {
            HStack {
                let timer = Timer
                    .publish(each: 1, on: .foremost, in: .default)
                    .autoconnect()
                VStack {
                    NavigationLink(vacation spot: OtherView(counter:$counter), tag: 2, choice: $motion) {}
                    Button {
                        //refreshView = nil // MARK: first a part of my workaround
                        self.motion = 2
                    } label: {
                        Textual content("Navigate to Different View!")
                    }
                    Textual content("(counter)")
                    if let r = refreshView, r {} // refreshView altering this causes the view to refresh
                }
                .onReceive(timer) { _ in
                    refreshView?.toggle()
                    if let _ = refreshView { // MARK: the opposite a part of my workaround
                        counter += 1
                    }
                }
            }
        }
    }
}

struct OtherView: View {
    @Binding var counter: Int

    var physique: some View {
        VStack {
            NavigationLink(vacation spot: ParentView(counter)) {
                Textual content("counter: (counter)")
            }
            Button {
                counter += 1
            } label: {
                Textual content("counter++")
            }
            Button {
                counter -= 1
            } label: {
                Textual content("counter--")
            }
        }
    }
}

I assumed (wrongly) that the Timer.TimerPublisher would cease publishing occasions after its view was now not on display. As you may see within the code, my workaround is to edit the .onReceive() to solely do something if refreshView != nil successfully disabling the counter from auto-incrementing after the navigation. Is there a approach I can merely disable the timer instantly or unload the earlier view after navigation in order that the incrementing stops? Thanks prematurely.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments