While working on the Cashbase iPhone project ( CashbaseHq ), I found myself longing for an autocomplete feature, but could not find anything on the web. So I decided to build my own. The functionality is identical to the way autocomplete is used on the web. Upon typing a text in the text field, a list with suggestions appears bellow it. Selecting an item from the suggestions list will hide the list and add the word in the textfield.
This is how it looks in our app (for space reasons we have designed the suggestion list to be displayed above the field that requires autocomplete, but you can easily display it below – just see the demo app)
How to use:
Import the Autocomplete.h file
Prepare the target UITextField for autocomplete by disabling the iPhone’s default autocomplete feature. You usually do this in the viewDidLoad method.
//disable the iPhone's default autocomplete feature textField.autocorrectionType = UITextAutocorrectionTypeNo; //create the Autocomplete class and initialize it with some data autocomplete = [[Autocomplete alloc] initWithArray:[[NSArray alloc] initWithObjects:@"apples", @"oranges", @"bananas", @"peaches", @"grapes", @"blackberries", @"strawberies", @"watermelons", @"mangos", @"pears", @"lemons", nil]];
Now, when the text in the text field has changed (ie: in the EditingChanged handler), just call the GetSuggestions method, which will return an array of strings that match the parameter passed
NSArray *suggestions = [autocomplete GetSuggestions:textField.text];
You can do whatever you want with these suggestions, I displayed them in a table view and when the user taps a cell, the text is added to the text field (see attached demo project)