ghostcrafter551
ghostcrafter551

Reputation: 1

SwiftUI calling searchable on a list combines all elements into one row

In the example below the list items get squished all into one cell of the list, but only when calling .searchable() on it. When I call .searchable() on the text everything displays normally. I can't use it on the text though, because it has problems with the search filter.

import SwiftUI

struct FoodItem: Identifiable {
    let id = UUID()
    let name: String
}

struct ListView: View {
    
    let listContent: [FoodItem] = [FoodItem(name: "Food 1"), FoodItem(name: "Food 2")]

    @State public var searchQuery: String = ""
    
    var body: some View {
        NavigationView {
            Form {
                Section {
                    List(filteredContent) { item in
                        Text(item.name)
                    }
                    .searchable(text: $searchQuery)
                }
            } .navigationTitle("Food List")
        }
    }
    
    var filteredContent: [FoodItem] {
        if searchQuery.isEmpty {
            return listContent
        } else {
            return listContent.filter { $0.name.localizedCaseInsensitiveContains(searchQuery)}
        }
    }
}

struct ListView_Previews: PreviewProvider {
    static var previews: some View {
        ListView()
    }
}

I spent probably two hours searching online and trying to fix it and didn't find any results. Also, I'm new to SwiftUI.

Thanks!!

Upvotes: 0

Views: 726

Answers (1)

ghostcrafter551
ghostcrafter551

Reputation: 1

Paulw11's comment helped me a lot. I found out, that it wasn't the problem, that I called .searchable() on the text, but that I had an error in my filteredContent.

The problem was fixed with this:

var filteredContent: [FoodItem] {
    if searchQuery.isEmpty {
        return listContent
    } else if (listContent.filter {$0.name.localizedCaseInsensitiveContains(searchQuery)}.isEmpty) {
        return listContent
    } else {
        return listContent.filter { $0.name.localizedCaseInsensitiveContains(searchQuery)}
    }
}

Upvotes: 0

Related Questions