数据更改时,选择器会删除选定的段

Picker drops selected segment when data changed

我遇到了 Picker 的问题。当我尝试更改所选段中的数据状态时,它会将其丢弃(附 gif)。当显示数据发生变化时,我如何在 Picker 中保持选定的段(当我按下“love”按钮时,选定的段应该保持不变)

单项有选项:

struct Landmark: Identifiable, Codable, Hashable {
var id: Int
var name: String
var imageName: String
var mainImage: Image {
    Image(imageName)
var liked: Bool
var popular: Bool
var recommended: Bool
}

我得到 class 对象数组:

final class ModelData: ObservableObject {
@Published var landmarks: [Landmark]
}

并尝试像这样使用选择器:

struct tempSegmentControl: View {

@EnvironmentObject var modelData: ModelData

@State private var selected = ModelData().landmarks

var popularLandmarks: [Landmark] {
    modelData.landmarks.filter { landmark in
        (landmark.popular)
    }
}

var rocommendedLandmarks: [Landmark] {
    modelData.landmarks.filter { landmark in
        (landmark.recommended)
    }
}

    var body: some View {
        VStack {
            Picker("Selection", selection: $selected) {
                Text("All").tag(modelData.landmarks)
                Text("Popular").tag(popularLandmarks)
                Text("Recommended").tag(rocommendedLandmarks)

            }
            .pickerStyle(SegmentedPickerStyle())
            .frame(width: UIScreen.main.bounds.width * 0.95)
            
            ForEach(selected, id: \.id) { land in
                NavigationLink(
                    destination: DetailView2(landmark: land)) {
                    MainItem3(landmark: land)
                    }
           }
        }
    }
}

Drop selected segment

selection: 无法正常使用这样的数组类型 ([Landmark])。

相反,您可能想要做一些简单的事情,例如:

@State private var selection = 0
//...
Picker("Selection", selection: $selection) {
   Text("All").tag(0)
   Text("Popular").tag(1)
   Text("Recommended").tag(2)

然后为您稍后迭代的数组使用计算的 属性:

var selected : [Landmark] {
  switch selection {
    case 0:
      return modelData.landmarks
    case 1:
      //etc
  }
}

您也可以使用 enum : Int 来执行此操作,如果您以后扩展案例,这可能会更安全一些(并且它会在您的计算 属性 中提供一个有限的集合) .