Search code examples
iosuipickerview

How to implement search within a UIPicker?


I have UIPicker that I need to write search mechanism for. The data that is feeding this picker is an array of strings. When the user enters the search string (I have a UISearchBar that handles that.) I would like to find all strings containing the search term. From the example below, it seems I need to write a predicate and then filter the array. The problem I am having right now is I don't know how to display the search results to the user. I tried assigning the result set back to the original array but that is not correct. Could someone suggest a technique for implementing searching of a UIPicker with a code example?

NSMutableArray* names = [NSMutableArray arrayWithObjects:@"Andy", @"Bart", @"Bob", nil]; 
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
NSArray* namesStartingWithB = [names filteredArrayUsingPredicate: predicate];

Solution

  • Here's a working project

    Remember your predicate is case sensitive. You used a lowercase b so it won't return any results. My solution is basically the same thing Joe suggested. I use two arrays. One array for the full dataset and then another array for the search result. The datasource for the picker is the partial array then I just reload the picker when I do a search.