How to add uisearchcontroller to tableview

 

This tutorial has been updated for X code 7.3 & swift 2.2

When you have large amount of data in your table then finding items can take a long time. Luckily you can quickly search using UISearchController. Before this there was UISearchDisplayController. That is deprecated in X code 6.3. And now you have UISearchController to replace it. I am going to teach you how to use this now.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set project name to search demo & save it on desktop.

new x code project

 

2. Go to main storyboard, delete view controller & add table view controller

add table view controller

 

3. Select table view controller & set it as initial view controller

set initial view controller

 

4. Select the prototype cell & set its identifier to tableCell

prototype cell identifier

 

5. Select table view controller, go to Editor -> Embed In -> Navigation controller & set its title to Numbers

set navigation title

 

6. Now delete view controller swift file & add new cocoa touch class file of subclass UITableViewController

add table view controller swift file

 

7. Go to main storyboard, select table view controller & set custom class to NumberTableViewController

set custom class

 

8. Create array to store table data values. Create another array to store filtered data. And create instance of search controller as follows

class NumberTableViewController: UITableViewController {
var tableData = ["One", "Two", "Three", "Four", "Five"]

var filteredData:[String] = []

var resultSearchController:UISearchController!

9. In view did load add following code

override func viewDidLoad() {
    super.viewDidLoad()
    // 1
    resultSearchController = UISearchController(searchResultsController: nil)
    // 2
    resultSearchController.searchResultsUpdater = self
    // 3
    resultSearchController.hidesNavigationBarDuringPresentation = false
    // 4
    resultSearchController.dimsBackgroundDuringPresentation = false
    // 5
    resultSearchController.searchBar.searchBarStyle = UISearchBarStyle.Prominent
    // 6
    resultSearchController.searchBar.sizeToFit()
    // 7
    self.tableView.tableHeaderView = resultSearchController.searchBar

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
  1. In closure of result search controller create instance of search controller
  2. The search result will be shows on same table view controller. This will give you error. Just ignore it for now & we will fix it soon.
  3. Search controller will not replace navigation bar when searching
  4. Background will not become dark when searching
  5. Search bar style is set to Prominent but you can set it to minimal also
  6. Search bar will fit in size available.
  7. Search bar is placed in header of table view.

10. Set number of sections to 1 & if search controller is active then set number of rows per section to filter data count else table data count

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    if resultSearchController.active {
        return filteredData.count
    }
    else {
        return tableData.count
    }
}

11. Uncomment cell for row at index path & similar to previous method when search controller is active show filtered data otherwise show table data

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath)

    // Configure the cell...
    if resultSearchController.active {
        cell.textLabel?.text = filteredData[indexPath.row]
    }
    else {
        cell.textLabel?.text = tableData[indexPath.row]
    }

    return cell
}

12. Add UISearchResultUpdateing subclass as follows

class NumberTableViewController: UITableViewController, UISearchResultsUpdating {

13. Add following method & all the errors will go away. This method triggers when search bar is active and search bar text is changed

func updateSearchResultsForSearchController(searchController: UISearchController) {
        if searchController.searchBar.text?.characters.count > 0 {
            
            // 1
            filteredData.removeAll(keepCapacity: false)
            // 2
            let searchPredicate = NSPredicate(format: "SELF CONTAINS %@", searchController.searchBar.text!)
            // 3
            let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
            // 4
            filteredData = array as! [String]
            // 5
            tableView.reloadData()
            
        }
        else {
            
            filteredData.removeAll(keepCapacity: false)
            
            filteredData = tableData
            
            tableView.reloadData()
            
        }

}
  1. Empty the filter data array
  2. Predicate sets condition for filter.[lower case c] means results would be case insensitive.
  3. Filter tableData using the predicate
  4. Save filtered result in an array
  5. Update table view with search results

Now build and run app in iPhone 5s. Then start searching.

search bar
Download X code file
Challenge 1: Add secondary search filters as follows

search controller with scope
Download Challenge 1 Solution
Challenge 2: Place search bar in navigation controller instead of table header

nav bar search
Download Challenge 2 Solution
Challenge 3: Hide search bar behind navigation controller & pull tableview to show search bar

hide behind nav bar
Download Challenge 3 Solution

Total 11 Votes
1

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?