【问题标题】:How to get search results to scroll the top of the tableview?如何获取搜索结果以滚动表格视图的顶部?
【发布时间】:2020-02-16 15:16:57
【问题描述】:

以前我的搜索结果显示为剪裁,我必须向上滚动才能看到完整的结果

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

我用来使其工作的代码第一次工作,但我一输入新搜索,就会在 AppDelegate 中收到 SIGABRT 错误。

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

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

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?

【问题讨论】:

    标签: ios swift search scroll tableview


    【解决方案1】:

    首先,在滚动到第 (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)
         }
    }
    

    【讨论】:

    • 第二个选项我不知道该放在哪里,但第一个选项效果很好
    猜你喜欢
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    相关资源
    最近更新 更多