How To Implement Search Bar in iOS 7 Using Storyboard

129 Flares 129 Flares ×

Editor’s note: Like some of the programming tutorials, you may find the search bar tutorial no longer works in Xcode 5 and iOS 7. We’ve rewritten the tutorial to make it compatible with the latest version of Xcode. On top of that, we enhance the tutorial with custom table cell.

Enter the search bar tutorial.

In most of the iOS apps using table view, it is common to have a search bar at the very top of the screen. How can you implement a search bar for data searching? In this tutorial, we will see how to add a search bar to the recipe app. With the search bar, we’ll enhance the recipe app to let users search through the recipe list by specifying a search term.

Well, it’s not difficult to add a search bar but it takes a little bit of extra work. As usual, we’ll walk you through the concept and implementation by building a sample app. As our focus is on the search bar implementation, you can download this project template to start with. The template is similar to the app we built in the tab bar tutorial.

iOS 7 Search Bar

Understanding Search Display Controller

You can use search display controller (i.e. UISearchDisplayController class) to manage search in your app. A search display controller manages display of a search bar and a table view that displays the results of a search of data.

When a user starts a search, the search display controller will superimpose the search interface over the original view and display the search results. Interestingly, the results are displayed in a table view that’s created by the search display controller.

Search Result Table View

Search Result Table View

Like other view controllers, you can either programmatically create the search display controller or simply add it into your app using Storyboard. In this tutorial, we’ll use the later approach.

Adding a Search Display Controller in Storyboard

In Storyboard, drag and add the “Search Bar and Search Display Controller” right below the navigation bar of Recipe Book View Controller. If you’ve done correctly, you should have a screen similar to the below:

Adding Search Display Controller

Adding Search Display Controller

Before proceeding, try to run the app and see how it looks. Without implementing any new code, you already add a search bar. Tapping the search bar will bring you to the search interface. However, the search is not working yet.

Search Bar in Table View App (but it’s not working yet)

Search Bar in Table View App (but it’s not working yet)

Why Search Results Show All Recipes?

As mentioned earlier, the search results are displayed in a table view created by the search display controller. When developing the recipe app in earlier tutorial, we implemented the UITableViewDataSource protocol so as to tell the table view the total number of rows to display and the data in each row.

Like UITableView, the table view bundled in the search display controller adopts the same approach. According to the official documentation of UISearchDisplayController, here are the available delegates that let you interact with the search result and search bar:

  • The search results table view’s data source, which is needed to provide the data for search result table.
  • The search result table view’s delegate, which is used to respond to the user’s selection of a search item.
  • The search display controller’s delegate, which responds to the events such as when the search starts or ends and when the search interface is displayed or hidden.
  • The search bar’s delegate, which is responsible for responding to changes in the search criteria.

Generally, the original view controller is used as the source object for the search results data source and delegate. You do not need to manually link up the data source and delegate with the view controller. As you insert the search bar into the view of Recipe Table View Controller, the appropriate connections for the search display controller are automatically configured. You can right click on the “Search Display Controller” icon in the dock to reveal the connections.

Search Display Controller Connections

Search Display Controller Connections

Both table views (i.e. the table view in recipe table view controller and the search result table view) shares the same view controller to handle data population. If you refer to the code, these are the two methods being invoked when displaying table data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [recipes count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomTableCell";
    RecipeTableCell *cell = (RecipeTableCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   
    // Configure the cell...
    if (cell == nil) {
        cell = [[RecipeTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
   
    // Display recipe in the table cell
    Recipe *recipe = [recipes objectAtIndex:indexPath.row];
    cell.nameLabel.text = recipe.name;
    cell.thumbnailImageView.image = [UIImage imageNamed:recipe.image];
    cell.prepTimeLabel.text = recipe.prepTime;

    return cell;
}

This explains why the search results show a full list of recipes regardless of your search term.
But why is the height of table row in search result table different from that in the recipe table? The original recipe table view was designed in storyboard. We set the height of the prototype cell right within the storyboard. The table view in the search display controller, however, has no idea about the change of cell height. To fix it, we have to change the row height programmatically. Add the following code into RecipeTableViewController.m:

1
2
3
4
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 71;
}

You can change the row height by implementing the tableView:heightForRowAtIndexPath: method of the UITableViewDelegate protocol. Here, we set the height to 71 points.
If you compile and run the app again, the table row in the search result should look better now. Yet, the search still doesn’t work and this is what we’re going to discuss in the next section.

Search Result after row change

Implementing Search Filter

Obviously, to make the search work, there are a couple of things we have to implement/change:

  1. Implement methods to filter the recipe names and return the correct search results
  2. Change the data source methods to differentiate the table views. If the tableView being passed is the table view of Recipe Table View Controller, we show all recipes. On the other hand, if it’s a search result table view, only the search results are displayed.

First, we’ll show you how to implement the filter. Here we have an array to store all recipes. We create another array to store the search results. Let’s name it as “searchResults”.

1
2
3
4
5
@implementation RecipeTableViewController
{
    NSArray *recipes;    
    NSArray *searchResults;
}

Next, add a new method to handle the search filtering. Filtering is one of the common tasks in iOS app. The straightforward way to filter the list of recipes is to loop through all the names and filter the result with the if-statement. There is nothing wrong with such implementation. But iOS SDK offers a better way known as Predicate to handle search queries. By using NSPredicate, which is an object representation of a predicate, you write less code. With just two lines of code, it searches through all recipes and returns the matched results. Add the following code to RecipeTableViewController.m:

1
2
3
4
5
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
    searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}

Basically, a predicate is an expression that returns a Boolean value (true or false). You specify the search criteria in the format of NSPredicate and use it to filter data in the array. As the search is on the name of recipe, we specify the predicate as “name contains[c] %@”. The “name” refers to the name property of the Recipe object. NSPredicate supports a wide range of filters including:

  • BEGINSWITH
  • ENDSWITH
  • LIKE
  • MATCHES
  • CONTAINS

Here we choose to use the “contains” filter. The operator “[c]” means the comparison is case-insensitive.
With the predicate defined, we use the filteredArrayUsingPredicate: method of NSArray that returns a new array containing objects that match the specified predicate.

To learn more about Predicate, check out Apple’s official documentation (https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/predicates.html).

Implementing Search Display Controller Delegate

Now we’ve created a method to handle the data filtering. But when should it be called? Apparently the filterContentForSearchText: method is invoked when user keys in the search term. The UISearchDisplayDelegate protocol defines a shouldReloadTableForSearchString: method which is automatically called every time when the search string changes. Therefore implement the following method in the RecipeTableViewController.m:

1
2
3
4
5
6
7
8
9
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
            scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                objectAtIndex:[self.searchDisplayController.searchBar
                selectedScopeButtonIndex]]];
   
    return YES;
}

When user keys in the search term in the search bar, this method is invoked automatically with the specified search term. We then call up the filterContentForSearchText: method to do the search.

Displaying Search Results

The last part of the puzzle is to display the search result in the table view of search display controller. As explained earlier, we have to change the data source methods to differentiate the table view in Recipe Table View Controller and the search result table view. Here are the updates of the two data source methods (changes are highlighted in bold):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];
   
    } else {
        return [recipes count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomTableCell";
    RecipeTableCell *cell = (RecipeTableCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   
    // Configure the cell...
    if (cell == nil) {
        cell = [[RecipeTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
   
    // Display recipe in the table cell
    Recipe *recipe = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        recipe = [searchResults objectAtIndex:indexPath.row];
    } else {
        recipe = [recipes objectAtIndex:indexPath.row];
    }
   
    cell.nameLabel.text = recipe.name;
    cell.thumbnailImageView.image = [UIImage imageNamed:recipe.image];
    cell.prepTimeLabel.text = recipe.prepTime;

    return cell;
}

The comparison is pretty straightforward. You can simply compare the tableView object in the data source methods against the searchResultsTableView of the search display controller. If the comparison is positive, we display the search results instead of all recipes.

Cool! It Works!

Once you complete the above changes, test your app again. Now the search bar should work properly.

Recipe app with search

Handling Selection in Search Results

Despite the search works, it doesn’t respond to your selection correctly. No matter what the search results are, the app always displays “Egg Benedict” in the detail view.

Referring to the prepareForSegue: method, we use the indexPathForSelectedRow: method to retrieve the indexPath of the selected row. As mentioned earlier, the search results are displayed in a separate table view. But in our original prepareForSegue: method, we always retrieve the selected row from the table view of Recipe Book View Controller. That’s why we got the wrong recipe in detail view. To make the selection of search results properly, we have to tweak the prepareForSegue: method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = nil;
        Recipe *recipe = nil;
       
        if (self.searchDisplayController.active) {
            indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
            recipe = [searchResults objectAtIndex:indexPath.row];
        } else {
            indexPath = [self.tableView indexPathForSelectedRow];
            recipe = [recipes objectAtIndex:indexPath.row];
        }
       
        RecipeDetailViewController *destViewController = segue.destinationViewController;
        destViewController.recipe = recipe;
    }
}

We first determine if the user is using search by using a built-in active property in UISearchDisplayController. In case of search, we retrieve the indexPath from searchResultsTableView and get the recipe from the searchResults array. Otherwise, we just get the indexPath from the table view of Recipe Table View Controller.

That’s it. Run the app again and the search selection should work as expected.

Recipe app displays the correct recipe in detail view

Summary

By now, you should know how to implement a search bar in iOS app. In this tutorial, we made the Recipe app even better by enhancing it with the search feature. The search feature is particularly important when you need to display tons of information in table view. So make sure you understand the materials we’ve discussed in this tutoral. Otherwise, start over and work on the project again.

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

What do you think about the tutorial? Leave me comment and share your thought. There are more programming tutorials in our free iOS course. Don’t miss it!

You May Like These:

Get Free Chapters of Our Swift Book

Beginning iOS 8 Programming with SwiftIf you want to create an app but don't know where to begin, this book covers the whole aspect of Swift programming and iOS 8 development and shows you every step from an idea to a real app on App Store. This book features a lot of hands-on exercises and projects. You will first create a simple app, then prototype an app idea, and later add some features to it in each chapter, until a real app is built. Want to learn more? Check it out here and get three free chapters.


  • bader

    Thank you .
    Regards
    bader n m

  • Sejersbol

    Nice! But I can’t get it to work with sections. Keep getting all the search results under each and every section…

    • Adam Barnes

      Did you have any luck with sections? I have been trying for days!

  • ramesh

    Can u tell me….how to implement uisearchdisplaycontroller to uicollectionview

    • lucas

      I’m having the same problem

  • Stefano

    Hi, when I drag the search bar with display controller then when I click the search bar the keyboard appears and overshadows my searchbar as shown in the image. Does it happen to someone else? What’s the solution for this?
    thx for your help

    • lucas

      yup this happens to me too. I have no idea what to do

      • Maya

        Try using UITableViewController instead of UITableView

      • John

        I have the the same problem before. Then I fixed as followings:

        – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

        {

        . . .

        if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:recipeIdentifier];

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        }

        . . .

        }

        Note: Use UITableViewCellStyleSubtitle, not the default style

    • Yan

      I also encountered this issue. Now I have fixed it. The reason was that when I drag the search bar to add it in, I didn’t put it at the correct place. You must make sure that the search bar is completed below header, and completely above the prototype cell. Hope it helps.

  • Pingback: implementare una Search Bar e Search Display Controller con la Storyboard | I PREDATORI DELL'ARCA PERDUTA()

  • Gabriel

    Hi, I can’t find search display controller in the toolbox??? I used xcod 5.02

  • Arif Fikri

    You are super awesome it works.

    For those who have error : dequeue a cell with identifier ……..bla bla bla.

    plz change

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    into

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    • Quân Chùa

      i have this problem and i couldnt solve it til i saw your comment.Thanks very much.You save my life….

    • QuenellePlus

      genius… <3

    • Gustavo Ramón

      VERY VERY NICE!!!

      THANK YOU!

    • Marcelly Luise

      Wooow! Thanks, Simon! :D And Thanks so much, Arif! :)

    • Atif Khan

      In the first statement you are using tableview instance provided as argument and the other is you are using instance you declare outside in the self object.
      Only possible reason first statement have not worked i you might not have registered cell with this id to the table instance passed in delegate method.
      For example in search controller, tableview instance is different than the table you have created. If you have created cell in storyboard or registered it to self.tableview manually. You should fix this, otherwise you are sending cell owned by one tableview to another tableview.

  • Sidney Leuson

    tengo problemas con el Search Bar y Search Display lo adiciono a un table view, pero no me filtra, este es el código que estoy utilizando, agradezco si me pueden ayudar.

    • ankit

      what we have to do if we does not create new Receipe class, instead we want controller to be display all information (label1+label2+image) on searchResults.

  • Terrance Shaw

    Absolutely awesome tutorial, per the norm. Thank you guys!

  • Ioannis Gman

    great tutorial

    just one question

    how do we make part of the words in detail view bold or italic or change paragraph if al data is taken from a plist file?

  • Pingback: IOS: UITableView with search: displayController not selectable? | QueryPost.com()

  • Евгений Онянов

    Why with metod not working:

    – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSString *CellIdentifier = @”MyCell”;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.textLabel.text = [_array objectAtIndex:indexPath.row];
    return cell;
    }

    But that metod working:

    – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    {
    static NSString *CellIdentifier = @”MyCell”;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text = [_array objectAtIndex:indexPath.row];
    return cell;
    }

    Sorry for my English…

    • Atif Khan

      Because search table is not registered with any cell, in second code you are creating cell if not found so it works fine there.

  • Marco Boldetti

    This tutorial a lot interesting!!! Thank you!!!

  • Adam Barnes

    As said below, a great addition to this would be sections, can anyone help with this?

  • MrPomfi

    Is it possible to add a scope bar not only to search for the recipe but also search for the ingredients?
    How can i choose the source of the search?

    thanks a lot for your help!

  • Guilherme

    Thank you soooo much for this series of tutorials for IOS! You are really amazing! I hope that I learn a lot with it… I really would like to have some apps runnings in AppStore (and make some money with it, lol)!

  • Joshua C

    Awesome tutorial! Thanks!

  • ohdowload

    hello there, i successfully follow this tutorial and it runs perfectly on my app. but i’m wondering why did – (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope method doesn’t appear automatically when i start typing?

    • Quân Chùa

      i have the same problem.I have no idea about it.DId you solve it ? If yes please point it out for me.Thanks alot

      • ohdowload

        I figured it out. i think it happens because we didn;t include UISearchDisplayDelegate on .h file.

  • Hesham Elsherif

    how to make navigation bar not overlaps the search bar please
    help me

  • Quân Chùa

    Could anyone explain to me why having the difference between self.tableView and tableView

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    vs

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    the first statement didnt work.

    • Atif Khan

      In the first statement you are using tableview instance provided as argument and the other is you are using instance you declare outside in the self object.
      Only possible reason first statement have not worked i you might not have registered cell with this id to the table instance passed in delegate method.
      For example in search controller, tableview instance is different than the table you have created. If you have created cell in storyboard or registered it to self.tableview manually. You should fix this, otherwise you are sending cell owned by one tableview to another tableview.

  • Charles Miller

    So, I have a rather dumb question which judging by the age of this article may not be answered. I just recently started TRYING to learn to program with the iPhone using xcode 5 & obj-c. With this tutorial I noticed that it limits how many items can show up on screen. Is there a way to make it display more than 20/25 items? Thanks!

  • kmanu

    Can anyone tell me how to implement this when fetch data from Core Data using NSFetchedResultController ?

    Thanks

  • Mike

    Great tutorial. I’ve spend many hours trying to figure out how to have a filtered search result go to a specific viewcontroller? I’ve been able to get items on the non-filtered list to go to a specific viewcontroller using the if (indexPath.row == 1) under the tableview didDeselectRowAtIndexPath. Any suggestions would be greatly appreciated!

  • Behinder

    For me not working :( It looks self.searchDisplayController.searchResultsTableView is never triggered :(

  • Mustafa Kuru

    Hi,
    thank you for your tutorials.

    i didn’t implement this part on existing code and it didn’t let to display search results.
    after debug i saw that the both tableViews (self.tableView and searchResultsTableView) have different id’s.

    in this case returns the following condition always false.
    if (tableView == self.searchDisplayController.searchResultsTableView)

    I solved it checking if searchDisplayController is active and so works for me.
    if (self.searchDisplayController.active)

  • Beccy

    Hi,

    I get an error code when i tap on the search bar before adding in any programming behind it at all, when it should just be not filtering the table.

    I continued any way and got the same error after following this tutorial completely. This time, it works unless you use the search bar, which looks normal and functioning until you type in any letter, then it crashes and gives the same error code.

    Any ideas or help would be awesome, because i’ve followed lots of tutorials for search bars and they all cause the same problem!

    It brings this up:

    @autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([_AppDelegate class])); }
    }

    and the error says this:

    Cannot find executable for CFBundle 0xa1d32d0 (not loaded)

    2014-07-02 07:16:47.856 Beans on Toast v3[1892:60b] *** Assertion failure in -[UISearchResultsTableView _configureCellForDisplay:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2935.137/UITableView.m:6509

    2014-07-02 07:16:47.913 Beans on Toast v3[1892:60b] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:’

    *** First throw call stack:

    (

    0 CoreFoundation 0x018171e4 __exceptionPreprocess + 180

    1 libobjc.A.dylib 0x015968e5 objc_exception_throw + 44

    2 CoreFoundation 0x01817048 +[NSException raise:format:arguments:] + 136

    3 Foundation 0x011764de -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116

    4 UIKit 0x00347d7f __53-[UITableView _configureCellForDisplay:forIndexPath:]_block_invoke + 426

    5 UIKit 0x002bc81f +[UIView(Animation) performWithoutAnimation:] + 82

    6 UIKit 0x002bc868 +[UIView(Animation) _performWithoutAnimation:] + 40

    7 UIKit 0x00347bd0 -[UITableView _configureCellForDisplay:forIndexPath:] + 108

    8 UIKit 0x0034f13d -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 442

    9 UIKit 0x0034f1f3 -[UITableView _createPreparedCellForGlobalRow:] + 69

    10 UIKit 0x00330ece -[UITableView _updateVisibleCellsNow:] + 2428

    11 UIKit 0x003456a5 -[UITableView layoutSubviews] + 213

    12 UIKit 0x002c5964 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355

    13 libobjc.A.dylib 0x015a882b -[NSObject performSelector:withObject:] + 70

    14 QuartzCore 0x03c8245a -[CALayer layoutSublayers] + 148

    15 QuartzCore 0x03c76244 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380

    16 QuartzCore 0x03c84885 -[CALayer(CALayerPrivate) layoutBelowIfNeeded] + 43

    17 UIKit 0x002b8026 -[UIView(Hierarchy) layoutBelowIfNeeded] + 595

    18 UIKit 0x002b7dcd -[UIView(Hierarchy) layoutIfNeeded] + 74

    19 UIKit 0x0061d40a -[UISearchDisplayControllerContainerView setFrame:] + 108

    20 UIKit 0x00615540 -[UISearchDisplayController setActive:animated:] + 11941

    21 UIKit 0x0e3b2a87 -[UISearchDisplayControllerAccessibility(SafeCategory) setActive:animated:] + 141

    22 UIKit 0x006187a4 -[UISearchDisplayController searchBarTextDidBeginEditing:] + 298

    23 UIKit 0x00537a74 -[UISearchBar(UISearchBarStatic) _searchFieldBeginEditing] + 113

    24 libobjc.A.dylib 0x015a882b -[NSObject performSelector:withObject:] + 70

    25 UIKit 0x002583b9 -[UIApplication sendAction:to:from:forEvent:] + 108

    26 UIKit 0x00258345 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61

    27 UIKit 0x00359bd1 -[UIControl sendAction:to:forEvent:] + 66

    28 UIKit 0x00359fc6 -[UIControl _sendActionsForEvents:withEvent:] + 577

    29 UIKit 0x0097eb4e -[UITextField willAttachFieldEditor:] + 685

    30 UIKit 0x00360b85 -[UIFieldEditor becomeFieldEditorForView:] + 927

    31 UIKit 0x0097574f -[UITextField _becomeFirstResponder] + 160

    32 UIKit 0x0053ad48 -[UISearchBarTextField _becomeFirstResponder] + 98

    33 UIKit 0x003bc0b5 -[UIResponder becomeFirstResponder] + 400

    34 UIKit 0x002b760e -[UIView(Hierarchy) becomeFirstResponder] + 114

    35 UIKit 0x0097506a -[UITextField becomeFirstResponder] + 51

    36 UIKit 0x005fbbff -[UITextInteractionAssistant(UITextInteractionAssistant_Internal) setFirstResponderIfNecessary] + 197

    37 UIKit 0x005fe1d2 -[UITextInteractionAssistant(UITextInteractionAssistant_Internal) oneFingerTap:] + 2640

    38 UIKit 0x005f24f4 _UIGestureRecognizerSendActions + 230

    39 UIKit 0x005f1168 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 383

    40 UIKit 0x005f2bdd -[UIGestureRecognizer _delayedUpdateGesture] + 60

    41 UIKit 0x005f613d ___UIGestureRecognizerUpdate_block_invoke + 57

    42 UIKit 0x005f60be _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 317

    43 UIKit 0x005ec7ac _UIGestureRecognizerUpdate + 199

    44 UIKit 0x00297a5a -[UIWindow _sendGesturesForEvent:] + 1291

    45 UIKit 0x00298971 -[UIWindow sendEvent:] + 1021

    46 UIKit 0x0026a5f2 -[UIApplication sendEvent:] + 242

    47 UIKit 0x00254353 _UIApplicationHandleEventQueue + 11455

    48 CoreFoundation 0x017a077f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15

    49 CoreFoundation 0x017a010b __CFRunLoopDoSources0 + 235

    50 CoreFoundation 0x017bd1ae __CFRunLoopRun + 910

    51 CoreFoundation 0x017bc9d3 CFRunLoopRunSpecific + 467

    52 CoreFoundation 0x017bc7eb CFRunLoopRunInMode + 123

    53 GraphicsServices 0x0380b5ee GSEventRunModal + 192

    54 GraphicsServices 0x0380b42b GSEventRun + 104

    55 UIKit 0x00256f9b UIApplicationMain + 1225

    56 Beans on Toast v3 0x00004fed main + 141

    57 libdyld.dylib 0x01e5e701 start + 1

    58 ??? 0x00000001 0x0 + 1

    )

    libc++abi.dylib: terminating with uncaught exception of type NSException

    (lldb)

  • Bruno Santos

    Hello, great tutorial!

    I’ve done it programatically and, I don’t know why, after the text in search bar is edited, the method cellForRowAtIndexPath is not being invoked. However, the numberOfRowsInSection is being invoked normally.

    This way, the table is never updated according to the text search.

    Does anyone know what is going on, and what should I do solve this?

    Thanks in advance!

  • Marc

    very nice Tutorial, thank you so much, best wishes from Germany

  • nura

    Great tutorial !! but I have a question, I followed your exact code but when I added more data to the array the controller prints only the the first 7 items (although I have added them the array :( ) how can I fix it :(?

  • Pingback: Adding a Search Bar to a Table View with Core Data()

  • Maksim
  • Hiren Patel

    Hi, your tutorial is awesome as always.
    I have a question, Can I implement these methods on UITextField?
    If not than How can I customize the UISearchBar as UITextField?
    Thanks in advance.

  • Joseph Richardson

    What about searching through a mutable array full of NSDictionaries?

  • Pingback: Table View search results not displaying correctly()

  • Vladimir

    Why can I have empty cells in search results instead of my custom prototype cells?
    Debugger shows, that cell is dequeued but all the outlets are nil..

  • Sergey Kolchanov

    Thank you very much for helpful tutorial. But can anyone explain me how to keep search bar on the top. For now it scrolls down with table cells.

  • D3pwnd

    Thanks! Awesome Tutorial.

  • Hanh Nguyen Van

    Please help me! I can’t check if I’m searching or not with this codes:

    -(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerLeftUtilityButtonWithIndex:(NSInteger)index // SWTableViewCell protocol
    {
    switch (index) {
    if (self.myTableView == self.searchDisplayController.searchResultsTableView)
    {
    NSLog(@”searching”);
    }else
    {
    NSLog(@”not search”);// always go this although i’m searching.
    }
    }
    }

    And it works but indexPath.row always equal to 0 although results have much more than one row.

    -(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerLeftUtilityButtonWithIndex:(NSInteger)index

    {

    NSIndexPath *indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];

    // or

    NSIndexPath *indexPath = [self.myTableView indexPathForSelectedRow];

    switch (index) {

    if (

    [self.searchDisplayController isActive])

    {

    NSLog(@”searching”);

    }else

    {

    NSLog(@”not search”);// always go this although i’m searching.

    }

    }

    }

    • Pascal

      Same problem, this does not work anymore with latest xcode.

  • John

    How is this different from the new iOS8 UISearchController Delegate? Can you create tutorial on that? Thanks!

  • Mickael

    Hi , if my data is in Parse , i can use this tuto to add search bar with sdk Parse ?

  • brandon

    I’m using xcode 6.1 and not able to get either the starter or final project to compile. The error I’m getting is : clang: erro: no such file or directory ‘/Users/brandonmc/Downloads/RecipeAppSearchBar/CustomTable/CustomTable-Prefix.pch; clang error no input files Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xtoolchain/usr/bin/clang failed with exit code 1.

    The .pch file I have in the project is RecipeApp-Prefix.pch.

    • Cathal Noster

      Me too on 6.1, did you ever solve this?

    • Pascal

      Same here…

  • reg

    Great tutorial. Unfortunately key methods used in this example have been depreciated in Xcode 6. Will you update this tutorial ???

  • Jillian O.

    Thanks! Made my life easier.

  • Lorenço Gonzaga

    Hi there! I bought your iOS 7 Course and really enjoyed. In the book there are two examples of this recipe app. This one that uses the SearchBar feature and other that uses Parse.com
    Could you guys give any help how to implement the SearchBar in the Parse.com example ? Considering not just me but other people who bought the course too, Im 100% sure that would help everybody. You guys can push as update via email or post the .zip project to the url of the dropbox Recipe Parse Part 2 example of the book. Thanx and cheers!

  • Francisco Javier Guadarrama

    RESPECT!!!!! thanks!!! really really Thanks!

129 Flares Twitter 29 Facebook 74 Google+ 20 LinkedIn 6 129 Flares ×