Search code examples
swiftuiswiftui-navigationstack

How can I make a NavigationTitle in SwiftUI open a picker view?


I understand that you can bind a string to the navigation title like:

.navigationTitle($titleString)

and you get:

enter image description here

and this will allow you to rename it, but is there a way to bind this to an enum to get a picker view?

(this doesn't work btw) :

enum LibraryViewType: String, CaseIterable {
    case albums, songs, artists
}

...

@State private var viewType: LibraryViewType = .albums

...

.navigationTitle($viewType)

Solution

  • This is where you should use ToolbarTitleMenu. That is the menu that is displayed when you tap the down-arrow next to the title. You can put your picker there, and set the title to a string representation of the currently selected enum value.

    @State var type = LibraryViewType.albums
    
    var body: some View {
        NavigationStack {
            Color.white // dummy view to put a toolbar on
                .toolbar {
                    ToolbarTitleMenu {
                        Picker("Picker", selection: $type) {
                            ForEach(LibraryViewType.allCases, id: \.self) { item in
                                Text(item.rawValue)
                            }
                        }
                    }
                }
                .navigationBarTitleDisplayMode(.inline)
                .navigationTitle(type.rawValue)
        }
    }