Dynamically change Navigation Title in SwiftUI?

1.6k views Asked by At

Is it not possible to have a dynamic Navigation Title in SwiftUI. The below code doesn't update the title as the timer elapses. Is there any way to do this? (this is in WatchOS)

(code edited for more testable example)

import SwiftUI

struct TimerTestView: View {
    
    @State private var timeRemaining = 100
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    
    var body: some View {
        Text("\(timeRemaining)")
            .onReceive(timer) { time in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                }
            }
            .navigationTitle("\(timeRemaining)")
    }
}

struct TimerTestView_Previews: PreviewProvider {
    static var previews: some View {
        TimerTestView()
    }
}
1

There are 1 answers

2
Asperi On BEST ANSWER

Just wrapped into NavigationView solves the issue (Xcode 12.1 / watchOS 7.0)

demo

var body: some View {
    NavigationView {
        Text("\(timeRemaining)")
                .onReceive(timer) { time in
                     if self.timeRemaining > 0 {
                          self.timeRemaining -= 1
                     }
                }
            .navigationTitle("\(timeRemaining)")
    }
}