【问题标题】:Picker inside of form no longer selecting表单内的选择器不再选择
【发布时间】:2021-03-14 21:48:25
【问题描述】:

我在表单中有一个选择器。以前它可以正确选择项目,但是,在更改代码以修复另一个问题后,它不再起作用。选择器正在使用的项目是从 coredata 中获取的。我该如何解决这个问题?

@FetchRequest(sortDescriptors: [])
var sources: FetchedResults<Source>
@State private var selectedSource = 0

这是我用于选择器的代码。

Picker(selection: $selectedSource, label: Text("Source")) {
    ForEach(sources, id: \.self) { source in
        Text(source.name!)
            .tag(source)
    }
}

这里是该问题视频的链接。 Video

【问题讨论】:

    标签: swift swiftui picker


    【解决方案1】:

    您在Picker(selection:) 中提供的类型(当前为Int -- selectedSource)需要与您在tag() 中提供的类型相同,当前为Source

    例如,您可以使用Source 的ID(我假设它有一个)作为selectedSource,然后在tag() 中使用相同的ID

    【讨论】:

    • 谢谢!我使用@State private var selectedSource: Source?Text(source.name!).tag(source as Source?) 让它工作。
    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2015-07-06
    • 2021-11-25
    • 2013-11-27
    相关资源
    最近更新 更多