Auto Complete Tutorial for iOS: How To Auto Complete With Custom Values

Ray Wenderlich
Custom Auto Complete Demo Screenshot

Custom Auto Complete Demo Screenshot

When a user is entering data into a text field, it’s often nice to have the ability to auto complete with custom values based on what the user is entering, saving them time. For example, when you enter a URL into Safari, it will show you past URLs you have entered that you can select to save time.

Here’s how to implement this on the iPhone. First, you need to have a NSArray containing all of the data that you want to provide as potential options for the user. In this example, we’ll use an NSMutableArray of pastURLs, and every time the user browses to a URL we’ll add it to the array.

Next, we’ll need to create a view to display the URLs that the user can select from. One good way of doing this is just to create a table view below the input field that lists all of the potential options. This table view can appear only when the user is typing data into the text field, and can be hidden the rest of the time.

autocompleteTableView = [[UITableView alloc] initWithFrame:
    CGRectMake(0, 80, 320, 120) style:UITableViewStylePlain];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.hidden = YES;  
[self.view addSubview:autocompleteTableView];

Next, we need to know when the text field is being edited so we can display the table view, and make sure the appropriate elements are in the table view. A good way to get notification that the text field is being edited is by registering your view controller as a UITextFieldDelegate and implementing the shouldChangeCharactersInRange protocol. Here’s how we’ll do it:

- (BOOL)textField:(UITextField *)textField 
    shouldChangeCharactersInRange:(NSRange)range 
    replacementString:(NSString *)string {
  autocompleteTableView.hidden = NO;
 
  NSString *substring = [NSString stringWithString:textField.text];
  substring = [substring 
    stringByReplacingCharactersInRange:range withString:string];
  [self searchAutocompleteEntriesWithSubstring:substring];
  return YES;
}

We want the table view to only show up the elements in our array that match the substring that the user has typed so far. So in our case we need to filter the pastURLs array by choosing the elements that start with the substring, and have the table view display those entries. Here’s how we’ve done this:

- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
 
  // Put anything that starts with this substring into the autocompleteUrls array
  // The items in this array is what will show up in the table view
  [autocompleteUrls removeAllObjects];
  for(NSString *curString in pastUrls) {
    NSRange substringRange = [curString rangeOfString:substring];
    if (substringRange.location == 0) {
      [autocompleteUrls addObject:curString];  
    }
  }
  [autocompleteTableView reloadData];
}

The table view just shows the contents of the autocompleteUrls, and that’s all there is to it! If you’d like to check this out for yourself, here’s a sample project.

Ray Wenderlich

Ray is an indie software developer currently focusing on iPhone and iPad development, and the administrator of this site. He’s the founder of a small iPhone development studio called Razeware, and is passionate both about making apps and teaching others the techniques to make them.

When Ray’s not programming, he’s probably playing video games, role playing games, or board games.

User Comments

10 Comments

  • Excellent stuff very useful for all of the ios developers
    shashirbabu
  • Great post, but I have a question.

    When I click on Search using the UISearchBar Search button, the delegate method 'shouldChangeTextInRange' is being called. Is it supposed to do this?
    ngoan
  • This is a good start, but how do we set the textfield with an option choosen by a user who clicks on a cell?

    I'm also having the issue only seeing hte auto-complete with the items I already entered. It doesn't seem to want to show options based on the predefined MS array.
    doomstrike
  • Excellent tutorial! :) 1 question, how do I give an autosuggest for words typed after a space? the words before and after the space come from the same array. for example, search for 'g', say, 'google' comes up as a suggestion, then I give a space, and type, 'b', say, 'bing' comes up as a suggestion in the same UITextField. Just an idea would help, I can manage the code :)
    Vittal
  • This is excellent!

    Just wondering how to implement with a UITableView from a single UITextField within a ViewController that has several UITextFields. I'm trying to autocomplete from a plist of guitar models within the app. The autocomplete works but I only know this from running it on the simulator and using my laptop keyboard for input. However, the iPhone keyboard does not appear. Presumably, because the custom input view is not the first responder. I've tried [self resignFirstResponder] and [modelField becomeFirstResponder] in

    - (BOOL)textField:(UITextField *)textField
    shouldChangeCharactersInRange:(NSRange)range
    replacementString:(NSString *)string

    But apparently there is something I don't understand about presenting from a custom input view. Also, how to make it exclusive to just the one UITextField.

    Any help would be greatly appreciated.

    Great site! what a wealth of info!
    americanguitar
  • FYI: I made a UITextField subclass called HTAutocompleteTextField (https://github.com/hoteltonight/HTAutocompleteTextField) that follows this a similar approach, but does the autocompletion in-line. Thanks for the tutorial!
    donutzeatpeople
  • Can you please post a new tutorial updated for iOS 7 in a UITextView?
    Thanks!
    jamal
  • Another amazingly helpful tutorial, thanks!
    SJTriggs
  • Hi Guys, can you please update this for SWIFT
    Thanks
    Benj
  • Like Benj, I'd loove to see this for swift.
    santiagoprietoe

Other Items of Interest

Ray's Monthly Newsletter

Sign up to receive a monthly newsletter with my favorite dev links, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

Vote for Our Next Tutorial!

Every week, we alternate between Gaming and Non-Gaming tutorial votes. This week: Non-Gaming!

    Loading ... Loading ...

Last week's winner: How to Make a Simple 2D Game with Metal.

Suggest a Tutorial - Past Results

Hang Out With Us!

Every month, we have a free live Tech Talk - come hang out with us!


Coming up in November: Swift, Functional Programming, and the Future of Objective-C.

Sign Up - October

Our Books

Our Team

Tutorial Team

  • Pietro Rea
  • Dominik Hauser

... 53 total!

Update Team

  • Ray Fix
  • Zouhair Mahieddine

... 14 total!

Editorial Team

... 22 total!

Code Team

  • Orta Therox

... 3 total!

Subject Matter Experts

  • Richard Casey

... 4 total!