Implement a autocomplete textfield Objective C

user2720097 picture user2720097 · May 13, 2014 · Viewed 8.3k times · Source

I am starting to work with text fields, and I want to implement a functionality with a custom autocomplete.

In a lot of blogs and answer, implement it with UITables to show the autocomplete, but I do not need this, I need to create a autocomplete like a iPhone function, where show a pop out with the filter but only with my array of words.

For example.

my_array = @{"apple","banana","pear","orange","berry"}

When I type "app" the text field only need to show me "apple" but not complete the text in the text field, should show the pop up with the autocomplete.

Something like this but only with my array.

enter image description here

Answer

Mindeater picture Mindeater · May 13, 2014

You can build this behaviour yourself using the UITextFieldDelegate methods ( implement the delegate in your UIView

@interface someViewController : UIViewController <UITextFieldDelegate> 

In doing this you get access to whatever the user has typed in

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

Where you can compare it to the items in your array and display another UIView or a custom button that when selected populates your text field.

Don't forget to tell your textfield who it's delegate should be, probably in your viewDidLoad method, but can also be done in the xib view

myTextField.delegate = self;

I know this seems laborious but it will be extremely gratifying. Here's the apple doc for the UITextViewDelegate