[英]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.