使用 Swift 搜索结果后搜索栏不重新加载到原始数据?

Searchbar not reloading to original data after search result using Swift?

我的方案,我为 UISearchbar 实现了代码库,具有一些 animation 效果,例如 expandcollapse.

在这里,每当我尝试 search 添加自定义清除 button 后搜索结果显示良好时,它会同时 operate 折叠动画 reload 搜索结果至 original table data.

我的问题是每当我单击自定义清除按钮时 search 结果不会重新加载到 tableview 中的 original 数据。

func didTapFavoritesBarButtonOFF() {

        self.navigationItem.setRightBarButtonItems([self.favoritesBarButtonOn], animated: false)
        print("Hide Searchbar")

        // Reload tableview 
        searchBar.text = nil
        searchBar.endEditing(true)
        filteredData.removeAll()
        self.tableView.reloadData() // not working

        // Dismiss keyboard
        searchBar.resignFirstResponder()

        // Enable navigation left bar buttons
        self.navigationItem.leftBarButtonItem?.isEnabled = false

        let isOpen = leftConstraint.isActive == true

        // Inactivating the left constraint closes the expandable header.
        leftConstraint.isActive = isOpen ? false : true

        // Animate change to visible.
        UIView.animate(withDuration: 1, animations: {
            self.navigationItem.titleView?.alpha = isOpen ? 0 : 1
            self.navigationItem.titleView?.layoutIfNeeded()
        })
    }

我的表格视图单元格

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredData.count
 }

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

    let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! CustomTableViewCell
    cell.titleLabel.text = self.filteredData[indexPath.row]
    return cell
}

您需要将数据源数组设置为原始数组。

原因

实际上您正在删除数据源数组 filteredData.removeAll()。在此之后数组为空,这就是 self.tableView.reloadData() 不起作用的原因。

解决方案

您需要复制数据源数组,假设 originalData 包含原始数据(没有过滤器)。

每当您进行用户过滤时,您都需要使用 originalData 来过滤数据。

例如

let filterdData = originalData.filter { //filter data }

所以当你清除过滤器时你需要重新设置原始数据到table数据源数组。

例如

filteredData.removeAll() //remove all data
filterData = originalData //Some thing that you need to assign for table data source
self.tableView.reloadData()

在table的cellForRowAt:会得到如下数据...

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

      var obj = filterData[indexPath.row] 
      print(obj)

 }

不要忘记在过滤器

之前将数据分配给originalData