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

Posted

技术标签:

【中文标题】使用 Swift 搜索结果后,搜索栏没有重新加载到原始数据?【英文标题】:Searchbar not reloading to original data after search result using Swift? 【发布时间】:2019-02-09 06:33:23 【问题描述】:

我的场景,我为 UISearchbar 实现了代码库,并带有一些 animation 效果,例如 expandcollapse

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

我的问题是,每当我单击自定义清除按钮 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

【问题讨论】:

请展示cellForRowAt:方法的实现 当然,我更新了我的答案。@– Mahendra GP 【参考方案1】:

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

原因

实际上,您正在删除数据源数组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

【讨论】:

帮助很大。我非常感谢您的宝贵回答和出色的解释方式……干得好,谢谢!

以上是关于使用 Swift 搜索结果后,搜索栏没有重新加载到原始数据?的主要内容,如果未能解决你的问题,请参考以下文章

在搜索期间重新加载 UITableView

如何在swift 3中从标签栏移动时重新加载页面?

展开 segue 后,swift 2 搜索栏不会隐藏

Swift:选择搜索结果后返回tableview

Swift 搜索栏 - 使用 Alamofire 请求更新表格视图

实现搜索栏功能 - Swift