gpt4 book ai didi

ios - 选择器不会从CoreData(SwiftUI)中选择值

转载 作者:行者123 更新时间:2023-12-01 17:28:25 26 4
gpt4 key购买 nike

我正在尝试从CoreData存储中选择实体,但是选择器无法正常工作-它不会显示所选的实体。

我的代码:

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")
}
}
}
}
}
}
}

结果:
enter image description here

最佳答案

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

@State private var selection: Aircraft? = nil

尝试使用 .tag如下
ForEach(aircrafts, id: \.self) { aircraft in
Text(aircraft.model ?? "Unknown").tag(aircraft as Aircraft?)
}

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

关于ios - 选择器不会从CoreData(SwiftUI)中选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59809097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com