3

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()
    }
}
GarySabo
  • 5,806
  • 5
  • 49
  • 124

1 Answers1

1

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)")
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • working well now thanks! In my production app I wrapped an earlier view in the stack inside a NavigationView, and in this view I was wrapping again inside a navigation view and it wasn't appearing at all. When I removed the NavigationView earlier in the stack it now appears AND counts down. – GarySabo Dec 04 '20 at 21:10
  • 1
    I see the same issue, but am not able to get it working. not saying this is a bad answer, just that it won't work for everyone :( – lewis Sep 14 '21 at 13:23