How to add (enable) UISearchBar in UINavigationBar
In this small tutorial I will guide you on how to enable Search Bar inside Navigation Bar on iOS.
As you may know, Apple added support of search controller for UINavigationItem since iOS 11. This allows displaying of search bar like inside of the navigation bar and it looks smooth and consistently.
As usual, Apple made integration as simple as few lines of code, so it takes no more than few minutes of your time.
I am going to show you the example on the Remotrainer application, which me and my team are working on.
First part is UI. In your Storybard place the UIViewController

- Create Storyboard file
- Place UITableViewController to the storyboard
- Embed it in UINavigationController
- Assign corresponding class for the UITableViewController in Identity inspector
The next step is code. In your controller class, in viewDidLoad() function, you need to create an instance of the search controller and set it as a search controller for navigation item:
let search = UISearchController(searchResultsController: nil)search.delegate = selfsearch.searchBar.delegate = selfself.navigationItem.searchController = search
Here are two more lines where I assign delegates for the search controller and search bar in search controller. First one is intended for notifying me when Cancel button is pressed, while the second one is for search bar field itself, when search text is entered. These delegates look like this:
extension ExercisesListController: UISearchControllerDelegate { func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { self.searchText = "" isFiltered = false self.tableView.reloadData() }}
And UISearchBarDelegate:
extension ExercisesListController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard !searchText.isEmpty else { self.searchText = "" isFiltered = false self.tableView.reloadData() return } self.searchText = searchText isFiltered = true self.tableView.reloadData() }}
The result looks like this:

Hope everything is clear. Ask questions if any. Happy coding :)
☕ Enjoying this content? Support me!
Creating quality content takes time and effort, and your support helps keep it going! If you found this article helpful, consider buying me a coffee — it’s a small gesture that makes a big difference.
