SwiftUI Firebase。删除所有项目而不仅仅是一个
Posted
技术标签:
【中文标题】SwiftUI Firebase。删除所有项目而不仅仅是一个【英文标题】:SwiftUI Firebase. Deletes all Items not just one 【发布时间】:2020-05-02 18:36:53 【问题描述】:我想删除带有其 ID (let db = Firestore.firestore()
db.collection("Warenkorb").document(i.id).delete()
) 的项目。所以这是我的代码。可悲的是,当我删除一个项目时,集合中的所有项目也会被删除。为什么?有人可以帮我吗?
ForEach(cart.data) i in
HStack
Image("pic").resizable().scaledToFit().frame(width: 50, height: 75, alignment: .leading).padding().foregroundColor(.black)
Spacer()
VStack(alignment: .leading)
Text(i.name).font(.system(size: 25)).foregroundColor(.black)
HStack
Text(i.preis).font(.system(size: 20)).foregroundColor(.black)
Text(i.size).font(.system(size: 20)).foregroundColor(.black)
Spacer()
Text("\(i.quantity)").font(.system(size: 25)).foregroundColor(.black)
Spacer()
if self.remove
Button(action:
let db = Firestore.firestore()
db.collection("Warenkorb").document(i.id).delete()
self.show.toggle()
self.show.toggle()
)
Image(systemName: "minus.circle.fill")
.resizable()
.frame(width: 20, height: 20)
.foregroundColor(.red)
Spacer()
.background(Color("Color-1")).frame(width: 350, height: 100).cornerRadius(30).padding(.leading)
【问题讨论】:
【参考方案1】:您不应在 SwiftUI 视图中添加数据访问代码。相反,实现一个视图模型(以及可选的存储库)来管理您的数据。
我已经稍微修改了你的代码:
查看
struct ShoppingCartView: View
@ObservedObject var viewModel: ShoppingCartViewModel
var body: some View
List
ForEach(viewModel.lineItems) lineItem in
VStack(alignment: .leading)
Text(lineItem.title)
.font(.headline)
.onDelete indexSet in
self.viewModel.deleteLineItems(at: indexSet)
查看模型
import Foundation
import FirebaseFirestore
import FirebaseFirestoreSwift
import Combine
class ShoppingCartViewModel: ObservableObject
@Published var lineItems = [LineItem]()
private var db = Firestore.firestore()
private var listenerRegistration: ListenerRegistration?
private var cancellables = Set<AnyCancellable>()
init()
fetchData()
deinit
unregister()
func unregister()
if listenerRegistration != nil
listenerRegistration?.remove()
func fetchData()
unregister()
listenerRegistration = db.collection("shoppingCart").addSnapshotListener (querySnapshot, error) in
guard let documents = querySnapshot?.documents else
print("No documents")
return
self.lineItems = documents.compactMap queryDocumentSnapshot -> LineItem? in
let lineItem = try? queryDocumentSnapshot.data(as: LineItem.self)
return lineItem
func deleteLineItems(at offsets: IndexSet)
let itemsToDelete = offsets.lazy.map self.lineItems[$0]
itemsToDelete.forEach lineItem in
if let id = lineItem.id
db.collection("shoppingCart").document(id).delete()
【讨论】:
以上是关于SwiftUI Firebase。删除所有项目而不仅仅是一个的主要内容,如果未能解决你的问题,请参考以下文章
无法使用 SwiftUI 从 Firebase / Firestore 中删除文档
删除 SwiftUI 后 Firebase Firestore 不更新 UI