Building a search bar in UIKit for real apps
Search UI is one of those controls that looks trivial until you try to ship it. The field itself is a single line of text, but the moment a user taps it, the keyboard appears, the interface has to respond, results need to update without stuttering, and the whole thing still has to work with VoiceOver turned on. I learned most of this the hard way while building small apps with UIKit outside of Xcode's templates.
UIKit actually offers two different starting points for search, and picking the wrong one is the most common mistake I made. A standalone UISearchBar is a view you place anywhere you like and configure yourself. UISearchController is a controller, introduced back in iOS 11, that wraps a search bar and handles the presentation of results for you. They solve similar problems but suit very different screens.
The walkthrough below covers both approaches, shows how to filter content as the user types, and finishes with the details that separate a working prototype from something you would genuinely want to release to users in Melbourne, Sydney or anywhere else. The snippets are plain Swift and drop straight into a fresh Xcode project.
Choosing between a search bar and a search controller
The simplest way to think about the difference is where the results appear. UISearchController owns the presentation: the search bar can be attached to your navigation item, slides down from the top, dims the underlying content on iPhone, and presents the cancel button automatically. You hand it a results updater and it calls you back on every keystroke. This is the behaviour people expect from native iOS apps, and it is almost always the right choice when typing a query replaces the current screen.
UISearchBar is just a view. You can drop it into a table header, a stack view pinned under a filter row, or a sidebar on iPad. Because you own it, you also own the delegate callbacks, the keyboard behaviour and the dismissal logic. That extra responsibility is worth it when the search field has to live permanently inside your layout rather than appearing only when the user starts scrolling.
A practical rule: if results should take over the screen, use UISearchController. If results should appear inside the screen that already exists, use a plain UISearchBar. Both routes end up calling the same filtering method in the end, so the decision is mostly about presentation and plumbing rather than logic.
Adding a search bar to your view controller
Start with the manual route, because it is the one that teaches you what the system is doing for free. The essentials are the delegate, a useful placeholder, and sensible keyboard behaviour. Autocapitalisation is worth turning off for codes and identifiers, while autocorrection can stay on for words like "Melbourne" or "Woolworths".
import UIKit
final class StoreSearchViewController: UIViewController {
private let searchBar = UISearchBar()
private let tableView = UITableView(frame: .zero, style: .insetGrouped)
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
searchBar.placeholder = "Search Australian stores"
searchBar.autocapitalizationType = .none
searchBar.autocorrectionType = .no
searchBar.searchBarStyle = .minimal
searchBar.showsBookmarkButton = true
tableView.frame = view.bounds
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(tableView)
searchBar.sizeToFit()
tableView.tableHeaderView = searchBar
}
}
extension StoreSearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filterStores(matching: searchText)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
Notice that the search bar sits in the table header rather than in the view hierarchy directly. That keeps it sticky while the table scrolls, which is exactly the behaviour users see in shopping or travel apps. When you are still deciding between two implementations, running a compare two files in a diff tool is a quick way to spot duplicated delegate wiring, because a lot of search bugs come from two objects both trying to respond to the same field.
One detail that catches newcomers: sizeToFit() must be called before the search bar becomes the table header, and the header needs to be reassigned afterwards if the layout ever changes. I have also found that adding the search bar in viewDidLoad and leaving it out of Auto Layout is perfectly fine here, since the table header is managed by UIKit itself.
Hooking search into the navigation bar
For the common case, UISearchController removes most of the code above. You create it once, point it at an updater, and assign it to navigationItem.searchController. The system handles the scroll-to-reveal behaviour, the cancel button and the dimming overlay, so your view controller stays focused on data.
final class CafeSearchViewController: UIViewController {
private lazy var searchController = UISearchController(searchResultsController: nil)
private let tableView = UITableView(frame: .zero, style: .insetGrouped)
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Find a cafe near you"
searchController.searchBar.autocapitalizationType = .none
searchController.searchBar.returnKeyType = .search
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = true
definesPresentationContext = true
}
}
extension CafeSearchViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let query = searchController.searchBar.text ?? ""
filterCafes(matching: query)
}
}
obscuresBackgroundDuringPresentation = false is the setting that makes the results list appear inside your own screen instead of on a separate blank page, and it pairs naturally with a UITableView that you want to keep visible. definesPresentationContext = true tells UIKit that this controller is the one presenting the search results, which prevents odd behaviour when you push a new screen from a search result.
The updater fires on every character, so keep the work inside it cheap. If your dataset is small, filtering an array of cafe names or suburbs is instant. If you are querying a database, use a background queue and only apply the result on the main thread, and debounce input by around 150 milliseconds so a fast typist does not trigger ten queries in two seconds.
Filtering data as the user types
Filtering is where search stops being a widget and starts being a feature. The core operation is usually a case-insensitive match against a display name, but there are variations worth knowing: matching on suburb and postcode as well as name makes a Melbourne cafe finder feel much more useful, since people search "3000" or "Carlton" as often as they search the business name.
private func filterCafes(matching query: String) {
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
cafes = allCafes
tableView.reloadData()
return
}
cafes = allCafes.filter { cafe in
cafe.name.localizedCaseInsensitiveContains(trimmed)
|| cafe.suburb.localizedCaseInsensitiveContains(trimmed)
|| cafe.postcode.hasPrefix(trimmed)
}
tableView.reloadData()
}
For longer lists, a diffable data source avoids the flicker of reloadData(). Build a snapshot with the filtered identifiers and apply it with animation, and the table inserts and removes rows smoothly instead of redrawing everything.
var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
snapshot.appendSections([0])
snapshot.appendItems(visibleCafes.map(\.id), toSection: 0)
dataSource.apply(snapshot, animatingDifferences: true)
Empty states matter more than people expect. When a search returns nothing, show a short line such as "No cafes match that suburb yet" rather than an empty table, because in the Australian market people often search with partial or informal terms, and a blank screen reads as a crash. Scope bars are another useful addition for apps that need filters, for example "Open now", "Under $10" or "Takeaway", and you attach them to the same search controller without extra layout work.
Accessibility, localisation and visual polish
Accessibility is not a coat of paint applied at the end. A search field needs an accessible label distinct from the visible placeholder, since placeholders disappear as soon as typing begins and VoiceOver users get nothing useful afterwards. Set searchBar.accessibilityLabel and accessibilityHint, and make sure the cancel button and the scope buttons have real titles rather than relying on their icons.
Dynamic Type deserves attention too. The system search bar scales reasonably well, but any custom filter chip or result header you build alongside it will not scale unless you use text styles. Australian English also matters: search fields that spell out "colour", "organisation" and "favourite" should use localised strings rather than hard-coded American spellings, and the autocorrect dictionary will follow the device region anyway, so inconsistent phrasing looks odd.
Settings worth checking
- Placeholder text that explains the searchable content, such as "Search suburbs or postcodes"
returnKeyType = .searchso the keyboard confirms the query instead of inserting a line break- Dark mode colours drawn from your asset catalogue rather than hard-coded white and grey
- VoiceOver labels and hints for the field, the cancel button and any scope controls
Mistakes worth avoiding
- Reusing one filtered array for both the table and the original dataset, which corrupts results after the second keystroke
- Leaving
obscuresBackgroundDuringPresentationat its default when results should render inside your screen - Forgetting
definesPresentationContext = truewhen pushing detail views from search results - Filtering on the main thread across a large dataset, which makes the keyboard lag on older devices
Keeping the search experience native
A working search bar is a small amount of code, but a convincing one comes from choosing the right component and letting the system do the heavy lifting. UISearchController for full-screen searching, UISearchBar for fields embedded in your own layout, a lightweight filter method, and a clear empty state. Everything else is detail, and the detail that users notice most is the one nobody sees: the keyboard never stutters, the cancel button appears exactly where iOS users expect it, and the results list stays readable with accessibility switched on.
The part worth remembering is that search is not a text field you add to a screen. It is a small interaction loop between typing, filtering, keyboard and presentation, and treating it as one loop rather than a collection of delegate callbacks is what makes the difference between a demo and an app you would put your name on.