Search using UITextField – Tutorial


Introduction to Search using UITextField – Tutorial:

Most of IOS developers implemented Search using UISearchBar but we can also use UITextField as a search bar. 

For swift version visit, Search using UITextField in swift3

Tutorial in objective C

You can check out UISearchBar implementation from below link

In this post,we will going to explain steps we followed to make our UITextField as UISearchBar. Advantage of using UITextfield over UISearchBar  is that UITextField offers much customization to your search interface. As shown in the picture, we are using UITextField as search bar. 

Implementation of code to implement search bar using UITextField:

To start using UITextField as search bar first in ViewDidLoad add notification observer for UITextField when some text gets caged in UITextfield.



In above code, we add observer with notification name  UITextFieldDidChangeNotification that fired our selector when user change text in UITextField. 

Now, its time to implement our method which we passed as selector in notification observer

Here we call our search method and passing our UITextField text as search parameter. We also implement delegate method to dismiss keyboard when user hit search button key on the keyboard.  We will implement textFieldShouldReturn delegate of UITextField and inside it resign our UITextField as first responder so that keyboard gets dismissed.



It’s time for most important part, we will perform search here inside our searchRecordsAsPerText method. This method will take string as input and we are already passing our search string. 

Please note

1) searchArray is an NSMutableArray allocated in ViewDidLoad method.

2) recordsArray is also NSMutableArray that contains all records coming from server and  we want to search it as it contains large number of records.

Inside our searchRecordsAsPerText: method, first we remove all object from searchArray. Then we implement foreach loop on recordsArray. We will use rangeOfString method to find out wether our search string matches with our dictionaries value for key @”TEXT”. If result range is greater then zero then string matched  successfully and we add the dictionary to searchArray. Lastly we load our UITableView to show searched results.



Please remove the observer in you viewDidDisappear method otherwise it will gets called when ever a Textfield start editing in your app means that this notification will get fired when ever user interact with UITextField or change text in UItextField