You want a toggling type nature for the imageView
.
- (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];
}
[cell.imageView setImage: [UIImage imageNamed:@""]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//refresh all cells
//basically call cellForRowAtIndexPath to reset all cells
[tableView reloadSections:indexPath.section
withRowAnimation:UITableViewRowAnimationFade];
//get cell for the currently selected row
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//set image
[cell.imageView setImage: [UIImage imageNamed:@"loudspeaker.png"]];
}
But this is just a visual aspect.
If you select the first row and scroll down and later return to the first row, the image would no longer be there because -cellForRowAtIndexPath:
is recalled and since we had [cell.imageView setImage: [UIImage imageNamed:@""]];
in it, the imageView.image
is reset.
To handle the above scenario, you need to remember which rows were selected. (you can achieve this by a basic array)
Example:
- (void)viewDidLoad {
[super viewDidLoad];
//arrMyDataSource is defined in .h as 'NSArray *arrMyDataSource;'
//needless to say but this is the tableView's datasource contents
arrMyDataSource = @[@"Apple",@"Banana",@"Candy",@"Door",@"Elephant"];
//arrMemoryMap is defined in .h as 'NSMutableArray *arrMemoryMap;'
//this is one way to remember which row is selected
arrMemoryMap = [NSMutableArray alloc] init];
for (int i = 0 ; i < arrMyDataSource.count ; i++) {
NSNumber *tmpSelectStatus = [NSNumber numberWithBool:NO];
[arrMemoryMap addObject: tmpSelectStatus];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//...
if([[arrMemoryMap objectAtIndex:indexPath.row] boolValue] == YES) {
[cell.imageView setImage: [UIImage imageNamed:@"loudspeaker.png"]];
} else {
[cell.imageView setImage: [UIImage imageNamed:@""]];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//first, reset arrMemoryMap for all rows
for (int i = 0 ; i < arrMemoryMap.count ; i++) {
if([[arrMemoryMap objectAtIndex:i] boolValue] == YES]) {
[[arrMemoryMap objectAtIndex:i] setBoolValue: NO];
break;
}
}
//now, set current row as selected in arrMemoryMap
[[arrMemoryMap objectAtIndex:indexPath.row] setBoolValue: YES];
//reload data or particular section
[tableView reloadSections:indexPath.section
withRowAnimation:UITableViewRowAnimationFade];
}