r/SwiftUI •

Weird visual on searchable, need help.

[deleted] — view deleted post

0 Upvotes

7 comments sorted by

4

u/ThanhDongNguyen 10d ago

From what you describe (fine when there is a space in the field, broken only when search goes back to empty), I think your view switches between two different views based on searchText.isEmpty. Something like if searchText.isEmpty { fullList } else { filteredList }.

When you cancel, the search bar collapses with animation and at the same time SwiftUI throws away one List and builds the other. The new list gets laid out with the old top inset, so you see that empty block pushing everything down.

Usually the fix is to keep one List and only change the data:

var results: [Item] {
    searchText.isEmpty ? items : items.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
}

List(results) { item in
    Row(item: item)
}
.searchable(text: $searchText)

Also check that .searchable is on the view inside the NavigationStack, not on the NavigationStack itself, and that the List is not wrapped in an extra VStack or ScrollView. If you need different UI while searching, read @Environment(\.isSearching) in a child view instead of checking the text.

If it still happens, post the code of the view with .searchable, easier to see what is going on.

1

u/dahiya_xa 10d ago

yeah if you're doing if searchText.isEmpty { list } else { results } the view gets swapped out while the search bar animates away and you get that leftover gap. try keeping one List and just filtering the data you feed it, or show the results/empty state in an .overlay instead of swapping views. the space-in-the-field thing kind of confirms it's the view switch