选择默认值时,选取器 .onChange 不会更改



我有和这里几乎相同的问题:SwiftUI Picker onChange或同等产品?,但是。on改变并不能完全解决我需要的问题。

我在那个链接中写了一个问题,但我被告知要问一个新问题(因为我在任何地方都找不到答案:(

我有这个枚举:

enum FruitTea: String, CustomStringConvertible, CaseIterable, Codable {
case peach = "Peach"
case passionFruit = "Passion Fruit"
case mango = "Mango"
case greenApple = "Green Apple"
var description: String { rawValue }

}

enum TypeOfTea: String, CustomStringConvertible, CaseIterable, Codable {
case specialTeaPresso = "Special Tea Presso"
case teaLatte = "Tea Latte"
case mousseSeries = "Mousse Series"
case milkTea = "Milk Tea"
case fruitTea = "Fruit Tea"
var description: String { rawValue }
}

这个拾取器:

@State private var type: TypeOfTea = .specialTeaPresso
@State private var fruit: FruitTea = .passionFruit
Picker("Fruit Tea", selection: $fruit) {
ForEach(FruitTea.allCases, id: .self) {
Text($0.rawValue).tag($0)
}
}
.onChange(of: fruit, perform: { _ in
type = .fruitTea
})

当我选择另一种已经选择的水果茶时,它是有效的。但如果我选择默认值,我的TypeOfTea不会改变。我知道为什么——因为没有变化。但对于我的应用程序来说,点击选取器意味着选择类型。你能帮忙吗?谢谢

如果有人对我的所有应用程序感兴趣:

我在github 上的应用程序

我不知道我是否完全理解你的问题,但正如你提到的那样,没有任何变化。并且你的TypeOfTea仍然是一个常数.fruitTea。但你可以尝试这样的东西来真正触发变化。

struct ContentView: View {
@State private var type: TypeOfTea = .specialTeaPresso
@State private var fruit: FruitTea = .passionFruit
var body: some View {
VStack {
Picker("Fruit Tea", selection: $fruit) {
ForEach(FruitTea.allCases, id: .self) {
Text($0.rawValue).tag($0)
}
}
Text(type.description)
}
.onChange(of: fruit, perform: { newFruit in
type = newFruit.typeOfTea
})
}
}
struct MyPreviewProvider_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

enum FruitTea: String, CustomStringConvertible, CaseIterable, Codable {
case peach = "Peach"
case passionFruit = "Passion Fruit"
case mango = "Mango"
case greenApple = "Green Apple"
var description: String { rawValue }
var typeOfTea: TypeOfTea {
switch self {
case .peach:
return .fruitTea
case .passionFruit:
return .teaLatte
case .mango:
return .mousseSeries
case .greenApple:
return .milkTea
}
}
}
enum TypeOfTea: String, CustomStringConvertible, CaseIterable, Codable {
case specialTeaPresso = "Special Tea Presso"
case teaLatte = "Tea Latte"
case mousseSeries = "Mousse Series"
case milkTea = "Milk Tea"
case fruitTea = "Fruit Tea"
var description: String { rawValue }
}

我找到了一个基于以下内容的解决方案:此处

我已经把那5个拾荒者减少到2个。第一个是选择茶的类型,第二个是使用返回一些view的函数显示正确的视图。Pickers必须包含在AnyView()中。

相关内容

  • 没有找到相关文章