在ios中自动填充文本字段

时间:2015-12-23 10:17:26

标签: ios objective-c uitableview uitextfield

我在Xcode 6.4工作(目标C)。我有一系列名字。我想在用户输入内容时自动完成我的textfield。如果用户输入" a"在TextField中,所有名称都以" a"开头的下拉列表必须显示。如果用户输入" ab"在TextField中,所有名称都来自" ab"必须出示。

我知道下拉列表需要TableView。我通过搜索SO和其他网站(RayWendelich.com)尝试了一些示例。但是我无法解决这个问题。请帮我一个简单的解决方案。(我是iOS开发的新手)。

2 个答案:

答案 0 :(得分:2)

为此,您可以使用shouldChangeCharactersInRange的{​​{1}}委托方法。

UITextField

答案 1 :(得分:0)

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

     NSString *substring = [NSString stringWithString:textField.text];

     substring = [substring stringByReplacingCharactersInRange:range withString:string];

    [self searchFoodNameFromString:substring];

返回YES;

}

- (void)searchFoodNameFromString:(NSString *)strFood {

if(strFood.length>2)
{
     [arrAutoSuggFood removeAllObjects];
    NSInteger counter = 0;
    for(NSString *name in itemArray)
    {
        NSRange r = [name rangeOfString:strFood options:NSCaseInsensitiveSearch];
        if(r.length>2)
        {
            [arrAutoSuggFood addObject:name];
        }

        counter++;

    }

    if (arrAutoSuggFood.count > 0)
    {
        NSLog(@"%@",arrAutoSuggFood);
        self.viewAutoSuggest.hidden = FALSE;
        [self displayAutoSuggestView];

    }
    else
    {
        self.viewAutoSuggest.hidden = TRUE;
    }

}
else
{
    [self.viewAutoSuggest setHidden:TRUE];

}

}

- (void)displayAutoSuggestView {

CGFloat autoSuggViewHeight;
if ([arrAutoSuggFood count] == 1) {
    autoSuggViewHeight = 44.0 * 1;
} else if ([arrAutoSuggFood count] == 2) {
    autoSuggViewHeight = 44.0 * 2;
} else {
    autoSuggViewHeight = 44.0 * 3;
}


[_viewAutoSuggest removeFromSuperview];
_viewAutoSuggest.frame = CGRectMake(addFoodAnotationTxt.frame.origin.x+8, addFoodAnotationTxt.frame.origin.y - autoSuggViewHeight, addFoodAnotationTxt.frame.size.width, autoSuggViewHeight);
[_scrlVwMain bringSubviewToFront:_viewAutoSuggest];
[_scrlVwMain addSubview:_viewAutoSuggest];

_tblAutoSugg.frame = self.viewAutoSuggest.bounds;
_tblAutoSugg.delegate = self;
_tblAutoSugg.dataSource = self;
[_viewAutoSuggest addSubview:_tblAutoSugg];
 [_tblAutoSugg reloadData];

}