Removing an Accessory View from a UITableViewCell When The Cell is Not Selected and maintaining between reloading views

StackOverflow https://stackoverflow.com/questions/22762560

문제

I have what I believe to be a simple problem, but I can't find a solution to it.

I have a static UITableView with two static cells (Light and Dark).

When the user selects one of the cells, I'm displaying an accessoryView with a custom image. When the user selects the other cell, I want the first cell to deselect and to remove the custom accessoryView and for that to be provided to the secondCell. I want this to continuously do this depending on which cell the user selects.

Of equal importance, I need to make sure the "selected" cell maintains the accessoryView throughout the reloading of this view controller (with the use of NSUserDefaults).

How would I go about doing this? I'm fairly new to iOS development.

Here's some code in my didSelectRow:

 BOOL isSelected;

if (cell.isSelected) {
    UIImageView *dot = [[UIImageView alloc]initWithFrame:CGRectMake(165, 10, 14, 15)];
    dot.image=[UIImage imageNamed:@"check-white-hi.png"];
    [cell addSubview:dot];
    cell.accessoryView = dot;
    isSelected = YES;
}
else {
    cell.accessoryView = nil;
    isSelected = NO;
}

Any assistance would really be appreciated with removing the accessory view from one of the cells and to the other, and also how to maintain this throughout the lifecycle of the app.

Thanks

도움이 되었습니까?

해결책

Create a property in your .h file

@property (nonatomic,retain)NSIndexPath * checkedIndexPath ;

synthesize in your .m file

@synthesize checkedIndexPath;

write this code in your didSelectRowAtIndexPath method

if(self.checkedIndexPath)
{
   UITableViewCell* uncheckCell = [tableView
                                    cellForRowAtIndexPath:self.checkedIndexPath];
    uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
if([self.checkedIndexPath isEqual:indexPath])
{
    self.checkedIndexPath = nil;
}
else
{
   UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    self.checkedIndexPath = indexPath;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top