Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change Navigation Title in SwiftUI?

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()
    }
}
like image 593
GarySabo Avatar asked Jun 27 '26 21:06

GarySabo


1 Answers

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)")
    }
}
like image 58
Asperi Avatar answered Jun 30 '26 11:06

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!