Searchbar filtering issue

前端 未结 3 1589
梦毁少年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:48
    let array = self.caseListOfBooker.filter{$0.person_of_interest.contains(searchString)}
    

    You are getting array of CaseDetails objects and trying to cast to array of String

    It fails. You need to get string values from the CaseDetails object and join them

    Use

    filteredString = array.map { $0.person_of_interest }
    

    Or

    for caseDetail in array {
        filteredString.append(caseDetail.person_of_interest)
    }
    

    Instead of

    if let list = array as? [String]{
        filteredString=list
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2021-01-16 10:52
    var searchPredicate = NSPredicate()
    searchPredicate = NSPredicate(format: "self CONTAINS[C] %@", your_searching_text)        
    let Final_Search_array = (Your_Array).filtered(using: searchPredicate)
    
    0 讨论(0)
提交回复
热议问题