首页 > 解决方案 > 使用 Swift 搜索结果后,搜索栏没有重新加载到原始数据?

问题描述

在我的场景中,我实现了代码库,UISearchbar具有某种animation效果,例如expandcollapse

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

我的问题是,每当我单击自定义清除按钮时,search结果不会重新加载originaltableview.

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
}

标签: iosswifttableviewuisearchbar

解决方案


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

原因

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

解决方案

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

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

例如。

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

因此,当您清除过滤器时,您需要将原始数据再次设置为表数据源数组。

例如。

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

在表cellForRowAt:中将获得如下数据...

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

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

 }

不要忘记将数据分配给originalData过滤器之前


推荐阅读