-->

自动建议中的UITextField用逗号分隔(Auto suggest in UITextfield

2019-10-16 23:44发布

下面的代码让我自动提示键入到的UITextField值,通过比较以前添加字符串对象的数组,并显示在一个UITableView。 这工作得很好,但只有一个字。

所以,现在,我可以修改代码以这样的方式,用户进入一个逗号后,然后再次开始打字,我能为逗号后键入的字符再次搜索建议相同字符串数组?

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

Answer 1:

你能做到这样,

- (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方式隔开的文本框的文本通过并给它作为一个NSArray
  • lastObject需要从阵列的最后一个对象。 如果是@“”无搜索,否则搜索的匹配元素。

希望这会帮助你。



文章来源: Auto suggest in UITextfield with comma separation