Automatic suggestion in a UITextfield comma separated field

The following code allows me to automatically indicate the values ​​entered in a UIText field by comparing it with an array of previously added string objects and displaying it in a UITableview. This works great, but only for one word.

So, can I change the code so that after the user enters a comma, then starts typing again, I can again find the same array of strings for sentences for characters entered after the comma?

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.tag == tagTextFieldTag) //The text field where user types { textField.autocorrectionType = UITextAutocorrectionTypeNo; autocompleteTableView.hidden = NO; //The table which displays the autosuggest NSString *substring = [NSString stringWithString:textField.text]; substring = [substring stringByReplacingCharactersInRange:range withString:string]; if ([substring isEqualToString:@""]) { autocompleteTableView.hidden = YES; //hide the autosuggest table if textfield is empty } [self searchAutocompleteEntriesWithSubstring:substring]; //The method that compares the typed values with the pre-loaded string array } return YES; } - (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring { [autoCompleteTags removeAllObjects]; for(Tag *tag3 in tagListArray) //tagListArray contains the array of strings //tag3 is an object of Tag class, which has a single attribute called 'text' { NSString *currentString = tag3.text; NSRange substringRange = [currentString rangeOfString:substring]; if(substringRange.location ==0) { [autoCompleteTags addObject:currentString]; } } [autocompleteTableView reloadData]; } 
+1
source share
1 answer

You can do it as follows:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.tag == tagTextFieldTag) //The text field where user types { textField.autocorrectionType = UITextAutocorrectionTypeNo; autocompleteTableView.hidden = NO; //The table which displays the autosuggest NSArray *autoComplete = [textField.text componentsSeparatedByString:@","]; NSString *substring = [NSString stringWithString:[autoComplete lastObject]]; if ([substring isEqualToString:@""]) { autocompleteTableView.hidden = YES; //hide the autosuggest table if textfield is empty } [self searchAutocompleteEntriesWithSubstring:substring]; } return YES; } 

this method works like,

  • componentsSeparatedByString splits the text textFields into , and gives it as an NSArray
  • lastObject takes the last object from this array. If it is @ "", the search otherwise does not search for the corresponding element.

Hope this helps you.

+5
source

Source: https://habr.com/ru/post/1208402/


All Articles