0

Previously my search results were showed clipped and I had to scroll up to down to see the full results

Where I want the Results to jump to the top of the tableview as soon as I start typing something in my search bar.

the code im using to make it work, works the first time but then I get the SIGABRT error in the AppDelegate as soon as I type in a new search.

productListTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)

▲ there's the code that used to make the search results show at the top of the tableview but as soon as I type something new the simulator closes out on me. im trying to get hate results presented to the top everytime I punch in a new search

extension ProductListController : UISearchBarDelegate, UISearchDisplayDelegate {

        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
            productInventory = self.productSetup.filter({ (products) -> Bool in
                return products.name.range(of: searchText, options: [ .caseInsensitive, .diacriticInsensitive ]) != nil 
                })

        self.productListTableView.reloadData()

      // Code that scrolls search results to the top of the tableview ▼

        self.productListTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
    }


    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchActive = true;
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchActive = false;
        self.searchBar.endEditing(true)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchActive = false;
        self.searchBar.endEditing(true)
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchActive = false;
        self.searchBar.endEditing(true)
    }
}

I've tried using the following from stack to help already but no luck

UITableView - scroll to the top

How to get a UITableview to go to the top of page on reload?

How to refresh my UITableView with UISearchBar after click of cancel button of UISearchBar?

Evelyn
  • 186
  • 1
  • 4
  • 25

1 Answers1

1

First, before scrolling to row (0,0) you need to check that it exists:

if !self.productInventory.isEmpty {
    self.productListTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
}

second, reloadData() may not happen immediately - it may happen on the next run loop. So you should wrap the scroll in a dispatch block:

DispathQueue.main.async {
    if !self.productInventory.isEmpty {
        self.productListTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
     }
}
Yonat
  • 4,382
  • 2
  • 28
  • 37