由枚举驱动的 SwiftUI 选择器:值未更新 [英] SwiftUI picker driven by an enum: value not updated

查看:22
本文介绍了由枚举驱动的 SwiftUI 选择器:值未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Apple 关于

但是,如果我为每个视图传递一个 tag,它就可以工作.

这里发生了什么?苹果文档有错吗?selectedFlavor 变量需要一个 Flavor 类型的值,但是选择器中使用的 id 实际上是一个 String.

谢谢.

解决方案

要使 Picker 正常工作,需要识别其元素.

请注意,selectedFlavor 变量的类型为 Flavor.这意味着 Picker 中的选项应该被标识为 Flavors(而不是 Strings).

但是,在您的代码中,您的 id 属于 String 类型:

var id: String { self.rawValue }


您可以:

  • 提供一个标签(Flavor类型):

Text(flavor.rawValue.capitalized).tag(风味)

  • 通过提供类型为 Flavor 的自定义 id 使 Flavor 符合 Identifiable:

var id: Flavor { self }

  • ForEach中明确指定id参数(Flavor类型):

ForEach(Flavor.allCases, id: \.self) { ... }

  • selectedFlavor 更改为字符串:

@State private var selectedFlavor = Flavor.chocolate.rawValue

According to Apple's documentation regarding Picker in SwiftUI using an Enum, if the enum conforms to the Identifiable protocol in addition to CaseIterable, a picker iterating over all cases should update the bound variable natively.

I tested it, and it does not work as expected.

enum Flavor: String, CaseIterable, Identifiable {
    case chocolate
    case vanilla
    case strawberry

    var id: String { self.rawValue }
}

struct EnumView: View {
    @State private var selectedFlavor = Flavor.chocolate
    var body: some View {
        VStack {
            Picker("Flavor", selection: $selectedFlavor) {
                ForEach(Flavor.allCases) { flavor in
                    Text(flavor.rawValue.capitalized)//.tag(flavor)
                }
            }
        
            Text("Selected flavor: \(selectedFlavor.rawValue)")
        }
    }
}

However, if I pass a tag for each view, it works.

What's happening here? Is the Apple documentation wrong? The selectedFlavor variable expects a value of type Flavor, but the id used in the picker is actually a String.

Thanks.

解决方案

For a Picker to work properly, its elements need to be identified.

Note that the selectedFlavor variable is of type Flavor. Which means the options in the Picker should be identified as Flavors (not Strings).

However, in your code your id is of type String:

var id: String { self.rawValue }


You can either:

  • provide a tag (of type Flavor):

Text(flavor.rawValue.capitalized)
    .tag(flavor)

  • conform Flavor to Identifiable by providing a custom id of type Flavor:

var id: Flavor { self }

  • specify the id parameter (of type Flavor) explicitly in the ForEach:

ForEach(Flavor.allCases, id: \.self) { ... }

  • change the selectedFlavor to be a String:

@State private var selectedFlavor = Flavor.chocolate.rawValue

这篇关于由枚举驱动的 SwiftUI 选择器:值未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆