[英]SwiftUI Picker selection binding not updating
I am trying to have a picker list all of a type, called Course
and then let the user select the appropriate course when adding a new Assignment
to the managed object context.我正在尝试使用一个名为Course
的选择器列表,然后让用户在向托管对象上下文添加新Assignment
时选择适当的课程。 The picker selection binding ( courseIndex
) isn't updated when the user taps a row in the picker view.当用户点击选取器视图中的一行时,选取器选择绑定 ( courseIndex
) 不会更新。 I'm not entirely sure how to fix the issue, nor do I know what is causing it.我不完全确定如何解决这个问题,也不知道是什么原因造成的。 Any help is appreciated!任何帮助表示赞赏!
Here is the affected code:这是受影响的代码:
struct NewAssignmentView: View {
@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) var context
@FetchRequest(entity: Course.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Course.name, ascending: true)]) var courses: FetchedResults<Course>
@State var name = ""
@State var hasDueDate = false
@State var dueDate = Date()
@State var courseIndex = 0
var body: some View {
NavigationView {
Form {
TextField("Assignment Name", text: $name)
Section {
Picker(selection: $courseIndex, label:
HStack {
Text("Course: ")
Spacer()
Text(self.courses[self.courseIndex].name ?? "").foregroundColor(self.courses[self.courseIndex].color).bold()
})
{
ForEach(self.courses, id: \.self) { course in
Text("\(course.name ?? "")").foregroundColor(course.color).tag(course)
}
}
}
Section {
Toggle(isOn: $hasDueDate.animation()) {
Text("Due Date")
}
if hasDueDate {
DatePicker(selection: $dueDate, displayedComponents: .date, label: { Text("Set Date:") })
}
}
}
[...]
When using optional binding values it's important that you explicitly provide the optional wrapping for the tag values because Swift doesn't automatically unwrap it for you and fails to equate a non-optional value with an optional one.使用可选绑定值时,重要的是您明确地为标签值提供可选包装,因为 Swift 不会自动为您解开它,并且无法将非可选值等同于可选值。
@Binding var optional: String?
Picker("Field", selection: $optional) {
// None option.
Text("None").tag(String?.none)
// Other fields.
ForEach(options) { option in
Text(option).tag(String?.some(option))
}
}
I cannot make your snapshot compilable, so just changed, here... I assume that as your selection is index, you have to use ranged ForEach
instead, like我不能让你的快照可编译,所以只是改变了,在这里......我假设你的选择是索引,你必须使用 ranged ForEach
,比如
ForEach(0 ..< self.courses.count) { i in
Text("\(self.courses[i].name ?? "")").foregroundColor(self.courses[i].color).tag(i)
}
PS.附注。 not sure about tag
usage, probably it might be not needed.不确定tag
使用,可能不需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.