Reputation: 649
I try to filter an array from UISearchController, and it failed. my first attempt is I try to make two array the first array is to store the data and the second array to hold the filter. than make my numberOfRowsInSection count as a filter array but it still not working, what went wrong?. here is show you my code .
// This is in my PopularViewController
let store = PopularStore()
var timer: Timer?
var page = 1
var hasMoreMovies = true
let dataSource = PopularDataSource()
override func viewDidLoad() {
super.viewDidLoad()
fetchMovie(page: page)
}
private func fetchMovie(page: Int) {
showLoadingView()
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { _ in
self.store.fetchMovie(page: page, completion: { [weak self] result in
guard let self = self else { return }
self.dismissLoadingView()
switch result {
case .success(let movies):
if movies.count < 100 { self.hasMoreMovies = false }
self.dataSource.items.append(contentsOf: movies)
case .failure(let error):
print(error)
}
self.tableView.reloadSections(IndexSet(integer: 0), with: .none)
})
})
}
extension PopularViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if !searchText.isEmpty {
dataSource.filterMovie = dataSource.items.filter({ $0.title.lowercased().contains(searchText.lowercased() )})
dataSource.filterMovie = dataSource.items
}
}
}
// This is in my UITableViewDataSource
class PopularDataSource: NSObject, UITableViewDataSource {
var items = [Movie]()
var filterMovie = [Movie]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filterMovie.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PopularCell.cellID, for: indexPath)
return cell
}
}
Upvotes: 0
Views: 60
Reputation: 285082
As filterMovie
is the main data source assign the whole list (items
) or the filtered items depending on searchText
and reload the table view
extension PopularViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if !searchText.isEmpty {
dataSource.filterMovie = dataSource.items.filter{ $0.title.range(of: searchText, options: .caseInsensitive) != nil }
} else {
dataSource.filterMovie = dataSource.items
}
self.tableView.reloadData()
}
}
If the deployment target is iOS 13 consider to use UITableViewDiffableDataSource
to populate the table view. It's very fast and you get smart animations.
Upvotes: 1