【问题标题】:The Picker does not select the value from CoreData (SwiftUI)Picker 不会从 CoreData (SwiftUI) 中选择值
【发布时间】:2020-05-05 15:00:03
【问题描述】:

我正在尝试从 CoreData 存储中选择实体,但 Picker 不起作用 - 它不显示所选实体。

我的代码:

import SwiftUI

struct SampleView: View {
    @FetchRequest(entity: Aircraft.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Aircraft.model, ascending: true)]) var aircrafts: FetchedResults<Aircraft>
    @State private var selection: UUID? = UUID()

    var body: some View {
        NavigationView {
            VStack {
                Form {
                    Picker(selection: $selection, label: Text("Picker")) {
                        ForEach(aircrafts, id: \.self) { aircraft in
                            Text(aircraft.model ?? "Unknown")
                        }
                    }
                }
            }
        }
    }
}

结果:

【问题讨论】:

    标签: ios swift xcode core-data swiftui


    【解决方案1】:

    选择的类型应该与选择的内容或标签相同。在你的情况下,我认为它可以如下

    @State private var selection: Aircraft? = nil
    

    尝试如下.tag

    ForEach(aircrafts, id: \.self) { aircraft in
        Text(aircraft.model ?? "Unknown").tag(aircraft as Aircraft?)
    }
    

    更新(可选特定):根据@user3687284的评论

    【讨论】:

    • 感谢您的回答,阿斯佩里!不幸的是,选择器仍然无法正常工作。
    • 请尝试使用标签更新...它适用于我的 Xcode 11.2 / iOS 13.2(实际上初始变体也适用)
    • 这很奇怪,但仍然没有结果......选择器仍然是空的。 Xcode 11.3.1,iOS 13.3。
    • 试试 .tag(aircraft as Aircraft?)
    • ... 在 Asperi 的解决方案中。这就是在类似情况下对我有用的方式。我从this question的答案中得到了解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    相关资源
    最近更新 更多