Why swipeActions modifier does not work with List container directly? #SwiftUI

Viewed 547

The newly introduced swipeActions modifier does not work directly with the List container that presents the rows of data arranged. However, it works perfectly fine in case I use a ForEach — A structure that computes views on demand from an underlying collection of identified data.

Below code doesn't work and show swipeActions

struct SwipeButtonDemoView: View {
  let listItems = WWDCViewModel().sessions
  var body: some View {
    NavigationView {
      VStack {
        Spacer()
        List(listItems) {  session in
            HStack {
              Image(systemName: "play")
              Text(session.title)
                .font(.callout)
            }
            .swipeActions(edge: .leading) {
              Button {
                print("Bookmark")
              } label: {
                Label("Bookmark", systemImage: "bookmark")
              }.tint(.indigo)
            }
          }
          .listRowSeparator(.hidden)
          }
      .listStyle(.inset)
      .navigationTitle("WWDC 21")
    }
  }
}

Below code works and shows swipeActions..

struct SwipeButtonDemoView: View {
  let listItems = WWDCViewModel().sessions
  var body: some View {
    NavigationView {
      VStack {
        Spacer()
        
        List {
          ForEach(listItems) { session in
            HStack {
              Image(systemName: "play")
              Text(session.title)
                .font(.callout)
            }
            .swipeActions(edge: .leading) {
              Button {
                print("Bookmark")
              } label: {
                Label("Bookmark", systemImage: "bookmark")
              }.tint(.indigo)
            }
          }
          .listRowSeparator(.hidden)
          }
        }
      .listStyle(.inset)
      .navigationTitle("WWDC 21")
    }
  }
}

Why it's not working with List directly? However, it works as expected with ForEach!!!

1 Answers

You are right that in Xcode 13 beta 1, swipeActions can't be applied to the internal block declaration of a List, so this version of your example wouldn't work:

List(listItems) { session in
  HStack {
    Image(systemName: "play")
    Text(session.title)
      .font(.callout)
  }
  .swipeActions(edge: .leading) {
    // etc
  }
}

It would appear that there'd be a valid use case for making swipe actions available for List declarations like this, so it's worth using the Feedback Assistant to make that suggestion to Apple.

Related