Reputation: 105
I am trying to use UISearchBar
with Firebase but I get an error when I try to type any right word
My Code is
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var isSearching: Bool = false
//list to store all the artist
var hotelList = [hotelsModel]()
var filterHotels = [hotelsModel]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearching{
return filterHotels.count
} else {
return hotelList.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//creating a cell using the custom class
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! hotelsTableViewCell
//the artist object
let hotel: hotelsModel
//getting the artist of selected position
hotel = hotelList[indexPath.row]
//adding values to labels
cell.lblName.text = hotel.name
cell.lblLocation.text = hotel.location
cell.appSuggest.text = hotel.appSuggest
cell.price.text = hotel.price
cell.canceletion.text = hotel.cancelation
cell.paymentNeeded.text = hotel.paymentNeeded
if isSearching{
cell.lblName?.text = filterHotels[indexPath.row].name
}
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
isSearching = false
view.endEditing(true)
tableView.reloadData()
} else {
isSearching = true
filterHotels = hotelList.filter({$0.name == searchBar.text})
tableView.reloadData()
}
}
in this line
if isSearching{
cell.lblName?.text = filterHotels[indexPath.row].name
}
this's my code files if someone can check it
thank you
Upvotes: 1
Views: 121
Reputation: 105
Thank You guys my problem it's was in the Number Of Rows In Section Function it's haven't return for filterHotels
I edit my question if someone need the code also i'll edit it in github
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isSearching{ return filterHotels.count } else { return hotelList.count } }
Upvotes: 0
Reputation: 475
I will suggest you to change the filter process (smth like this):
func filterContentForSearchText(_ searchText: String) {
let pred = NSPredicate(format: "name contains[cd] %@", searchText)
filteredHotels = hotelList?.filtered(using: pred) as? [hotelsModel]
tableView.reloadData()
}
and change the isSearching variable to this:
var isSearching: Bool {
return searchBar.text != ""
}
Use the debugger to see the indexPath.row value on the line that is causing your crash.
Upvotes: 1