Reputation: 151
I am using a Custom image for checkmark - '[email protected]' in a `UITableViewCell, but it's displaying everywhere in the cell. Can anyone suggest how to make it display only for the single selected cell?
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10, 300, 30)];
[cell.contentView addSubview:label];
label.text = [tableArr objectAtIndex:indexPath.row];
label.font = [UIFont fontWithName:@"Whitney-Light" size:20.0];
label.tag = 1;
UIImageView *checkmark = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"[email protected]"]];
cell.accessoryView = checkmark;
return cell;
}
Upvotes: 0
Views: 4238
Reputation: 5038
Less code is better:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
cell.textLabel.text = [tableArr objectAtIndex:indexPath.row];
cell.textLabel = [UIFont fontWithName:@"Whitney-Light" size:20.0];
return cell;
}
UPDATE:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
lastIndexPath = indexPath;
[tableView reloadData];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([lastIndexPath isEqual:indexPath]) {
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iphone-checkMark.png"]];
} else {
cell.accessoryView = nil;
}
}
UPDATE 2:
Write
//dont forget check for nil
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:lastIndexPath forKey:@"lastIndexPath"];
[defaults synchronize];
Read
NSIndexPath *lastPath = [defaults valueForKey:@"lastIndexPath"];
Upvotes: 1
Reputation: 840
One way to achieve what you are trying to do is to use a button and set the background image as your checkbox. This button will be your accessoryView. Monitor the touch event on the button and display the boolean accordingly. The sample project in the following link will provide all the code you need to implement this. https://developer.apple.com/library/ios/#samplecode/Accessory/Introduction/Intro.html
Upvotes: 0