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

末鹿安然 提交于 2019-12-23 03:21:16

问题


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


回答1:


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;
}


来源:https://stackoverflow.com/questions/22762560/removing-an-accessory-view-from-a-uitableviewcell-when-the-cell-is-not-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!