Search code examples
swiftuinavigationview

Adding a Subtitle under NavigationTitle


Let's say I have the following code:

struct SwiftUIView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Hello")
                Text("World")
            }
            .navigationTitle("SwiftUI")
        }
    }
}

I'd like to add a smaller subtitle right under SwiftUI. I tried adding something like .navigationSubtitle("") but it doesn't exist. I also tried reading the documentation, and it does mention func navigationSubtitle(_ subtitle: Text) -> some View, but I'm just not sure how to add that to my code. Thanks in advance!


Solution

  • You can add a ToolbarItem with the principal placement:

    struct SwiftUIView: View {
        var body: some View {
            NavigationView {
                VStack {
                    Text("Hello")
                    Text("World")
                }
                // .navigationTitle("SwiftUI") this won't make any changes now
                .toolbar {
                    ToolbarItem(placement: .principal) {
                        VStack {
                            Text("title")
                            Text("subtitle")
                        }
                    }
                }
            }
        }
    }
    

    The downside is that it overrides the navigation title, so any changes made with navigationTitle won't visible.