我有一个文本字段,用户想在其中输入年份。我在textfield下面有tableview,我在其中传递了一系列年份。当用户输入年份时,表视图应在表视图中显示数组中的年份列表,并且它应与数组中的前两个单词匹配。我试过一个代码,但它没有显示多年的数组。我的代码就是这个,
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"Range:%@",NSStringFromRange(range));
NSLog(@"%@",textField.text);
NSString *passcode = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSLog(@"%@",passcode);
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"SELF CONTAINS %@",passcode];
year1Array = [year1Array filteredArrayUsingPredicate:predicate];
NSLog(@"%@", year1Array);
if ([year1Array count]==0) {
_year01.hidden=true;
}else{
_year01.hidden = FALSE;
}
[_year01 reloadData];
return TRUE;
}
tableview代码就是这个,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView==_year01) {
return [year1Array count];
}else{
return [year2Array count];
}
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == _year01){
cell.textLabel.text=[year1Array objectAtIndex:indexPath.row];
}else{
cell.textLabel.text=[year2Array objectAtIndex:indexPath.row];
}
cell.backgroundColor=[UIColor grayColor];
cell.textLabel.textColor=[UIColor whiteColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
if (tableView == _year01){
self.year1.text=[year1Array objectAtIndex:indexPath.row];
self.year01.hidden=YES;
}else{
self.year2.text=[year2Array objectAtIndex:indexPath.row];
self.year02.hidden=YES;
}
}
答案 0 :(得分:0)
只需更改CONTAINS[cd]
NSPredicate
即可
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", passcode];
已编辑:
让你问一下你哪里出错了
year1Array = [year1Array filteredArrayUsingPredicate:predicate];
您要将过滤后的结果添加到主阵列的year1Array
,这样当您不能获得结果时,则表示0,那么您的主阵列也将为0,这就是您遇到此类问题的原因。
所以为Ex。
选择一个全局数组@property(nonatomic,strong)NSMutableArray * temStaticArray;
仅将 year1Array 添加到 temStaticArray 一次。
[temStaticArray addObjectsFromArray:year1Array];
现在改变shouldChangeCharactersInRange
if (year1Array.count > 0){
[year1Array removeAllObjects];
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"SELF CONTAINS %@",passcode];
year1Array = [temStaticArray filteredArrayUsingPredicate:predicate];
NSLog(@"%@", year1Array);
if ([year1Array count]==0) {
[year1Array addObjectsFromArray:temStaticArray];
_year01.hidden=true;
}else{
_year01.hidden = FALSE;
}
[_year01 reloadData];