sheet 被关闭时选择器数据未更新

Picker data not updating when sheet is dismissed

我正在使用 coredata 来保存信息。此信息填充了一个选择器,但目前没有任何信息,因此选择器是空的。该数组是使用 FetchedRequest 设置的。

@FetchRequest(sortDescriptors: [])
var sources: FetchedResults<Source>
@State private var selectedSource = 0

这就是选择器的设置方式。

Picker(selection: $selectedSource, label: Text("Source")) {
    ForEach(0 ..< sources.count) {
        Text(sources[[=12=]].name!)
                            
    }
}

还有一个按钮显示另一个 sheet 并允许用户添加源。

Button(action: { addSource.toggle() }, label: {
    Text("Add Source")
})
    .sheet(isPresented: $addSource, content: {
        AddSource(showSheet: $addSource)
})

如果用户按下“添加源”,sheet 会显示一个文本字段和一个用于添加源的按钮。还有一个按钮可以关闭 sheet.

struct AddSource: View {
@Environment(\.managedObjectContext) var viewContext
@Binding var showSheet: Bool
@State var name = ""

var body: some View {
    NavigationView {
        Form {
            Section(header: Text("Source")) {
                TextField("Source Name", text: $name)
                Button("Add Source") {
                    let source = Source(context: viewContext)
                    source.name = name
                    
                    do {
                        try viewContext.save()
                        
                        name = ""
                    } catch {
                        let error = error as NSError
                        fatalError("Unable to save context: \(error)")
                    }
                }
            }
            
        }
        .navigationBarTitle("Add Source")
        .navigationBarItems(trailing: Button(action:{
            self.showSheet = false
        }) {
            Text("Done").bold()
                .accessibilityLabel("Add your source.")
        })
    }
}

}

sheet 关闭后,它会返回到第一个视图。第一个视图中的选取器未使用新添加的源进行更新。你必须关闭它并重新打开。用户添加源后如何更新选择器?谢谢!

问题出在您使用的 ForEach 签名上。它仅适用于常量数据。如果你想使用变化的数据,你必须使用类似的东西:

ForEach(sources, id: \Source.name.hashValue) {
    Text(verbatim: [=10=].name!)
}

请注意,对于两个同名的实体对象,hashValue 将不是唯一的。这只是一个例子