swift - 将 UISearchBar 与 Firebase 数据库一起使用

标签 swift firebase uisearchbar

我正在尝试将 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
    }
    

    /image/wSsP4.png

  • 这是我的代码文件 如果有人可以检查一下

    https://github.com/HaMaDaRaOuF/UISearchBar-Firabse

谢谢

最佳答案

我会建议你改变过滤过程(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/

相关文章:

ios - 如何在应用程序加载时在启动屏幕上播放 MP4 视频

ios - 向 GMSMapView 添加手势识别器以获得 .begin/.ended/.change 手势

javascript - Firebase:限制 child 对创建它的浏览器 session 的写访问权限

ios - 如何让搜索栏在 uicollectionview 中工作

ios - 使用 CoreLocation 获取最近的位置

swift - 当网络连接不可用时,Realm 使用本地数据库而不是同步?

java - 每个 API 的 Firestore 导入/导出

javascript - Firebase 推送给了我 SyntaxError : invalid object initializer

ios - UISearchController 的 UISearchBar 的光标显示第一次使用,而不是后续

uitableview - 带有 scopeBar 奇怪行为的 searchBar