How to make a custom search bar in Swift

Oscar de la Hera Gomez
A flower that represents Swift next to a flower that represents XCode. Beneath it sits the text that states 'Custom Search Bar'.

A step by step tutorial on making a custom search bar in Swift (iOS). Github repository included.

The following tutorial walks you through how to make a custom search bar in Swift (iOS). The tutorial builds off our open source starter project and starts at the tutorial/graphql/data-driven-collectionview branch with all relevant changes found on the tutorial/custom/searchbar branch.

Please note that this tutorial builds of a series of tutorials listed below destined at creating a Swift starter project, setting it up for API calls, making a GraphQL API call and visualizing the results through a data driven UICollectionView.

Please note this tutorial uses the TinyConstraints Swift package, which we added using the Swift Package Manager.

What are we making in this tutorial ?

A screenshot of the product of the tutorial.

In this tutorial, we will be creating a custom search bar that uses a style for both the placeholder text and the active search text. We will handle all the keyboard dismissals by allowing the user to dismiss the keyboard when touching on the screen outside of the search bar or when pressing the return key and make the search bar change appearance depending on the content that is within it (i.e. if no content, appear grayed out, with content, appear black).

If you are seeking how to make use of the out of the box UISearchBar provided by Apple, please use the link below.

Tutorial

We recommend downloading our Open Source project, checking out the tutorial/graphql/data-driven-collectionview branch and carrying out the steps outlined below. All relevant changes are found in the tutorial/custom/searchbar branch.

git clone git@github.com:delasign/swift-starter-project.git

Step One: Add the content

A screenshot of our updated UIContent, English language json and Spanish language json.

The following step is dedicated at declaring the content for the search bar.

For more information on content and localization please read the tutorial linked below.

A | Declare the UIContent

A screenshot of how we declared the search UIContent.

In UIContent.swift, declare a new struct called SearchBar and add a constant called search.

B | Add your strings

A screenshot of our updated English language JSON and Spanish language JSON.

Add the struct and search string to the en.json and es.json.

Step Two: Add the colors

A screenshot of how we added the search placeholder grey to the Colors struct.

In Colors.swift, add the colors for your placeholder text and active search text. In our case, we are creating a searchPlaceHolderGray as we will be using black for the active search text and this already exists.

Sample snippet available below.

Step Three: Create the search style

A screenshot of our attributed Search Style extension for our Styleguide.

In our case we will be using a single style for both the placeholder and the active search text.

In the Styleguide folder, create a new file called Styleguide+SearchStyle.swift and paste in the code below.

Please note that in this case we have created a separate static function for the attributes as the UITextfield requires you to set default attributes to save you having to update the attributed text over time.

For more information on the Styleguide please use the links below.

Step Four: Add the Search Image

A screenshot of the search icon in the assets.xcassets and in the UIImage struct.

Add your local image to Assets.xcassets as searchBarIcon and subsequently add it to UIImages.swift as a constant within the SampleImages struct.

We recommend that you create different structs for different parts of your app, but for this tutorial we have added it there to simplify the process.

Step Five: Create the SearchBar UIView

A screenshot of the SearchBar UIView file.

Within the Components folder, create a new folder called SearchBar.

Within the newly created SearchBar folder, create a new file called SearchBar.swift and paste in the code found below.

Please note that we created the setupUI functionality in the next step.

Step Six: Create the SearchBar UI extension

A screenshot of the SearchBar UI Extension

Within the SearchBar folder, create a new file called SearchBar+UI.swift and paste in the code found below.

Please note that we set the attributes of the SearchBar UITextFiled on line 51 - these match those of the placeholder and were created on Step Three.

Step Seven: Create the SearchBar update extension

A screenshot of the SearchBar Update Extension

Within the SearchBar folder, create a new file called SearchBar+Update.swift and paste in the code found below.

The purpose of this functionality is to allow the attributed placeholder text to be set when the content is updated.

Step Eight: Add the search bar to the CustomUIView

A screenshot of the Searchbar added to the CustomUIView.

The following step is dedicated at adding the search bar to the CustomUIView.

A screenshot of the declaration of the Search Bar variable.

In the CustomUIView.swift, declare the search bar constant.

B | Add the search bar UI to the CustomUIView

A screenshot of the updates that we made to the CustomUIView UI extension to add the search bar to the CustomUIView, along with the modifications to the UICollectionView.

In CustomUIView+UI.swift, add the search bar to your UI.

Sample snippet provided below.

Please note that we updated the UICollectionView to be top to bottom of the search bar.

C | Update search bar content

A screenshot of the code that we used to update the search bar content, within the onContentUpdate of the CustomUIView Update file.

In CustomUIView+Update.swift call the search bar content update to update the placeholder.

D | Verify

A screenshot of the Searchbar added to the CustomUIView.

Run your app to make sure that it appears as above.

As you can see the UITextField works as expected, with the placeholder appearing on launch; a keyboard appearing on tap and the text changing to the attributed text that we set on Step Seven.

Step Nine: Hide the keyboard when the user presses return

A screenshot showing the application with a keyboard, with text saying "active text" in the search bar on the left and the same image without a keyboard on the right. This visual is meant to demonstrate that if you touch the screen or the return key, it will dismiss the keyboard.

The following step aims to dismiss the keyboard when the user presses return on the iOS Keyboard.

A | Set the UITextfield delegate

A screenshot of the code that demonstrates how we declared the textfield delegate within the UI setup of the UITextfield.

In SearchBar+UI.swift set the UITextfield delegate to self.

Please note that we create the delegate in the next part of this step.

B | Create dismiss keyboard functionality

A screenshot of our dismiss keyboard functionality within the SearchBar+Update.swift file.

In SearchBar+Update.swift create the dismiss keyboard functionality.

Sample snippet available below.

C | Create the TextField delegate extension

A screenshot of the first version of our delegate extension that dismisses the keyboard if the user presses the return key.

Within the SearchBar folder, create a new file called SearchBar+Textfield.swift and paste in the code found below.

D | Verify

A screenshot showing the application with a keyboard, with text saying "active text" in the search bar on the left and the same image without a keyboard on the right. This visual is meant to demonstrate that if you touch the screen or the return key, it will dismiss the keyboard.

Run the app, select the search bar textfield and see the keyboard appear. Then, verify that if you press the return key, the keyboard is dismissed.

A screenshot showing the application with a keyboard, with text saying "active text" in the search bar on the left and the same image without a keyboard on the right. This visual is meant to demonstrate that if you touch the screen or the return key, it will dismiss the keyboard.

The following step aims to dismiss the keyboard when interacting outside of the SearchBar UIView.

A | Declare the keyboard is active variable

A screenshot showing how we declared the keyboard is active boolean.

In SearchBar.swift declare a keyboardIsActive boolean variable and set it to false.

B | Update keyboard is active depending on edit state.

A screenshot showing how we updated keyboard is active based on edit state.

In SearchBar+Textfield.swift change the state depending on whether the UITextField is editing or not.

C | Hide the keyboard

A screenshot showing the touch functionality for the the UICollectionView that dismisses the keyboard when touching UICollectionview - which happens to be the remaining part of the screen.

In CustomUIView+CollectionView.swift add the UICollectionView touch functionality above the visual functionality, and if the keyboard is active - dismiss the keyboard.

D | Verify

A screenshot of our dismiss keyboard functionality within the SearchBar+Update.swift file.

Run the app, press the search bar to see the keyboard appear. Then, press the screen to verify that the keyboard is dismissed.

Step Eleven: Change the search icon color if the search is active

A screenshot of the verification of the Icon changing color if the text is active.

A | Create the SearchState

A screenshot of the Search State enum, with two cases: Pending and Active.
Within the State folder under Models, create a new file called SearchState.swift and paste in the code below.

B | Add the animation time constant

A screenshot of how we added the time constant to the constants file.

In Constants.swift add the animation time constant. We recommend setting it to 0.67.

C | Create the animation functionality

A screenshot of the SearchBar animation functionality.

In the SearchBar folder, create a new file called SearchBar+Animations.swift and paste in the code found below.

D | Declare the search state and observer

A screenshot of the declaration of the search state variable and its underlying observer that changes the tint of the icon depending on its state.

In SearchBar.swift declare the search state variable and set it to pending as search is not initially active.

Within it, create a didSet property observer and depending on the value, alter the appearance of the icon to being inactive (searchPlaceholderGray) or active (black).

For more information on Property Observers, please consult the Swift Programming Language Guide in the link below and search for didSet.

E | Update the TextField delegate extension

A screenshot of our updated textfield delegate with an @objc func that allows us to listen to text changes, and depending on the text that's within the search bar, change the search bar is search state.

We need to a new function, of @objc type in the SearchBar+Textfield.swift, that will serve as a target for when the textfield updates. Within this function, depending on the text, update the search bar's search state to the relevant state.

The complete code for the textfield extension is provided below.

F | Add the target to the textfield

A screenshot of how we added a target to the textfield of its editingChanged event.

In order to listen to text changes, we must add a target to the textfield for the action editingChanged.

Step 12: Verify

A screenshot of the product of the tutorial.

Run your app and verify that it all works as expected. The checklist includes:

  • That the search bar appears with the placeholder text and color on launch.
  • That you can change the search text using the keyboard that appears when tapping on the search bar.
  • That the text that you type into the textfield has a different color (black) than the placeholder (searchPlaceholderGray).
  • That the search icon animates depending on whether the text is active (black) or not (searchPlaceholderGray).
  • That you can dismiss the keyboard by tapping the screen or pressing return.

Want to filter the displayed data?

To change the results that appear on the UICollectionView to match filtered data based on your search query, please follow the tutorial in the link below.

Any Questions ?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details