Autocomplete using UITextView should change text in range
I followed Ray Wenderlich's tutorial on text autocomplete here: http://www.raywenderlich.com/336/how-to-auto-complete-with-custom-values
And it works great, but it only allows you to search for the string contained in the textView. I need it to search for multiple strings in one view. For example:
Hi @user, how @steve
Must search for both occurrences of @. Here's the source code:
- (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;
}
And here's mine:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
NSArray* items = [textView.text componentsSeparatedByString:@"@"];
if([items count] > 0 && [[items lastObject] length]){
NSString *substring = [NSString stringWithString:[items lastObject]];
[self searchAutocompleteEntriesWithSubstring:substring];
}
return YES;
}
And everything works, but it looks like it's character. So typing "J" will fail, but "Jo" will return results for "J". I think it has something to do with:
[substring stringByReplacingCharactersInRange:range withString:string]
But everything I'm trying to accomplish with NSRange is out of scope.
source to share
First of all, are we talking about a text box or a text view? They are different! Your code applies to both. I'll just go with textField
since that's the name of the method.
At the time you receive textField:shouldChangeCharactersInRange:replacementString:
, has textField.text
n't been changed to contain the replacement string. Therefore, when the user enters "J", textField.text
it does not yet contain J
.
The Ray method handles this by performing a replacement. When you try to do the substitution it fails because your variable substring
doesn't contain a copy textField.text
. Yours substring
contains only a part textField.text
. This is why you get an out of bounds exception - your range is out of bounds because it is substring
shorter textField.text
.
Therefore, you may need to do the replacement before you split the string. Try the following:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *changedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray* items = [changedText componentsSeparatedByString:@"@"];
if([items count] > 0 && [[items lastObject] length]){
NSString *substring = [NSString stringWithString:[items lastObject]];
[self searchAutocompleteEntriesWithSubstring:substring];
}
return YES;
}
source to share