Sam Flattery
Sam Flattery

Reputation: 53

Difference between UISearchBar and UISearchBarController?

I'm confused as to what the difference between a UISearchBar/UISearchBarDelegate and a UISearchBarController is.

Right now, this is what I'm doing to implement my search bar:

class SearchViewController: UIViewController {
    @IBOutlet weak var searchBar: UISearchBar!
}

extension SearchViewController: UISearchBarDelegate {

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        if !searchBar.text!.isEmpty {
            performSegue(withIdentifier: "Search", sender: searchBar.text!)
        }
    }
}

I've seen people online doing things like:

let searchController = UISearchController(searchResultsController: nil)

What is the difference between this and what I'm doing?

Upvotes: 5

Views: 3498

Answers (2)

Sweeper
Sweeper

Reputation: 273125

Your question is kind of similar to asking "What is the difference between UIView and UIViewController?"

UISearchBar is a view. It has a text field and (optionally) a button, and that's pretty much it.

UISearchController is a controller that controls the more abstract behaviour of "searching". One of its jobs is to control the behaviour of its searchBar, but it has many other jobs too, such as telling the searchResultsUpdater that it should update the search results (because the text in the search bar has changed, or whatever). It also exposes properties like obscuresBackgroundDuringPresentation and hidesNavigationBarDuringPresentation to control how the views should look when the search bar is the first responder.

If you are directly using UISearchBar, then you need to manually implement all these things that the UISearchController does for you. This could be desired if your intention is to create your own kind of searching behaviour that the UISearchController doesn't provide, but if you just want a plain old search feature in your app, use UISearchController because it will save you a lot of time.

Upvotes: 10

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36431

Roughly.

  • UIxxx is the class of objects rendered on screen, (UIButton, etc)

  • UIxxxController is the class of objects that coordinates objects on screen (receive events, etc.)

  • UIxxxDelegate the class of objects that embed functional code to let UIxxx objects behave the way you want (fill content, etc).

Your code looks like you connected things via IB. The code found on internet looks like the controller is built directly in the code and not via IB; the UISearchController is instanciated.

Upvotes: 0

Related Questions