选择选择器选项后,为什么我的 SwiftUI 页面标题会发生变化?
Why does my SwiftUI page title change when a picker option is selected?
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)
}
}
}
回答我自己的问题,这个问题是通过将 Form
包装在 Section
中并在其上定义 navigationBarTitle
来解决的。
Form {
Section {
...
}.navigationBarTitle("Settings", displayMode: .inline)
}.navigationBarTitle("Settings")
我从this answer那里得到了灵感,虽然我不知道为什么标题需要定义两次。
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)
}
}
}
回答我自己的问题,这个问题是通过将 Form
包装在 Section
中并在其上定义 navigationBarTitle
来解决的。
Form {
Section {
...
}.navigationBarTitle("Settings", displayMode: .inline)
}.navigationBarTitle("Settings")
我从this answer那里得到了灵感,虽然我不知道为什么标题需要定义两次。