Search code examples
iosswiftswiftuipicker

Change Navigation Title of Picker in SwiftUI


I'd like to set a navigation title when an user selected some option in Picker

Here is my selection model:

enum AppIcon: CaseIterable, Identifiable {

    var id: Self {
        return self
    }

    case `default`
    case ethereum
    case litecoin

    var name: String {
        switch self {
        case .default:
            return "Bitcoin"
        case .ethereum:
            return "Ethereum"
        case .litecoin:
            return "Litecoin"
        }
    }
}

and here is my view

struct ContentView: View {
    @State var icon: AppIcon = .default
    var body: some View {
        NavigationView {
            Form {
                Section {
                    Picker(selection: $icon, label: Text("Icon")) {
                        ForEach(AppIcon.allCases) { icon in
                            Text(icon.name).tag(icon)
                        }
                    }
                }
            }
            .navigationBarTitle("Appearance")
        }
    }
}

I want to get that behavior:

enter image description here

but I tried to put .navigationBarTitle("Title") after any close bracket and it doesn't work.


Solution

  • I have tried to solve issue.

    struct ContentView: View {
        
        @State var icon: AppIcon = .default
        
        var body: some View {
            NavigationView {
                Form {
                    Section {
                        Picker(selection: $icon, label: Text("Icon")) {
                            ForEach(AppIcon.allCases) { icon in
                                Text(icon.name).tag(icon)
                            }
                            .navigationBarTitle("Title") // for picker navigation title 
                        }
                        .navigationBarTitle("Appearance")
                    }
                }
            }
        }
    }