繁体   English   中英

在字典数组中搜索并在表视图中显示数据

[英]Searching in Array of dictionary and displaying data in table view

我有一系列字典,在其中可以实现搜索功能并在tableView单元格上显示数据。

搜索效果很好,我已经对其进行了测试:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    NSString *dictionryKey = @"eViela";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS [cd] %@", dictionryKey, searchText];
    NSArray *filteredArray = [self.allItems filteredArrayUsingPredicate:predicate];
    NSLog(@"%@", filteredArray);

    self.sortedText = filteredArray;

    [self.tableView reloadData];

}

现在,当用户在搜索栏中键入信息时,我需要tableView仅填充键“ eViela”的数据。 到目前为止,我只能按照以下代码显示所有项目:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchCell" forIndexPath:indexPath];
    EvielasLibrary *library = [[EvielasLibrary alloc] init];
    cell.textLabel.text = [[library.library objectAtIndex:indexPath.row] 
    return cell;
}

我知道这应该很容易,但我无法弄清楚。

感谢帮助!

您需要从数组中获取模型,而不是创建新模型。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchCell" forIndexPath:indexPath];
    EvielasLibrary *library = [self.sortedText objectAtIndex:indexPath.row]; // assume that  self.sortedText is your data source array of tableview
    cell.textLabel.text = @"" // populate your string here  
    return cell;
}
NSMutableArray *arrayForTableView = [[NSMutableArray alloc] init];
NSString *dictionryKey = @"eViela";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",dictionryKey];
NSArray *filteredArray = [self.allItems filteredArrayUsingPredicate:predicate];
for (NSInteger i = 0; i<filteredArray.count; i++){
    NSString *matchValue = [NSString stringWithFormat:@"%@",[filteredArray objectAtIndex:i]];
    if ([matchValue isEqualToString:dictionryKey]){
        [arrayForTableView addObject:matchValue];
    }
}

将arrayForTableView数组用于表视图

cell.textLabel.text = [arrayForTableView objectAtIndex:indexPath.row];

问题是您没有更新sortedArray的numberOfRowsInSection委托方法

您需要检查搜索栏是否处于活动状态。 如果搜索栏处于活动状态,则使用sortedText数组;否则,如果搜索栏处于非活动状态,则使用library.library数组

对于选中的搜索栏,请创建一个全局变量isSearchBarActive并在searchBarTextDidBeginEditing委托函数中为其分配true值,并在searchBarTextDidEndEditing false分配给false

numberOfRowInSection添加条件

if searchBarActive {
    return self.sortedText.count
}
else {
    return library.library.count
}

像这样在cellForRowAtIndexPath添加条件

if searchBarActive {
    cell.textLabel.text = [self.sortedText objectAtIndex:indexPath.row] 
}
else {
    cell.textLabel.text = [library.library objectAtIndex:indexPath.row] 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM