2

我正在尝试使用 ActionSheet 来操作List. 如何调用作为deleteItem数据模型一部分的函数(在此示例中),使用 ActionSheet 并操纵所选项目,类似于什么.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")
}

更新EquatableItem声明中添加以符合要求。

4

1 回答 1

1

您可以尝试将其传递ItemModelForEach()类似的东西:

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)
            }
        }
    }
}
于 2019-12-10T03:04:56.080 回答