ios - 使用 Swift 搜索结果后,搜索栏没有重新加载到原始数据?
问题描述
在我的场景中,我实现了代码库,UISearchbar
具有某种animation
效果,例如expand
和collapse
。
在这里,每当我尝试search
在添加自定义清除后显示良好的搜索结果时button
,它会将operate
动画同时折叠reload
到original
table搜索结果data
。
我的问题是,每当我单击自定义清除按钮时,search
结果不会重新加载original
到tableview
.
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 }
因此,当您清除过滤器时,您需要将原始数据再次设置为表数据源数组。
例如。
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
过滤器之前
推荐阅读
- php - Laravel 在几小时之间运行一批命令
- c++ - 在非 constexpr 函数中作为左值传递的变量上使用“constexpr”函数
- r - 取数据帧的 sum 和 col 名称的频率
- typescript - 使用 babel eslint 解析的 Typescript 强制转换
- terraform - 覆盖变量的一部分
- javascript - 无法停止反应中输入标签中小数点后的尾随零
- angular - ngrx/store 给我找不到模块“./shopping-list/store/shopping-list.reducer”错误
- python - Keras ConvLSTM 优化结果和内存管理
- vuejs2 - 如何将动态id 绑定到 JavaScript 事件?
- ios - Stripe iOS didCreatePaymentResult 永远不会被调用