在逗号分隔的UITextfield自动build议

下面的代码让我自动build议input到UITextfield中的值,方法是将它与先前添加的string对象的数组进行比较,并将其显示在UITableview中。 这工作正常,但只适用于一个单词。

那么现在我可以用这样的方式修改代码,那么在用户input逗号之后,再次开始input,我可以再次search相同的string数组,以便在逗号后面input字符。

- (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]; } 

你可以这样做,

 - (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; } 

此方法的工作原理是,

  • componentsSeparatedByString将textFields文本分开并将其作为NSArray
  • lastObject从该数组中获取最后一个对象。 如果是@“”则不进行search,否则search匹配的元素。

希望这会帮助你。