【问题标题】:Scroll tableview and click in searcher crashes app滚动表视图并单击搜索器崩溃应用程序
【发布时间】:2017-01-03 13:46:39
【问题描述】:

我有一个tableView,它显示了员工列表。现在,当我滚动tableView 时,如果滚动还没有停止,如果我单击搜索栏,应用程序就会崩溃。索引超出范围。我不知道为什么会这样。请,如果有人可以提供帮助。非常感谢您。

注意: Tableview 是用 listArray 加载的。当用户搜索时,我是 searchArray 来显示搜索结果。

代码:

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        self.searchedArray = []
        searchEnable = true
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

        let cell:ListingCell = self.tableView.dequeueReusableCell(withIdentifier: "Cell") as! ListingCell

        if searchEnable {
                self.setEmployeeDetailsInTableView(cell: cell, index: indexPath.row, dataArray: searchedArray)
        }
        else{
                self.setEmployeeDetailsInTableView(cell: cell, index: indexPath.row, dataArray: listArray)
        }
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if (searchBar.text?.characters.count)! > 0 {
        searchEnable = true
        getListForSearchedText(searchText)
    }
    if searchBar.text?.characters.count == 0{
        searchEnable = false
        self.tableView.reloadData()
    }
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchEnable = false
    self.searchedArray = []
    self.tableView.reloadData()
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    getListForSearchedText(searchBar.text!)
    searchBar.resignFirstResponder()
}

崩溃:

致命错误:索引超出范围

【问题讨论】:

  • 你能告诉我们崩溃的代码吗
  • 您是否在点击搜索栏时修改 listArray?
  • 不,我没有修改 listArray。
  • @JeniKhant 如果您需要帮助,那么您需要向我们展示您的代码。
  • @JeniKhant 您需要发布更多代码。

标签: ios swift uitableview swift3 uisearchbar


【解决方案1】:

您遇到此问题是因为您将searchEnable 设置为true 太早意味着在searchBarTextDidBeginEditing(_:) 中,所以正如您所说,tableView 仍在滚动,所以它会调用cellForRowAtIndexPath 并且因为@ 987654326@ 是 true 你遇到了这个崩溃。现在要解决您的问题,您需要将searchEnable 设置为true,您将在其中初始化searchedArray 数组并重新加载tableView

所以您需要在方法searchBar(_:shouldChangeTextIn:replacementText:) 中将searchEnable 设置为true,或者可能在您的方法getListForSearchedText 中。

【讨论】:

  • 谢谢这么多的答案,如果这是问题,我会更新。
  • 是的,你说得对@Nirav,我刚刚删除了“searchBarTextDidBeginEditing(_ searchBar: UISearchBar)”函数中的代码,现在它工作正常。谢谢你。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多