【问题标题】:Auto suggest in UITextfield with comma separation在 UITextfield 中使用逗号分隔自动建议
【发布时间】:2012-07-11 10:08:53
【问题描述】:

下面的代码让我可以自动建议输入到 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];
}

【问题讨论】:

    标签: ios nsstring uitextfield


    【解决方案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, 分隔 textFields 文本并将其作为 NSArray
    • lastObject 从该数组中获取最后一个对象。如果是@"" 则不搜索,否则搜索匹配元素。

    希望这会对你有所帮助。

    【讨论】:

    • 哇。有用! :) 但是有两个问题,当我在文本字段中键入时它不会占用第一个字符,并且当文本字段为空时 tableview 视图不会隐藏
    猜你喜欢
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2011-01-18
    相关资源
    最近更新 更多