Duck
Duck

Reputation: 36003

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

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.

Upvotes: 0

Views: 3364

Answers (2)

Duck
Duck

Reputation: 36003

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!)
}

Upvotes: -1

Asperi
Asperi

Reputation: 258267

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)

Upvotes: 3

Related Questions