我试图在一个单独的详细信息视图中编辑一个项目。我想在从列表中选择项目后,在文本字段中填充项目详细信息。
List {
ForEach(vm.savedEntites) { entity in
Text(entity.name ?? "No Name")
HStack {
Button(action: {vm.deleteMemory(entity: entity)}) {
Label("Delete",systemImage: "trash")
}
Button(action: {
vm.selectedEntity = entity
showingDetailScreen.toggle()}) {
Label("Details", systemImage: "pencil")
}
}
}// list ends here
.sheet(isPresented: $showingDetailScreen) {
DetailItemView(isVisible: self.$showingDetailScreen, entity: vm.selectedEntity!, text: vm.selectedEntity!)
}// sheet ends here
}
详细项视图表。这就是我得到这个错误旁边的TextField
无法将类型"Binding<String?>"的值转换为期望的参数类型"绑定">
struct DetailItemView: View {
@Environment(.presentationMode) var presentationMode
@Binding var isVisible: Bool
var entity: MemoryEntity
@ObservedObject var text: MemoryEntity
var body: some View {
Text(entity.name ?? "No Name")
TextField(text.name ?? "No Name", text: $text.name)
....}
这是项
的CoreData模型类class CoreDataViewModel: ObservableObject {
let container: NSPersistentContainer
@Published var savedEntites: [MemoryEntity] = []
@Published var selectedEntity: MemoryEntity?
init() {
container = NSPersistentContainer(name: "MemoryContainer")
container.loadPersistentStores { (description, error) in
if let error = error {
print("Error loading CoreData. (error)")
}
}
FetchMemories()
}
因为所有核心数据字段都是可选的,所以必须将其封装到Binding
中。当你使用核心数据,可能面临很多可选的,你可以创建一个扩展:
extension Binding {
func toUnwrapped<T>(defaultValue: T) -> Binding<T> where Value == Optional<T> {
Binding<T>(get: { self.wrappedValue ?? defaultValue }, set: { self.wrappedValue = $0 })
}
}
像这样使用:
TextField("title", text: $text.name.toUnwrapped(defaultValue: ""))