如何让搜索结果滚动到tableview的顶部?

How to get search results to scroll the top of the tableview?

之前我的搜索结果被截断了,我必须向上滚动才能看到完整的结果

当我开始在搜索栏中输入内容时,我希望结果跳转到表格视图的顶部。

我用来让它工作的代码,第一次工作但后来我在 AppDelegate 中收到 SIGABRT 错误当我输入新搜索时。

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

▲ 有用于使搜索结果显示在表格视图顶部的代码,但只要我键入新内容,模拟器就会关闭我。每次我输入新搜索时,我都试图让讨厌的结果出现在顶部

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

我已经尝试使用堆栈中的以下内容来提供帮助,但没有成功

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?

首先,在滚动到 (0,0) 行之前,您需要检查它是否存在:

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

秒,reloadData() 可能不会立即发生 - 它可能会在下一个 运行 循环中发生。所以你应该把卷轴包裹在一个调度块中:

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