Searchbar filtering issue

前端 未结 3 1588
梦毁少年i
梦毁少年i 2021-01-16 10:13

Im new to the swift, I am trying to filter name from an array using the search bar in console am getting what I entered in the search bar but filtering with predicate im not

3条回答
  •  时光说笑
    2021-01-16 10:52

    The most efficient way to filter custom classes is to use the same type for the data source array and the filtered array

    var caseListOfBooker = [CaseDetails]()
    var filteredBooker = [CaseDetails]()
    

    Add a property isFiltering which is set to true when the search text is not empty

    var isFiltering = false
    

    and delete searchString and filteredString

    var searchString:String=""
    var filteredString = [String]()
    

    In updateSearchResults filter the data source array (with native Swift functions), set isFiltering accordingly and reload the table view

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print("searchText \(searchText)")
        updateSearchResults(searchText: searchText)
    }
    
    func updateSearchResults(searchText: String) {
        if searchText.isEmpty {
            filteredBooker.removeAll()
            isFiltering = false
        } else {
            filteredBooker = caseListOfBooker.filter{$0.person_of_interest.range(of: searchText, options: .caseInsensitive) != nil }
            isFiltering = true
        }
        tableview.reloadData()
    }
    

    In the table view data source methods display the data depending on isFiltering

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return isFiltering ? filteredBooker.count : caseListOfBooker.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview.dequeueReusableCell(withIdentifier: "POIProfileDetailsCell", for: indexPath) as! POIProfileDetailsCell
        let booker = isFiltering ? filteredBooker[indexPath.row] : caseListOfBooker[indexPath.row]
        cell.poiName.text = booker.person_of_interest
    }
    

提交回复
热议问题