【问题标题】:CoreData List Items, Edit ViewCoreData 列表项,编辑视图
【发布时间】:2021-05-22 13:28:58
【问题描述】:

在将 CoreData 保存到数据库后,需要帮助将其传递到另一个视图。我有一个单独的“添加项目”视图,列表视图显示排序的项目。使用 NavigationView 我可以点击查看每个条目,但我想 .onTapGesture 用可编辑的列表项覆盖一个新视图。 正在努力解决这个问题。

现在这可以查看每个列表项的更多详细信息,但我宁愿让它使用 .onTapGesture 打开一个新视图,但不知道如何将点击的数据库项传递给新视图并设置编辑它。

NavigationView{
    List {
          ForEach(newItem) { newItems in
               NavigationLink(destination: TapItemView(database: newItems)) {
                   DatabaseRowView(database: newItems)}
          }
     }.onDelete(perform: deleteItem)
}

?

【问题讨论】:

  • CoreData 和所有 ObservableObjects 应该被包装在 ObservedObject 包装器中,当您想查看更改时

标签: ios core-data swiftui


【解决方案1】:

观察:在您的代码示例中——“ForEach(newItem) { newItems in”应该是“ForEach(newItems) { newItem in”。换句话说,集合放在 ForEach 括号中,并且单个项目在“in”之前。有了这个,我开始为这个例子(Xcode 版本 13.1)使用 Xcode 生成的带有 Core Data 的项目。修改包含在下面的代码中。

@State var showEditView = false
@State var tappedItem: Item = Item()
var body: some View {
    NavigationView {
        List {
            ForEach(items) { item in
                Text(item.timestamp, formatter: itemFormatter)
                    .onTapGesture {
                        tappedItem = item
                        showEditView = true
                    }
            }
            .sheet(isPresented: $showEditView) {
                EditView(item: $tappedItem)
            }
        }
    }
}

这是被点击项目的可能接收视图:

struct EditView: View {
@Binding var item: Item
var body: some View {
    NavigationView {
        Form {
            Section(header: Text("Date")) {
                DatePicker("Date Selection",
                           selection: $item.timestamp,
                           displayedComponents: [.date]
                )
                .datePickerStyle(.compact)
                .labelsHidden()
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多