我正在开发一个 SwiftUI 项目,但无法让选择器正常工作。
我将视图层次结构拆分为多个文件,初始视图将所有内容包装在 NavigationView 中。
看起来像这样:
MainFile (TabView -> NavigationView)
- ListPage (NavigationLink)
-- DetailHostPage (Group.EditButton)
if editing
--- DetailViewPage
else
--- DetailEditPage (picker in a form)
我拥有的选择器DetailEditPage
不允许我更改它的值,尽管它确实显示了正确的当前值。
Picker(selection: self.$_myObj.SelectedEnum, label: Text("Type")) {
ForEach(MyEnum.allCases, id: \.self) {
Text("\(String(describing: $0))")
}
}
如果我直接将选择器包装在导航视图中,那么它可以工作,但现在我有一个嵌套导航视图,导致两个后退按钮,这不是我想要的。
是什么导致选择器不允许它的选择改变,我怎样才能让它工作?
编辑
以下是如何复制此内容的示例:
内容视图.swift
class MyObject: ObservableObject {
@Published var enumValue: MyEnum
init(enumValue: MyEnum) {
self.enumValue = enumValue
}
}
enum MyEnum: CaseIterable {
case a, b, c, d
}
struct ContentView: View {
@State private var objectList = [MyObject(enumValue: .a), MyObject(enumValue: .b)]
var body: some View {
NavigationView {
List {
ForEach(0..<objectList.count) { index in
NavigationLink(destination: Subview(myObject: self.$objectList[index])) {
Text("Object \(String(index))")
}
}
}
}
}
}
struct Subview: View {
@Environment(\.editMode) var mode
@Binding var myObject: MyObject
var body: some View {
HStack {
if mode?.wrappedValue == .inactive {
//The picker in this view shows
SubViewShow(myObject: self.$myObject)
} else {
//The picker in this view does not
SubViewEdit(myObject: self.$myObject)
}
}.navigationBarItems(trailing: EditButton())
}
}
struct SubViewShow: View {
@Binding var myObject: MyObject
var body: some View {
Form {
Picker(selection: self.$myObject.enumValue, label: Text("enum values viewing")) {
ForEach(MyEnum.allCases, id: \.self) {
Text("\(String(describing: $0))")
}
}
}
}
}
struct SubViewEdit: View {
@Binding var myObject: MyObject
var body: some View {
Form {
Picker(selection: self.$myObject.enumValue, label: Text("enum values editing")) {
ForEach(MyEnum.allCases, id: \.self) {
Text("\(String(describing: $0))")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}