2

I am relatively new to iOS (100 hours or so) and I am trying to implement a UISearchController without a storyboard. Is it possible to do this programmatically?

Bigtrizzy
  • 103
  • 2
  • 7
  • Additionally to Praveens detailled answer, if you need Objective-C examples, Apple provided [example code](https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Introduction/Intro.html) for dealing with UISearchController in iOS8. – itinance Apr 17 '15 at 21:32

1 Answers1

15

You have to implement UISearchController programmatically since Apple hasn't provided the ability to set it up using Storyboard yet.

Here are the steps to implement UISearchController in a view controller

  • Conform to UISearchResultsUpdating Protocol
  • Create a variable to reference the UISearchController

    var searchController: UISearchController!
    
  • Set searchController in viewDidLoad(_:)

    override func viewDidLoad() {
        super.viewDidLoad()
    
        searchController = UISearchController(searchResultsController: nil)
    
        // The object responsible for updating the contents of the search results controller.
        searchController.searchResultsUpdater = self
    
        // Determines whether the underlying content is dimmed during a search.
        // if we are presenting the display results in the same view, this should be false
        searchController.dimsBackgroundDuringPresentation = false
    
        // Make sure the that the search bar is visible within the navigation bar.
        searchController.searchBar.sizeToFit()
    
        // Include the search controller's search bar within the table's header view.
        tableView.tableHeaderView = searchController.searchBar
    
        definesPresentationContext = true
    }
    
  • Implement the method updateSearchResultsForSearchController(_:), which is called when the search bar becomes the first responder or when the user makes changes to the text inside the search bar

    func updateSearchResultsForSearchController(searchController: UISearchController) {
        // No need to update anything if we're being dismissed.
        if !searchController.active {
            return
        }
    
        // you can access the text in the search bar as below
        filterString = searchController.searchBar.text
    
        // write some code to filter the data provided to your tableview
    }
    
Praveen Gowda I V
  • 9,569
  • 4
  • 41
  • 49
  • Perfect, if only you can add the delegate methods for UISearchBar to your answer to avoid confusions with managing the search bar, it would be just great. They are referenced at this answer: http://stackoverflow.com/a/17628326/1953178. Thanks! – Amr Hossam Aug 30 '15 at 12:43
  • What is tableView? – Ian Warburton Jul 05 '16 at 16:31