Swift Using NSFetchedResultsController and UISearchBarDelegate

前端 未结 2 1531
广开言路
广开言路 2021-02-10 17:12

I am looking for a decent solution to this problem. I am wanting to implement some simple search functionality on a TableView that I have.

All the examples I have found

2条回答
  •  不思量自难忘°
    2021-02-10 17:41

    From your code, I assume you want to use the same table view to display the results. So you just need to update your FRC with a new filter based on the search term.

    Store the search term in a variable. In the FRC factory function, include the predicate, something like this:

    request.predicate = searchText?.characters.count > 0 ?
     NSPredicate(format:"title contains[cd] %@", searchText!) : nil
    

    When the text changes, reset the FRC and reload.

    fetchedResultsController = nil
    tableView.reloadData()
    

    If you have additional filters, such as scope buttons, add additional terms to the predicate.

提交回复
热议问题