我在SwiftUI中做了一个非常简单的应用程序。使用核心数据的TODO列表。我可以添加做项目,并存储他们的核心数据。项显示在内容视图中的列表中。点击每个项目,我们就会看到EditItemView。我设法为每个条目显示了正确的数据。从这个视图中,我想删除我在EditItemView中看到的这个特定条目。它的工作方式应该类似于在iOS上删除提醒应用程序中的列表。DELETE按钮应该删除这个特定的条目,然后带我们回到ContentView。但是.。什么都没发生。我没有收到任何错误,但什么也没有删除。
核心数据在核心数据中,我有一个实体:ToDoItem(Module:Current ProductModule,Codegen:class Definition)属性:createdAt:Date(今天的默认值)标题:string(默认值=空字符串)
下面是我到目前为止掌握的代码:
内容视图
import SwiftUI
struct ContentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
entity: ToDoItem.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \ToDoItem.createdAt, ascending: true),
NSSortDescriptor(keyPath: \ToDoItem.title, ascending: true)
]
) var toDoItems: FetchedResults<ToDoItem>
@State private var show_modal: Bool = false
var body: some View {
NavigationView {
List{
ForEach(toDoItems, id: \.self) {todoItem in
NavigationLink(destination: EditItemView(createdAt: todoItem.createdAt!, title: todoItem.title!)) {
ToDoItemView(title: todoItem.title!, createdAt: todoItem.createdAt!)
}
}
}
.navigationBarTitle(Text("My List"))
.navigationBarItems(trailing:
Button(action: {
self.show_modal = true
}) {
Text("Add")
}.sheet(isPresented: self.$show_modal) {
AddItemView().environment(\.managedObjectContext, self.managedObjectContext)
}
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
return ContentView().environment(\.managedObjectContext, context)
}
}
编辑视图
import SwiftUI
struct AddItemView: View {
@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) var managedObjectContext
static let dateFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
@State private var createdAt : Date = Date()
@State private var showDatePicker = false
@State private var title = ""
var body: some View {
NavigationView {
ScrollView {
HStack {
Button(action: {
self.showDatePicker.toggle()
}) {
Text("\(createdAt, formatter: Self.dateFormat)")
}
Spacer()
}
if self.showDatePicker {
DatePicker(
selection: $createdAt,
displayedComponents: .date,
label: { Text("Date") }
)
.labelsHidden()
}
TextField("to do item", text: $title)
.font(Font.system(size: 30))
Spacer()
}
.padding()
.navigationBarTitle(Text("Add transaction"))
.navigationBarItems(
leading:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Cancel")
},
trailing:
Button(action: {
let toDoItem = ToDoItem(context: self.managedObjectContext)
toDoItem.createdAt = self.createdAt
toDoItem.title = self.title
do {
try self.managedObjectContext.save()
}catch{
print(error)
}
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Done")
}
)
}
}
}
struct AddItemView_Previews: PreviewProvider {
static var previews: some View {
AddItemView()
}
}
EditItemView
import SwiftUI
struct EditItemView: View {
@Environment(\.managedObjectContext) var managedObjectContext
static let dateFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
var createdAt : Date
var title: String = ""
@State private var newCreatedAt : Date = Date()
@State private var showDatePicker = false
@State private var newTitle = ""
var body: some View {
ScrollView {
HStack {
Button(action: {
self.showDatePicker.toggle()
}) {
Text("\(createdAt, formatter: Self.dateFormat)")
}
Spacer()
}
if self.showDatePicker {
DatePicker(
selection: $newCreatedAt,
displayedComponents: .date,
label: { Text("Date") }
)
.labelsHidden()
}
TextField(title, text: $newTitle)
.font(Font.system(size: 30))
}
.padding()
.navigationBarTitle(Text("Edit transaction"))
.navigationBarItems(
trailing:
Button(action: {
print("Delete")
let deleteToDoItem = ToDoItem(context: self.managedObjectContext)
self.managedObjectContext.delete(deleteToDoItem)
do {
try self.managedObjectContext.save()
}catch{
print(error)
}
// let deleteToDoItem = self.toDoItems[indexSet.first!] // self.managedObjectContext.delete(deleteToDoItem) // // do { // try self.managedObjectContext.save() // }catch{ // print(error) // }
}) {
Text("Delete")
.foregroundColor(.red)
}
)
}
}
struct EditItemView_Previews: PreviewProvider { static var previews: some View { EditItemView( createdAt: Date(), title: "to do item" ) } } 托依坦视图
import SwiftUI
struct ToDoItemView: View {
static let dateFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
var title:String = ""
var createdAt:Date = Date()
var body: some View {
HStack{
VStack(alignment: .leading){
Text(title)
.font(.headline)
Text("\(createdAt, formatter: Self.dateFormat)")
.font(.caption)
}
}
}
}
struct ToDoItemView_Previews: PreviewProvider {
static var previews: some View {
ToDoItemView(title: "To do item", createdAt: Date())
}
}
P.S.我知道我可以在列表视图中添加.onDelete。但我想故意让用户更难删除一个项目。这就是为什么我想将“删除”按钮移动到“详细信息”视图。
只需向EditItemView添加一个属性
var todoItem: ToDoItem 还可以添加环境对象以取消视图。
@Environment(.presentationMode) var presentationMode: Binding 编辑删除按钮操作
self.managedObjectContext.delete(self.todoItem) do { try self.managedObjectContext.save() self.presentationMode.wrappedValue.dismiss() }catch{ print(error) } 最后一个关于ContentView init的文章EditView init
ForEach(toDoItems, id: .self) { todoItem in EditItemView(todoItem: todoItem)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。