Why does my SwiftUI page title change when a picker option is selected?

731 Views Asked by At
struct SettingsView: View {
    let settings: [Setting] = [
        Setting(name: "Aperture Increments", options: ["1/3", "1/2", "1"]),
        Setting(name: "Shutter Speed Increments", options: ["1/3", "1/2", "1"]),
        Setting(name: "ISO Increments", options: ["1/3", "1/2", "1"])
    ]
    
    var body: some View {
        NavigationView {
            Form {
                ForEach(self.settings, id: \.name) { setting in
                    SettingDetailView(setting: setting)
                }
            }
            .navigationBarTitle("Settings", displayMode: .inline)
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct SettingsView_Previews: PreviewProvider {
    static var previews: some View {
        SettingsView()
    }
}

struct SettingDetailView: View {
    let setting: Setting
    @State var selection: String = ""
    
    var body: some View {
        Picker(selection: $selection, label: Text(setting.name)) {
            ForEach(self.setting.options, id: \.self) { option in
                Text(option).tag(option)
            }
            .navigationBarTitle(Text(setting.name), displayMode: .inline)
        }
    }
}

enter image description here

1

There are 1 best solutions below

5
On BEST ANSWER

Answering my own question, this problem is solved by wrapping the Form in a Section and defining the navigationBarTitle on it.

Form {
  Section {
    ...
  }.navigationBarTitle("Settings", displayMode: .inline)
}.navigationBarTitle("Settings")

I got the idea from this answer, although I've no idea why the title needs to be defined twice.