SwiftUI - How to get the selected index of a list when you have a search?

2.8k views Asked by At

I have a List in SwiftUI but the problem is that I have a search box.

My code is like this:

  List {
    
    ForEach(items.filter {
      self.searchText.isEmpty ? true : $0.term!.contains(self.searchText)
    }, id: \.self) { item in
      Text(item.term!)
    }
    .onDelete(perform: deleteItems)
    .onTapGesture(count: 1, perform: {
      selectedItem = index // 1
    })
  }

I need to get the index of the selected item from that list, when the item is selected.

See the line //1? How do I get the index there.

2

There are 2 answers

0
Duck On BEST ANSWER

The solution by Aperi is not good, because the only elements tappable will be the texts, not the cells.

The correct answer is to wrap the Text element as a view of a Button, like shown on this video...

Button(action: {
  // do something()            
}) {
   Text(item.term!)
}
2
Asperi On

If I correctly understood your goal (and item is Equatable), then in can be done with

}, id: \.self) { item in
  Text(item.term!)
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .contentShape(Rectangle())
    .onTapGesture {
        // above makes complete row tappable inside dynamic content
        // so you have access here to item to find index
        selectedItem = items.firstIndex { $0 == item }
    }
}
.onDelete(perform: deleteItems)