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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With