Ajvar1
Ajvar1

Reputation: 147

Is it possible to add swipe actions dynamically in SwiftUI?

The question is quite simple. I receive entities from API that contains property actions and I need to display them in a list with actions as swipe actions accordingly.

Problem is that I didn't find the way how to iterate actions in swipeActions modificator.

I tried something like this:

List {
    ForEach(entities) { entity in
        CustomCell(entity: entity)
            .swipeActions(edge: .trailing) {
                for action in entity.actions {
                    Button(action: {}) {
                        Label(action.title)
                    }
                }
            }
    }
}

and it does not work.

Is it even possible to solve?

Upvotes: 1

Views: 364

Answers (1)

Asperi
Asperi

Reputation: 257493

Assuming action type is Identifiable (if not then confirm it), it can be done with ForEach, because swipeActions expects views, so it can be like

List {
    ForEach(entities) { entity in
        CustomCell(entity: entity)
            .swipeActions(edge: .trailing) {
                ForEach(entity.actions) { action in    // << here !!
                    Button(action: {}) {
                        Label(action.title)
                    }
                }
            }
    }
}

Upvotes: 1

Related Questions