SwiftUI 选择器选择绑定未更新

2024-03-24

我正在尝试让选择器列出所有类型,称为Course然后让用户在添加新课程时选择适当的课程Assignment到托管对象上下文。选择器选择绑定(courseIndex) 当用户点击选取器视图中的行时不会更新。我不完全确定如何解决这个问题,也不知道是什么原因造成的。任何帮助表示赞赏!

这是受影响的代码:

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:") })
                }
            }
        }
[...]

使用可选绑定值时,显式提供标签值的可选包装非常重要,因为 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))
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SwiftUI 选择器选择绑定未更新 的相关文章

随机推荐