在核心数据SwiftUI中添加和删除

时间:2020-05-18 16:11:00

标签: swift core-data swiftui

我试图显示一颗心,当我点击它时,会向我喜欢的视图中添加一个项目,像这样

struct ContentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Favorites.entity(), sortDescriptors: [NSSortDescriptor(key: "title", ascending: true)]) var favoritesItems: FetchedResults<Favorites>

let title1 = "Random title1"
let title2 = "Random title2"
@State private var saved1 = false
@State private var saved2 = false

    var body: some View {
        HStack {
            Text(title1)
            Image(systemName: saved ? "heart.fill" : "heart")
                .onTapGesture {
                    self.saved1.toggle()
                    self.addItem(item: title1)
                    // Deleting?
                }

            Text(title2)
            Image(systemName: saved ? "heart.fill" : "heart")
                .onTapGesture {
                    self.saved2.toggle()
                    self.addItem(item: title2)
                    // Deleting?
                }
        }
    }
    func addItem(item: String) {
        let newItem = Favorites(context: managedObjectContext)
        newItem.title = item
    }
    // Function to delete that item??
}

我如何创建一个甚至删除该项目的功能

0 个答案:

没有答案