Reputation: 81
My scenario, I implemented codebase for UISearchbar
with some animation
effect like expand
and collapse
.
Here, whenever I am trying to search
the search result displaying well after I added custom clear button
it will operate
collapse animation same time reload
search result to original
table data
.
My issues is whenever I am clicking the custom clear button search
result not reloading to original
data in 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()
})
}
My Tableview cell
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
}
Upvotes: 0
Views: 1004
Reputation: 8914
You need to set data source array to original one.
Reason
Actually you are removing the datasource array filteredData.removeAll()
. After this an array is empty that is the reason self.tableView.reloadData()
is not working.
Solution
You need to make a copy of data source array, lets say originalData
contains the original data (without filter).
Whenever you user filter then you need to use originalData
to filter the data.
For Eg.
let filterdData = originalData.filter { //filter data }
So when you clear filter you need to set the original data again to table data source array.
For Eg.
filteredData.removeAll() //remove all data
filterData = originalData //Some thing that you need to assign for table data source
self.tableView.reloadData()
In table's cellForRowAt:
will get the data as follow...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var obj = filterData[indexPath.row]
print(obj)
}
Don't forget to assign data to originalData
before filter
Upvotes: 1