В моем приложении я работаю с UISearchBar
, где пользователь будет искать из NSMutableArray
, выполняя поиск по имени пользователя. Вот мой метод поиска пользователя из NSMutableArray
- (void)searchTableList
{
NSString *searchString = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in contentList)
{
NSArray *array = [dictionary objectForKey:@"username"];
[searchArray addObject:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchString options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[filteredContentList addObject:sTemp];
}
}
И вот как я настраиваю UITableView
для отображения результатов поиска
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"SearchListTableViewCell";
NSMutableDictionary *dict=[contentList objectAtIndex:indexPath.row];
SearchListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SearchListTableViewCell" owner:nil options:nil];
cell = (SearchListTableViewCell*)[topLevelObjects objectAtIndex:0];
cell.backgroundColor=[UIColor colorWithRed:239.0/255 green:239.0/255 blue:239.0/255 alpha:1];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
// Configure the cell...
if (isSearching)
{
cell.friendName.text = [filteredContentList objectAtIndex:indexPath.row];
NSMutableArray *searchImageArray=[[NSMutableArray alloc]init];
for (NSDictionary *dictionary in contentList)
{
NSArray *imageArray=[dictionary objectForKey:@"thumbnail_path_150_150"];
NSLog(@"image arrayt is %@",imageArray);
[searchImageArray addObject:imageArray];
}
for (NSString *imageS in searchImageArray) {
NSRange title=[imageS rangeOfString:cell.friendName.text options:NSCaseInsensitiveSearch];
if (title.length>0) {
[filteredImage addObject:imageS];
}
}
NSString *url=[NSString stringWithFormat:@"%@/get_image?avatar=%@",BaseURL,[filteredImage objectAtIndex:indexPath.row]];
url=[url stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:url]]];
[cell.friendProfileImage setImage:myImage];
NSLog(@"filtered Image data %lu",(unsigned long)filteredImage.count);
NSLog(@"filtered content list data %lu",(unsigned long)filteredContentList.count);
}
else
{
cell.friendName.text =[dict objectForKey:@"username"];
NSString *url=[NSString stringWithFormat:@"%@/get_image?avatar=%@",BaseURL,[dict objectForKey:@"thumbnail_path_150_150"]];
url=[url stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:url]]];
[cell.friendProfileImage setImage:myImage];
}
return cell;
}
Теперь я хочу получить остальные данные об искомом имени пользователя из NSMutableDictionary
. Вот мой словарь.
(
{
jid = "hey@196.0.0.1";
"thumbnail_path_150_150" = "E\\path\\to\\getImage\\files\\heythumbnail";
username = hey;
},
{
jid = "tweety@196.0.0.1";
"thumbnail_path_150_150" = "E:\\path\\to\\getImage\\files\\tweetythumbnail";
username = tweety;
}
)
Здесь я хочу получить изображение искомого пользователя. Если пользователь ищет "привет", он должен показать "thumbnail_path_150_150"
="E\\path\\to\\getImage\\files\\heythumbnail";
это изображение в tableViewCell. Я пробовал свой код для установки изображения, но он заменяет изображение, когда два пользователя имеют одинаковое имя. Например, если один пользователь - Ray, а другой - Blueray, тогда изображение обоих меняется. Я знаю, что написал слишком много. Но я действительно сбит с толку. Пожалуйста, помогите кому-нибудь решить эту проблему.
3 ответа
Примените NSPredicate
для фильтрации вашего массива, а затем используйте этот массив для заполнения tableView
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username contains[c] %@",_search_bar.text];
NSArray *filteredArray = [yourMainArray filteredArrayUsingPredicate:predicate];
NSLog(@"here is the filteredCandyArray%@",filteredCandyArray);
//set it to the array you use to fill the table
_dataSourceArray = _filteredCandyArray;
//go!
[_yourTable reloadData];
Сравнение строк по умолчанию чувствительно к регистру и диакритическому знаку. Вы можете изменить оператор, используя ключевые символы c и d в квадратных скобках, чтобы указать нечувствительность к регистру и диакритике соответственно, например firstName BEGINSWITH [cd] $ FIRST_NAME.
BEGINSWITH: левое выражение начинается с правого выражения. CONTAINS: левое выражение содержит правое выражение. ENDSWITH: левое выражение заканчивается правым выражением. LIKE: левое выражение равно правому выражению:? и * разрешены как символы подстановки, где? соответствует 1 символу, а * соответствует 0 или более символам. СООТВЕТСТВИЯ: левое выражение равно правому выражению. или для получения дополнительной информации посетите http://nshipster.com/nspredicate/
Я рекомендую вам использовать Search Bar and Search Display Controller
, а не Search Bar
.
Также обратите внимание на следующий код, он охватывает все, что вам нужно.
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
#pragma mark
#pragma mark - View Lifecycle
-(void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *dic1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1", @"India", @"IN", @"+91", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"2", @"Australia", @"AU", @"+61", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"3", @"New Zealand", @"NZ", @"+64", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"4", @"South Africa", @"SA", @"+27", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic5 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"5", @"England", @"EN", @"+44", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic6 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"6", @"Israel", @"IS", @"+972", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic7 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"7", @"Afghanistan", @"AF", @"+93", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic8 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"8", @"Ireland", @"IR", @"+353", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic9 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"9", @"China", @"CN", @"+86", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
arrTotalCountries = [NSArray arrayWithObjects:dic1, dic2, dic3, dic4, dic5, dic6, dic7, dic8, dic9, nil];
}
#pragma mark
#pragma mark - UITableView delegate, datasource methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView == self.searchDisplayController.searchResultsTableView){
return [arrFilteredCountries count];
}
else{
return [arrTotalCountries count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:@"CellIdentifier%ld%ld",(long)indexPath.section,(long)indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dicCountry;
if (tableView == self.searchDisplayController.searchResultsTableView) {
dicCountry = [arrFilteredCountries objectAtIndex:indexPath.row];
} else {
dicCountry = [arrTotalCountries objectAtIndex:indexPath.row];
}
NSString *strShow = [NSString stringWithFormat:@"%@ (%@)",[dicCountry objectForKey:@"CountryName"],[dicCountry objectForKey:@"ISDCode"]];
cell.textLabel.text = strShow;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *dicCountry;
if (tableView == self.searchDisplayController.searchResultsTableView) {
dicCountry = [arrFilteredCountries objectAtIndex:indexPath.row];
} else {
dicCountry = [arrTotalCountries objectAtIndex:indexPath.row];
}
NSString *countryName = [dicCountry objectForKey:@"CountryName"];
NSString *CountryISDCode = [dicCountry objectForKey:@"ISDCode"];
[self showAlertWithTitle:countryName message:CountryISDCode];
}
#pragma mark
#pragma mark - Other method Implementation
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF.CountryName BEGINSWITH[cd] %@) OR (SELF.ISDCode CONTAINS[cd] %@)", searchText, searchText];
arrFilteredCountries = [arrTotalCountries filteredArrayUsingPredicate:predicate];
}
-(void)showAlertWithTitle:(NSString *)title message:(NSString *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
#pragma mark
#pragma mark - UISearchbar controller delegate
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#pragma mark
#pragma mark - Memory management
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
Также добавьте комментарий на случай, если кто-то застрял в какой-то момент. Я реализовал это, и он отлично работает. Это краткий и лучший способ добавить функцию поиска в представление таблицы.
Самый простой способ сделать это - использовать предикаты, и с небольшими изменениями ваш код может выглядеть примерно так
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username == %@", @"ray"];
NSArray *searchedArray = [rootArray filteredArrayUsingPredicate:predicate];
Приведенный выше код вернет только значения, в которых имя пользователя - ray, а не Ray или RAY и т. Д.
Похожие вопросы
Новые вопросы
ios
iOS - мобильная операционная система, работающая на Apple iPhone, iPod touch и iPad. Используйте этот тег [ios] для вопросов, связанных с программированием на платформе iOS. Используйте связанные теги [target-c] и [swift] для проблем, характерных для этих языков программирования.