Ios 搜索栏在使用Swift搜索结果后不重新加载到原始数据?
在我的场景中,我为Ios 搜索栏在使用Swift搜索结果后不重新加载到原始数据?,ios,swift,tableview,uisearchbar,Ios,Swift,Tableview,Uisearchbar,在我的场景中,我为UISearchbar实现了代码库,并使用了一些动画效果,如展开和折叠 在这里,每当我尝试搜索时添加自定义清除按钮后,搜索结果显示良好它将操作同时折叠动画重新加载搜索结果到原始表数据 我的问题是,每当我单击自定义清除按钮时,search结果不会重新加载到tableview中的original数据 func didTapFavoritesBarButtonOFF() { self.navigationItem.setRightBarButtonItems([se
UISearchbar
实现了代码库,并使用了一些动画
效果,如展开
和折叠
在这里,每当我尝试搜索时
添加自定义清除按钮后,搜索结果显示良好
它将操作
同时折叠动画重新加载
搜索结果到原始
表数据
我的问题是,每当我单击自定义清除按钮时,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()
})
}
我的Tableview手机
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()
因此,当您清除过滤器时,需要将原始数据再次设置为表数据源数组
例如
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)
}
不要忘记在筛选前将数据分配给
原始数据
请显示cellforrow的实现:
方法当然,我更新了我的答案。@–Mahendra gp非常有帮助。我真的很感谢你宝贵的回答和解释的方式非常好…干得好,谢谢你!