我正在尝试使用ActionSheet来操纵List
的项目。如何使用ActionSheet调用属于数据模型的函数(在本示例中为deleteItem
),并操纵所选项目,类似于.onDelete
那样?
我的视图使用以下代码显示来自模型的项目:
struct ItemManager: View {
@ObservedObject var model: ItemModel
var body: some View {
List {
ForEach(model.items) { item in
ItemCell(item: item)
}
.onDelete { self.model.deleteItem(at: $0) }
}
}
}
struct ItemCell: View {
var item: Item
@State private var isActionSheetVisible = false
private var actionSheet: ActionSheet {
let button1 = ActionSheet.Button.default(Text("Delete")){
self.isActionSheetVisible = false
}
let button2 = ActionSheet.Button.cancel(){
self.isActionSheetVisible = false
}
let buttons = [button1, button2]
return ActionSheet(title: Text("Actions"), buttons: buttons)
}
var body: some View {
VStack(alignment: .leading) {
Button(action: {
self.isActionSheetVisible = true
}) {
Text(item.title).font(.headline)
}.actionSheet(isPresented: self.$isActionSheetVisible) {
self.actionSheet
}
}
}
}
我的模型具有一些简单的属性和一个从集合中删除项目的函数:
struct Item: Identifiable, Equatable {
let title: String
var id: String {
title
}
}
class ItemModel: ObservableObject {
@Published var items: [Item] = [Item(title: "temp.1"), Item(title: "temp.2")]
public func deleteItem(at indices: IndexSet) {
indices.forEach { items.remove(at: $0) }
}
}
extension Item {
static let previewItem = Item(title: "temp.3")
}
更新:在Equatable
声明中添加了Item
以便遵守。
答案 0 :(得分:1)
您可以尝试将ItemModel
传递给ForEach()
,如下所示:
ForEach(model.items) { item in
ItemCell(item: item, model: self.model)
}
然后在您的ItemCell
中,您可以:
struct ItemCell: View {
var item: Item
var model: ItemModel // Add the model variable
@State private var isActionSheetVisible = false
private var actionSheet: ActionSheet {
let button1 = ActionSheet.Button.default(Text("Delete")) {
// Get the index
if let index = self.model.items.firstIndex(of: self.item) {
// Delete the item based on the index
self.model.items.remove(at: index)
// Dismiss the ActionSheet
self.isActionSheetVisible = false
} else {
print("Could not find item!")
print(self.item)
}
}
}
}