banner



How To Keep My Typing Search Of Address Bar

Quite often information technology'due south required from iOS applications to exist capable of performing search in specific data that is displayed in a tableview. Undoubtably, nigh of developers have faced that situation, and the most usual approach to that is to apply the default controls that the iOS SDK provides. Up to iOS 8, Apple tree was providing a special command for performing searches in tableviews named UISearchDisplayController. This controller, in conjunction with the UISearchBar was making possible to add search features quite easily in an application. All the same, this belongs to history at present.

Since iOS eight coming, things changed a bit. First of all, the UISearchDisplayController has been deprecated, even though it's provided equally an bachelor control in the Interface Architect'south controls drove in Xcode. A new controller named UISearchController has been given in its place. In spite of this change though, no visual command exists for information technology in the controls collection in Interface Builder; instead, it must be initialized and configured programmatically, simply this is a really piece of cake task, and y'all'll run into that later on.

Also all the above, there's some other interesting point regarding the searching in a tableview datasource. iOS SDK provides a predefined appearance for the search bar, and that bar is suitable in many cases. However, when the UI of the app is highly customized, then information technology'south quite possible the default search bar format not to fit in the whole look and feel of the app. In that case the search bar must be customized appropriately so equally to be a not-distinguishable role of the app ecosystem.

Then, having said all the to a higher place, it's fourth dimension to present before long what this tutorial is all most. I could say that through this text I'g aiming in 2 things: My first goal is to demonstrate how the new UISearchController presented in iOS viii can exist used then it's possible to search and filter data using the default iOS search bar. You'll see through the sample code we are almost to write that configuring information technology it'south an easy process, regardless the fact that a visual control in the Interface Architect doesn't exist.

My second goal is to show you how you can override the default search bar advent and customize it according to the app look and feel. As you'll run into adjacent, we have to bracket both the UISearchController and the UISearchBar classes, just the code we'll add to them is straightforward enough. Actually, the subclasses we'll implement in the post-obit parts will be made in a quite general way, and so y'all can reuse them in your projects as well.

At this point this introductory role comes to its end, and then let's get to run across beginning of all the demo app details, and so let'south bring information technology in life.

Demo App Overview

The following two images demonstrate our goals in this tutorial:

search-bar-demo-app

In the beginning i, y'all can meet the default search bar using the UISearchController that was introduced in iOS 8. In the second prototype, the custom bar has been customized. You are going to see how both can be achieved both in the upcoming parts, but first, let's say a few words about the project.

As commonly happens, you can download a starter project to work with. When y'all get it, open it in Xcode and navigate yourself around. As the final app is elementary, y'all won't observe much; at that place'southward one scene in the storyboard containing a tableview, the one that volition display our data, the search bar and the search results. Besides that, in the ViewController class y'all'll find a minimal implementation of the needed UITableView delegate and datasource methods.

The sample information for our demo application is going to exist a list with countries from all over the earth. In the project y'all will find a file named countries.txt being already at that place, so all we will have to do it to load its contents to an assortment and use them in code. The countries list was created in this website.

Our whole work in the next parts can be separated in three general steps:

  1. Initially, we'll load the sample data to the app, and so it's handy at any time later on when we'll need it.
  2. Nosotros'll implement the default search functionality using the new UISearchController.
  3. We'll subclass and customize the search controller and the search bar and then we change the default appearance.

So, having said that, allow'due south see each single pace in details.

Loading and Displaying Sample Data

We are going to get started by loading the contents of the countries.txt file into an assortment and so we have a datasource for our tableview. Likewise, we'll brandish the entire list of countries in information technology. Once we exercise so, we can totally focus on the search functionality we'll implement in ii different ways.

Our initial movement right before we load the contents of the file into an array, is to declare a few properties in the ViewController grade. So, nosotros'll be able to work using them straight. At the meridian of the class in the ViewController.swift file add the side by side three lines:

Let me explain a bit now. The dataArray array will contain the contents of the file, significant the listing of the countries that will be displayed in the tableview. Note that this array will be used as a datasource only when no searching is beingness performed. In case the user has started searching, so the filteredArray array will exist used equally the datasource, as it will contain but the countries matching to the search term. The actual assortment that should be used as a datasource for the tableview will exist specified past the value of the shouldShowSearchResults property. When it'southward true, and then the contents of the filteredArray will exist used; when information technology's false, the dataArray array volition be used instead.

Now, permit's load the data from the countries.txt file into the dataArray, so we can use it with our tableview. In the starter project there is an initial implementation of the tableview, just we're going to enrich it as nosotros proceed. We'll start coding a new custom function named loadListOfCountries(). Hither's what we'll practice here: At first we'll load all the file contents into a string, and and then we'll "intermission" that cord into an array based on the new line (enter) graphic symbol. The resulting array will be the original datasource for the tableview. Allow' run across information technology:

The above function has to be called, and obviously this will happen in the viewDidLoad(…) role:

We are ready at present to update a couple of the tableview methods. Initially allow's specify the number of rows that volition be returned depending on the used array:

Then, permit's specify the actual cell contents:

Now you can run the app for first time and see the countries listing appearing in the tableview. What we've done so far isn't something new or difficult, so let's go going by configuring the search controller and displaying the default search bar.

t41_3_countries_list

Configuring the UISearchController

In order to use the UISearchController and perform search in the tableview data, it's necessary to declare such a holding first. And so, in the top of the ViewController class just add the following line:

For our purpose we will implement a new custom office that nosotros'll name configureSearchController(). In it, we'll initialize the holding we alleged right above, and then we'll gear up a few properties of information technology. Actually, the search controller is a view controller having some additional special properties.

Ane of those properties is the searchBar which represents programmatically the search bar view that appears at the top of the tableview. Some of the backdrop nosotros'll prepare in the next method regard it also. The search bar view doesn't automatically appear to the tableview; we take to exercise that manually every bit you'll encounter side by side. There are many things one can configure in both the search controller and the search bar so the default controls tin be parameterized as much as possible. Detailed information yous'll discover here and hither.

Let'due south become started with the new part where we'll see almost 1 by one all the configuration we'll practice. At first, let's initialize the searchController:

Hither's an important detail: In our demo awarding the tableview that displays the search results exists in the same view controller that the search controller exists. However there are cases where the view controller displaying the search results is other than the i the search is being performed, and the search controller has to know that somehow. The just fashion is through the higher up initializer. When the nil value is passed every bit an argument, the search controller knows that the view controller that exists to is also going to handle and brandish the search results. In whatever other case the results view controller is a different one.

In that location are two ways that nosotros tin can use in club to be able to update the tableview with the search results every bit we type the search term. The first one is to use a delegate method of the search bar, and the 2d 1 is to make the ViewController class the delegate of the searchResultsUpdater property of the search controller. Nosotros'll see how the first approach is used afterwards when we'll write our own custom search controller, so allow'southward stick to the second style for now. By doing so, we accept to make the ViewController arrange to a specific protocol, named UISearchResultsUpdating. This protocol has been first-presented in iOS 8, and it does what I described exactly: Information technology updates the search results based on the search term we're typing. In that location'due south only i delegate method we'll have to implement, merely we'll exercise so later. For now, allow's include it in the protocols that our class already conforms to:

Back to our new function again, allow's go going by calculation the next line that will add i more piece to the puzzle:

Further than than, yous can add any other properties depending on your needs. For example, the post-obit one dims view while we're all the same typing the search term if it gets the true value:

Usually there's no reason to dim the view when the search controller exists in the same view controller with the results tableview. So, set the imitation value to the to a higher place belongings.

Let's deal a bit with the search bar now, and let's specify a placeholder text that will announced on it:

Also, let's make our class the delegate of the search bar so we tin use some delegate methods of it afterward on:

And hither's a pocket-size flim-flam needed to make the search bar get its proper size and be displayed in the tableview:

Displaying the search bar in the tableview requires the following line:

Here's the whole method in i identify:

At present go to the top of the grade and prefer the UISearchBarDelegate protocol every bit well:

Lastly, in the viewDidLoad() role permit's call the above one:

The above is what yous demand so you tin can display a search bar in a tableview using the brand new UISearchController. Now, we can continue and handle the search results. For now, don't mind about the errors Xcode is showing, they'll be gone one time we write the missing delegate functions.

Performing Search

Let's handle and brandish the search results now. This step has two parts. Firstly, search results tin be returned when a search term is typed in the search bar, and secondarily, when the search button in the keyboard is tapped. In the commencement example we'll filter the displayed countries listing as nosotros blazon. Also, this case isn't always mandatory to exist implemented, then if you demand to skip returning results while typing you're allowed to do. Notwithstanding showing search results when the Search push button in the keyboard is tapped is required, otherwise having a search bar in your tableview is totally pointless. In both cases the filteredArray array must become the datasource of the tableview, while when no searching is being performed the dataArray assortment is the default datasource co-ordinate to what we implemented earlier.

We take already used the shouldShowSearchResults property which defines the actual datasource of the tableview, merely so far we haven't written a single line of code to modify its value. Now, it'south fourth dimension to do and then, e'er depending on whether a search process is taking place or not.

With that in heed, let's begin by defining the following two UISearchBarDelegate consul methods. Every bit you'll see, with them we alter the to a higher place property's value and reload the tableview appropriately:

The first one makes the filteredArray the datasource of the tableview when we brainstorm searching. On the other hand, the second function makes the dataArray array the datasource when the Cancel button of the search bar is tapped.

The next step is to implement some other delegate method that will display the search results and will resign the search field from first responder one time the Search button in the keyboard gets tapped. Note that the if condition you'll meet next is useful in case yous determine to disable the real-time searching and you only want to display results after the Search button is tapped.

As you lot assume from all the in a higher place delegate methods, past setting the proper value to the shouldShowSearchResults flag and by reloading the tableview, we manage to display the proper data each time to our view controller.

All the above are cracking, but nonetheless there's a big piece missing here. Upward until now we haven't dealt with the filteredArray array at all, then the in a higher place delegate methods are not going to have the desired result. In the previous part we adopted the UISearchResultsUpdating protocol, and there I had said that there'southward just one delegate method that we have to implement. Well, in that method that yous tin see right next, nosotros filter the original data based on the typed search term, and the matching results are stored in the filteredArray assortment. Here information technology is:

Let's take a deeper wait at what is going on here. At first, we access and shop the typed search term in a local constant named searchString. We could have avoided doing this, simply it makes our work more convenient.

The centre of the above method is right next, where nosotros use the filter(…) method of the dataArray assortment. As its name says, it filters the data according to what we enquire from it in the closure body, and stores the matching elements to the filteredArray array. Each country string in the source array is represented by the country parameter value of the closure. This string is converted to a NSString object named countryText, and that's only because we want to brand use of the rangeOfString(…) method that the NSString class provides. That method checks if the searched term (the searchString value) exists in the current country, and if so it returns its range (NSRange) in the country cord. If the string we're searching for doesn't exist in the current country value, and then it returns a NSNotFound value. Every bit the closure expects a Bool value to be returned, all we have to practice is to return the comparison result betwixt the rangeOfString(…) return value and the NSNotFound value.

At the end, we reload the tableview data, so it displays the filtered countries. As yous understand, what I presented correct in a higher place is just an approach among many, and obviously it can be refined or modified with the functionality you desire each time.

At present run the application to test our new additions. Start typing a country name, and you lot'll run across the tableview get updated in real fourth dimension. Utilise both the search and cancel buttons, and see how the app reacts. At the end, make any modifications y'all wish to whatever we've done so far, so yous become a amend understanding over the discussed content upwards to at present.

At this signal, the first part of the tutorial is over. In the remaining sections you'll see how you can override the default behaviour of the search controller and the search bar, and how yous can customize it so it fits to the app'southward UI.

default search bar

The Custom Search Bar

Customizing the search controller and the search bar does non really consist of a hard procedure, equally all you lot have to do is to subclass both of them and write the custom functionality and logic that you wish. Actually, that'due south the procedure for every default beliefs you desire to override in iOS SDK classes, so whatever comes next is definitely something nosotros all have done in the by.

Nosotros'll begin the customization procedure by subclassing commencement the search bar (UISearchBar). Then, we'll use this custom search bar in the subclass of the search controller, and at the end nosotros'll use both of them in the ViewController class.

Initially we'll create a new file in Xcode, therefore become to the File > New > File… menu. In the template option, click to the Cocoa Touch Class in the Source category of the iOS department. In the side by side stride, gear up the UISearchBar class in the Subclass of: field, and set the CustomSearchBar name for the new grade as shown below:

t41_4_custom_search_bar_class

Get finished with the new file creation, and so select information technology to open it. We'll begin coding hither by creating a custom initializer. In that, we'll pass the desired frame, font, and text color of the search bar and search field, and later we'll utilize them to practice the customization. But prior to this, let's declare the next ii properties:

Now, let's come across the custom initializer:

As you lot run into, we gear up the parameter frame value equally the search bar frame, and we store both the font and the text color for later use.

Our side by side duty is to change the default search bar style using the next line:

This command results to a search bar with a translucent background and opaque search field. All the same, this is not enough, equally we want both the search bar and the search field to be opaque, and so information technology's possible to utilise the desired color to both and they look every bit one piece. Therefore, we'll use the next command to reach that:

After the above two additions, hither's once again the initializer:

Note: A search bar is not a single control that is parted only from a textfield (the search field). On the contrary, the search bar has a UIView view as a subview, and that view has ii of import subviews amid others: The search field (actually a subclass of the UITextField course), and the search field background view. To make it more clear, if yous type this in the following custom function:

… here's what you lot'll arrive the console:

t41_5_search_bar_subviews

Besides the custom initializer, we are required to add together one more:

Based on the to a higher place note and because that we want to admission the actual search field (the textfield of the search bar), let's write an auxiliary role that will return us the alphabetize of it in the search bar's subviews:

The above is simple, and in alignment to what I explained correct earlier. With that, nosotros're able to go along to the actual customization past overriding the drawRect(…) method of the course. In it, nosotros'll perform two distinct tasks: Nosotros'll access the search field and we'll alter it every bit nosotros desire, and then nosotros'll draw a custom line at the bottom side of the search bar.

Regarding the search field modifications, nosotros'll perform the side by side changes:

  1. Nosotros'll change information technology's frame and we'll brand it a bit smaller than the search bar's.
  2. Nosotros'll gear up the custom font.
  3. We'll set the custom text colour.
  4. We'll alter its groundwork color. This will match to the bar's tint color and we'll specify it in the next function. By doing that we'll manage to brand both the search bar and search field expect as one control (refer to the app overview section to see what our concluding goal is).

Permit's encounter all that in code now:

As you see, we also make utilize of the custom function nosotros implemented earlier.

Lastly, let'due south draw a line at the bottom side of the search bar. Actually nosotros'll practice two things: At starting time, we'll create a new bezier path with the line we want to depict. At second, we'll create a new CAShapeLayer layer to which nosotros'll set the bezier path, and we'll specify the line's color and width. Eventually, this line will be added as a sublayer to the search bar'south layer. Here we go:

Of course, yous can change both the line's colour and width according to your gustatory modality or needs. In any example, it's articulate how y'all can handle them.

At present the custom search bar is gear up. For the time beingness we are unable to test it, equally we're nevertheless missing the custom search controller, merely we'll implement information technology in the next part. The important affair here is the fact that all the give-and-take in this office shows you the proper way to customize the search bar and make it fit to your app'due south look and feel.

The Custom Search Controller

Our custom search controller will exist a subclass of the UISearchController form, and hither nosotros'll brainstorm working in a similar fashion to the last role. And then, initially create a new file as described previously, but this time make certain to prepare the UISearchController value in the Subclass of: field, and the CustomSearchController as the proper name of the new class:

t41_6_custom_search_controller_class

One time the file gets created, select it in the Projection Navigator to open it. At the top of the class declare a custom search bar property:

Next, nosotros'll create a custom initializer hither too. We'll provide it with the following 5 parameters:

  1. The search results view controller.
  2. The desired frame of the search bar.
  3. The search field font.
  4. The search field text color.
  5. The search bar tint color.

Here information technology is:

The configureSearchBar(…) is a custom function we'll implement correct away. As y'all assume from its name, in information technology nosotros'll do all the proper search bar configuration.

However, before we see that function, let's add two more than required init functions:

At present, let's configure the search bar. What we'll practice is uncomplicated, so permit'due south see it equally one piece:

As you see in the first line to a higher place, we make utilise of the custom initializer we created in the custom search bar. The rest is easy: Nosotros set the bar tint color of both the search bar (barTintColor) and its elements (tintColor), we "tell" it that nosotros don't want to display the bookmark push, and finally we enable the appearance of the cancel button. Of course, yous can change or add properties as per your demands.

Right now, the custom search controller is ready, even though we haven't adopted the UISearchBarDelegate to handle the search bar's delegate methods yet. We'll do so in the side by side section. However, nosotros're able to put our 2 new custom classes into action.

Back in the ViewController class, let's begin by declaring the next property at the top of the grade:

Adjacent, allow'south define a really unproblematic role to initialize the custom search controller, and specify the actual values for the frame, font and colors. Let's see information technology:

By initializing the custom search controller as shown above, we're sure that the specified arguments volition be passed to the custom search bar besides. Farther than that, we set a placeholder text for the search field, and then we set it to the tableview header to brandish it.

In the viewDidLoad() method now, nosotros accept to exercise two things: To phone call the above function and to prevent the default search controller from actualization:

At the moment our custom controls won't work as expected, meaning that no searching will be performed. We'll set up that in the next role. Nevertheless, now we are able to see the custom search bar, so launch the app to do that.

Custom Search Bar

Performing Search Using The Custom Search Controller

The custom search controller class is going to exist the consul of the custom search bar, and that means that we'll command all the search-related functionality in the CustomSearchController grade. Then, by implementing a custom protocol and adopting the delegation pattern, nosotros'll let through custom consul methods the ViewController class to handle the search results in a similar way we saw previously in the normal search controller.

Then, allow'south bring all the to a higher place in life, and start of all open the CustomSearchController.swift file. Get in the configureSearchBar(…) function, and add the side by side line:

Having fabricated the CustomSearchController course the delegate of the custom search bar, allow'southward go to the class header line to adopt the UISearchBarDelegate:

Don't forget to adopt the UISearchBarDelegate protocol in the class header line:

Now, permit's create a custom protocol with the following delegate functions (add the next lines before the CustomSearchController class):

I recollect information technology's pointless to explain what each i is for, as their names are self-explanatory. At the top of the CustomSearchController class allow'due south declare a delegate property every bit shown below:

At this point nosotros tin can add the missing search bar delegate functions, and call each time the proper delegate function of the CustomSearchControllerDelegate. Allow'due south showtime with the one that is called when the editing begins in the search field:

When the search button in the keyboard gets tapped:

When the Cancel button in the search bar is tapped:

And finally, when the search text gets inverse:

All the above functions will inform the ViewController class when the search begins, ends, or the search cord is inverse. At present, open the ViewController.swift file, and initially go straight to the configureCustomSearchController() function. In it, add the next line:

In the form header line, adopt the CustomSearchControllerDelegate protocol and so we tin implement its consul functions:

Lastly, let'due south come across the implementations. In the next functions, we'll exist taking the exact aforementioned deportment as nosotros did for the normal search controller. Let's go for them:

Brainstorm of searching:

Tap on the search button:

Tap on the cancel button:

Changes on the search text:

The app now is fully functional and it's using our custom search controller and search bar. You can go and give it a final try.

custom_search_bar

Summary

Taking a quick look at what we've washed in all the previous parts of this tutorial, information technology's easy to understand that working either with the UISearchController that iOS viii provides, or by customizing the search bar and the search controller, the result is always the same: You can add together search functionality in your apps pretty fast. If your application doesn't demand UI modification then you lot tin can stick to the default advent of the search bar. If y'all demand though to apply some custom touches, then you can do that too, as now you lot know the way. Hopefully this tutorial will be your guide in your time to come implementations, and with that I think it's time to go out you. Happy searching!

For reference, you lot can download the complete Xcode project here.

Source: https://www.appcoda.com/custom-search-bar-tutorial/

Posted by: millerandised1956.blogspot.com

0 Response to "How To Keep My Typing Search Of Address Bar"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel