我正在尝试将 UISearchBar
与 Firebase 一起使用,但是当我尝试输入任何正确的词时出现错误
我的代码是
@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() } }
在这一行
if isSearching{ cell.lblName?.text = filterHotels[indexPath.row].name }
这是我的代码文件 如果有人可以检查一下
谢谢
最佳答案
我会建议你改变过滤过程(smth like this):
func filterContentForSearchText(_ searchText: String) {
let pred = NSPredicate(format: "name contains[cd] %@", searchText)
filteredHotels = hotelList?.filtered(using: pred) as? [hotelsModel]
tableView.reloadData()
}
并将 isSearching 变量更改为:
var isSearching: Bool {
return searchBar.text != ""
}
使用调试器查看导致崩溃的行上的 indexPath.row 值。
关于swift - 将 UISearchBar 与 Firebase 数据库一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53377464/