Configurable Navigation Title in SwiftUI 4

DevTechie Inc
May 10, 2023

Starting SwiftUI 4 and iOS 16 we can configure/change navigation title dynamically.

On iOS, when a view is inside a navigation stack, it’s title is displayed in navigation bar. In its simplest form navigation title modifier takes a string parameter as the value for navigation title.

struct DevTechieConfigurableNavigationTitle: View {
    var body: some View {
        NavigationStack {
            VStack {
                Text("New in SwiftUI 4 : Configurable Navigation Title")
                    .font(.title3)
                    .padding()
                    .background(.orange.gradient, in: RoundedRectangle(cornerRadius: 20))
                    .foregroundColor(.white)
            }
            .navigationTitle("DevTechie")
        }
    }
}

But starting iOS 16 and SwiftUI 4, we can provide text binding to the navigation title modifier and SwiftUI will automatically configure and reflect the toolbar to reflect the new title. SwiftUI automatically syncs the navigation title with the value of the string binding provided.

Let’s look at this by adding a State property to hold navigation title. We will add TextField to change the State property and bind this State property to the navigationTitle modifier.

struct DevTechieConfigurableNavigationTitle: View {
    @State private var dynamicTitle = "DevTechie"
    var body: some View {
        NavigationStack {
            VStack {
                Text("New in SwiftUI 4 : Configurable Navigation Title")
                    .font(.title3)
                    .padding()
                    .background(.orange.gradient, in: RoundedRectangle(cornerRadius: 20))
                    .foregroundColor(.white)
                
                TextField("Enter title here", text: $dynamicTitle)
                    .textFieldStyle(.roundedBorder)
            }
            .padding()
            .navigationTitle($dynamicTitle)
        }
    }
}