[英]SwiftUI Setting Initial Picker Value From CoreData
I am pulling my hair out trying to figure out how to get my picker to show the already stored CoreData value.我正在努力弄清楚如何让我的选择器显示已经存储的 CoreData 值。 I want it to show on the right side of the picker as if the user just selected it.
我希望它显示在选择器的右侧,就像用户刚刚选择它一样。 I have tried adding
self.updatedItemAttribute = self.editItem.attribute ?? ""
我试过添加
self.updatedItemAttribute = self.editItem.attribute ?? ""
self.updatedItemAttribute = self.editItem.attribute ?? ""
prior to the picker to set the initial value but that does not build. self.updatedItemAttribute = self.editItem.attribute ?? ""
在选择器之前设置初始值但不会构建。 I also tried defining it in @State
(eg @State var updatedItemAttribute: String = self.editItem.attribute
) but that does not build either.我也尝试在
@State
定义它(例如@State var updatedItemAttribute: String = self.editItem.attribute
),但这也没有建立。 If I add a TextField
prior to the picker it will set the value, but I do not want to have a TextField
with the value just to get it to set.如果我在选择器之前添加一个
TextField
,它将设置该值,但我不想让一个带有该值的TextField
只是为了设置它。 Any ideas on how I get updatedItemAttribute
set to editItem.attribute
just prior to the picker?关于如何在选择器之前将
updatedItemAttribute
设置为editItem.attribute
任何想法? Thanks.谢谢。
import CoreData
import SwiftUI
struct EditItemView: View {
@Environment(\.managedObjectContext) var moc
@Environment(\.presentationMode) var presentationMode
@ObservedObject var editItem: Item
@State var updatedItemName: String = ""
@State var updatedItemAttribute: String = ""
let attributes = ["Red", "Purple", "Yellow", "Gold"]
var body: some View {
NavigationView {
Form {
Section {
TextField("Name of item", text: $updatedItemName)
.onAppear {
self.updatedItemName = self.editItem.name ?? ""
}
Picker("Test attribute", selection: self.$updatedItemAttribute) {
ForEach(attributes, id: \.self) {
Text($0)
.onAppear {
self.updatedItemAttribute = self.editItem.attribute ?? ""
}
}
}
}
...
You have to this in init as shown below您必须在 init 中执行此操作,如下所示
struct EditItemView: View {
@Environment(\.managedObjectContext) var moc
@Environment(\.presentationMode) var presentationMode
@ObservedObject var editItem: Item
@State private var updatedItemName: String
@State private var updatedItemAttribute: String
init(editItem item: Item) { // << updated here
self.editItem = item
self._updatedItemName = State<String>(initialValue: item.name ?? "")
self._updatedItemAttribute = State<String>(initialValue: item.attribute ?? "")
}
let attributes = ["Red", "Purple", "Yellow", "Gold"]
var body: some View {
NavigationView {
Form {
Section {
TextField("Name of item", text: $updatedItemName)
Picker("Test attribute", selection: self.$updatedItemAttribute) {
ForEach(attributes, id: \.self) {
Text($0)
}
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.