选择了选择器选项后,为什么我的SwiftUI页面标题会更改?

时间:2020-07-13 03:09:24

标签: ios swiftui swiftui-picker

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 个答案:

答案 0 :(得分:1)

回答我自己的问题,可以通过将Form包装在Section中并在其上定义navigationBarTitle来解决。

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

我从this answer中得到了这个主意,尽管我不知道为什么标题需要定义两次。