将UISearchBar与Firebase数据库一起使用

时间:2018-11-19 15:07:19

标签: 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
    }
    

    https://i.stack.imgur.com/wSsP4.png

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

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

谢谢

2 个答案:

答案 0 :(得分:1)

我建议您更改过滤过程(如下所示):

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值。

答案 1 :(得分:0)

谢谢你们,我的问题是在节中的行数中,filterHotels还没有返回。我编辑我的问题,是否有人需要代码,我也会在github上进行编辑

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->  Int { if isSearching{ return filterHotels.count } else { return hotelList.count } }
相关问题