SwiftUI 选择器选择绑定未更新

Kev*_*ats 5 core-data ios swift swiftui

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. The picker selection binding (courseIndex) isn't updated when the user taps a row in the picker view. 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:") })
                }
            }
        }
[...]
Run Code Online (Sandbox Code Playgroud)

mat*_*zav 5

使用可选绑定值时,重要的是您明确地为标签值提供可选包装,因为 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))
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这有效,谢谢!事实上,简单的“.tag(option)”不起作用似乎很荒谬,但 SwiftUI 以神秘的方式工作。 (4认同)
  • 精彩的答案。太感谢了 (3认同)
  • 这就是我需要阅读的内容!谢谢你!! (3认同)

Asp*_*eri 2

我无法使您的快照可编译,因此只需更改,这里...我假设由于您的选择是索引,因此您必须使用范围ForEach,例如

ForEach(0 ..< self.courses.count) { i in
    Text("\(self.courses[i].name ?? "")").foregroundColor(self.courses[i].color).tag(i)
}
Run Code Online (Sandbox Code Playgroud)

附言。不确定tag用法,可能不需要。