Question:
I want to search for images using the search bar in a tableview. My search works, but for showing the image I am using this code in
- (void)viewDidLoad
{
[super viewDidLoad];
_array18 = [[NSArray alloc ]initWithObjects:@"title1",@"title2",@"title3", nil];
_image = [[NSArray alloc ]initWithObjects:[UIImage imageNamed:@"title1.jpg"],[UIImage imageNamed:@"title2.jpg"],[UIImage imageNamed:@"title3.jpg"], nil];
}
- (void)searchForText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:@"SELF contains[cd] %@",
searchText];
_searchResults = [_array18 filteredArrayUsingPredicate:resultPredicate];
}
But the code in cellForRowAtIndexPath
not an easy solution, if I have 100 images or more I need to create 100 checks. How can this code be simplified or is there a simpler solution?
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
cell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell= [[cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
if ([[_searchResults objectAtIndex:indexPath.row]isEqualToString:@"title1"]) {
cell.imageView.image = [_image objectAtIndex:0];
}
if ([[_searchResults objectAtIndex:indexPath.row]isEqualToString:@"title2"]) {
cell.imageView.image = [_image objectAtIndex:1];
}
if ([[_searchResults objectAtIndex:indexPath.row]isEqualToString:@"title3"]) {
cell.imageView.image = [_image objectAtIndex:2];
}
}
Answer:
Use a dictionary:
@property (strong,nonatomic)NSMutableDictionary *dic;
- (void)viewDidLoad {
[super viewDidLoad];
_array18 = [[NSArray alloc]initWithObjects:@"title1",@"title2",@"title3", nil];
[self initDic];
}
- (void)initDic {
self.dic = [[NSMutableDictionary alloc] initWithDictionary:@{ @"title1":[UIImage imageNamed:@"title1.jpg"],
@"title2":[UIImage imageNamed:@"title2.jpg"],
@"title3":[UIImage imageNamed:@"title3.jpg"]
}];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"Cell";
cell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.imageView.image = [dic objectForKey:[_searchResults objectAtIndex:indexPath.row]];
return cell;
}