问题
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