Add search view controller on top of view năm 2024

Update note: Lorenzo Boaro updated this tutorial to Xcode 11, Swift 5 and iOS 13. Tom Elliott wrote the original.

Scrolling through massive lists of items can be a slow and frustrating process for users. When dealing with large datasets, it’s vitally important to let the user search for specific items. UIKit includes UISearchBar, which seamlessly integrates with UINavigationItem via a UISearchController and allows for quick, responsive filtering of information.

In this tutorial, you’ll build a searchable Candy app based on a standard table view. You’ll add table view search capability, dynamic filtering and an optional scope bar, all while taking advantage of UISearchController. In the end, you’ll know how to make your apps much more user-friendly and how to satisfy your users’ urgent demands.

Ready for some sugar-coated search results? Read on.

Getting Started

Start by downloading the starter project using the Download Materials button at the top or bottom of this tutorial. Once it’s downloaded, open CandySearch.xcodeproj in Xcode.

To keep you focused, the starter project has everything unrelated to searching and filtering already set up for you.

Open Main.storyboard and look at the view controllers contained within:

Add search view controller on top of view năm 2024

The view controller on the left is the root navigation controller of the app. Then you have:

  1. MasterViewController: This contains the table view that you’ll use to display and filter the candies you’re interested in.
  2. DetailViewController: This displays the details of the selected candy along with its image.

Build and run the app and you’ll see an empty list:

Add search view controller on top of view năm 2024

Back in Xcode, the file Candy.swift contains a struct to store the information about each piece of candy you’ll display. This struct has two properties:

  • name: This property has type String and is fairly self-explanatory.
  • category: This is an enum of type let searchController = UISearchController(searchResultsController: nil) 0, which represents the category each candy belongs to. It also conforms to let searchController = UISearchController(searchResultsController: nil) 1 so that you can convert it to and from an associated raw value of type String.

When the user searches for a type of candy in your app, you’ll search the name property using the user’s query string. The category will become important near the end of this tutorial, when you implement the scope bar.

Populating the Table View

Open MasterViewController.swift. You’ll manage all the different

let searchController = UISearchController(searchResultsController: nil) 3 for your users to search in

let searchController = UISearchController(searchResultsController: nil) 4. Speaking of which, it’s time to create some candy!

Note: In this tutorial, you only need to create a limited number of values to illustrate how the search bar works; in a production app, you might have thousands of these searchable objects. But whether an app has thousands of objects to search or just a few, the methods you use will remain the same. This is scalability at its finest!

To populate

let searchController = UISearchController(searchResultsController: nil) 4, add the following code to

let searchController = UISearchController(searchResultsController: nil) 6 after the call to

let searchController = UISearchController(searchResultsController: nil) 7:

candies = Candy.candies() Build and run. Since the sample project has already implemented the table view’s data source methods, you’ll see that you now have a working table view:

Add search view controller on top of view năm 2024

Selecting a row in the table will also display a detail view of the corresponding candy:

Add search view controller on top of view năm 2024

So much candy, so little time to find what you want! You need a UISearchBar.

Introducing UISearchController

If you look at UISearchController‘s documentation, you’ll discover it’s pretty lazy. It doesn’t do any of the work of searching at all. The class simply provides the standard interface that users have come to expect from their iOS apps.

UISearchController communicates with a delegate protocol to let the rest of your app know what the user is doing. You have to write all of the actual functionality for string matching yourself.

Although this may seem scary at first, writing custom search functions gives you tight control over how your specific app returns results. Your users will appreciate searches that are intelligent and fast.

If you’ve worked with searching table views in iOS in the past, you may be familiar with

extension MasterViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) {

// TODO  
} } 1. Since iOS 8, Apple has deprecated this class in favor of UISearchController, which simplifies the entire search process.

In MasterViewController.swift, add a new property under

let searchController = UISearchController(searchResultsController: nil) 4‘ declaration:

let searchController = UISearchController(searchResultsController: nil) By initializing UISearchController with a

extension MasterViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) {

// TODO  
} } 5 value for

extension MasterViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) {

// TODO  
} } 6, you’re telling the search controller that you want to use the same view you’re searching to display the results. If you specify a different view controller here, the search controller will display the results in that view controller instead.

In order for

extension MasterViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) {

// TODO  
} } 7 to respond to the search bar, it must implement

extension MasterViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) {

// TODO  
} } 8. This protocol defines methods to update search results based on information the user enters into the search bar.

Still in MasterViewController.swift, add the following class extension outside of the main

extension MasterViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) {

// TODO  
} } 7:

extension MasterViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) {

// TODO  
} }

// 1 searchController.searchResultsUpdater = self // 2 searchController.obscuresBackgroundDuringPresentation = false // 3 searchController.searchBar.placeholder = "Search Candies" // 4 navigationItem.searchController = searchController // 5 definesPresentationContext = true 0 is the one and only method that your class must implement to conform to the

extension MasterViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) {

// TODO  
} } 8 protocol. You’ll fill in the details shortly.

Setting Up

// 1 searchController.searchResultsUpdater = self // 2 searchController.obscuresBackgroundDuringPresentation = false // 3 searchController.searchBar.placeholder = "Search Candies" // 4 navigationItem.searchController = searchController // 5 definesPresentationContext = true 2‘s Parameters

Next, you need to set up a few parameters for your

// 1 searchController.searchResultsUpdater = self // 2 searchController.obscuresBackgroundDuringPresentation = false // 3 searchController.searchBar.placeholder = "Search Candies" // 4 navigationItem.searchController = searchController // 5 definesPresentationContext = true 2. Still in MasterViewController.swift, add the following to

let searchController = UISearchController(searchResultsController: nil) 6, just after the assignment to

let searchController = UISearchController(searchResultsController: nil) 4:

How do I add a search bar to a table view?

Adding Search Bar on TableViewAdd the UISearchBar at the top of your UITableView. … and give the name searchBar. In the ViewController add a Boolean called searching to know when to switch between the full list of items and the list of items from the searching results.

How do I add a search bar to a view in Swift?

Let's Create a Simple SearchBar in Swift.

Open an empty Xcode project. Select storyboard as interface and Swift as language..

Open the component library and add Searchbar component in the default View Controller..

What is search display controller?

An object that manages the display of a search bar, along with a table view that displays search results.