Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autocomplete UITextField

I want to auto complete a text field from a custom value

Having researched Google and SO here UITextField Autocomplete - iPhone SDK

I tried this:

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

    if ([string isEqualToString:@"Fac"]) {
        _clientField.text = @"Factory";
    }

    return YES;
}

Problem is I get no predicted value entered Factory, just the typed value Fac

EDIT

Tried this based on answers...

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

if ([string isEqualToString:@"Fac"]) {
    _clientField.text = [_clientField.text stringByReplacingCharactersInRange:range
                                                   withString:@"Factory"];
  }

  return NO;
}

Still the same

like image 400
JSA986 Avatar asked Apr 17 '26 06:04

JSA986


2 Answers

Sounds like HTAutocompleteTextField will do the job:

https://github.com/hoteltonight/HTAutocompleteTextField

You basically just need to give it an array of values as the autocomplete data source, and it will make the suggestions in the text field as the user types.

like image 97
codeperson Avatar answered Apr 19 '26 19:04

codeperson


I checked your sample code and the text field's delegate is not set.

You can set it in your view controller using

_clientField.delegate = self;

Additionally you need to use a slightly different method to get the text which the users sees. Something like this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *currentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([currentString isEqualToString:@"Fac"]) {
        textField.text = @"Factory";
        return NO;
    }
    return YES;
}

Note that you probably want to fine tune this a bit, since it e.g. also autocompletes when the user deletes text. But this should get you on the right track.

like image 43
Alfonso Avatar answered Apr 19 '26 20:04

Alfonso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!