所以我实现了一个带有tableview的UIViewController,基本上它作为我的uicollectionview的一组“过滤器”加载.
现在,当我点击tableview中的复选标记时,它会相应地“过滤”我的单元格,但现在当我再次重新加载视图时,我想显示我使用过的最新“复选标记”或“过滤器”.
我已经看到这是用NSUserDefaults实现的,但我无法成功实现它.
如果有人能帮助我,我将不胜感激.
码
FiltersViewController.m:
#import "FiltersViewController.h" @interface FiltersViewController () @property (nonatomic,strong) NSMutableSet *selectedRowObjects; //@property (nonatomic,strong) NSArray *filters; @end @implementation FiltersViewController - (void)viewDidLoad { [super viewDidLoad]; self.selectedRowObjects = [NSMutableSet setWithCapacity:10]; } - (IBAction)filteRSSelected:(id)sender { [self.delegate filteRSSelected:self.selectedRowObjects]; } - (IBAction)cancelFilterSelection:(id)sender { [self.delegate filterSelectionCancelled]; } - (Nsstring *)getKeyForIndex:(int)index { return [Nsstring stringWithFormat:@"KEY%d",index]; } - (BOOL) getCheckedForIndex:(int)index { if([[[NSUserDefaults standardUserDefaults] valueForKey:[self getKeyForIndex:index]] boolValue]==YES) { return YES; } else { return NO; } } - (void) checkedCellAtIndex:(int)index { BOOL boolChecked = [self getCheckedForIndex:index]; [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:!boolChecked] forKey:[self getKeyForIndex:index]]; [[NSUserDefaults standardUserDefaults] synchronize]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 10; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"filter" forIndexPath:indexPath]; cell.textLabel.text = [Nsstring stringWithFormat:@"%u",indexPath.row]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; Nsstring *obj = cell.textLabel.text; if (cell.accessoryType == UITableViewCellAccessorycheckmark) { cell.accessoryType = UITableViewCellAccessoryNone; [self.selectedRowObjects removeObject:obj]; } else { cell.accessoryType = UITableViewCellAccessorycheckmark; [self.selectedRowObjects addobject:obj]; } [tableView deselectRowAtIndexPath:indexPath animated:YES]; } @end
解决方法
你还需要检查cellForRowAtIndexPath.在此编写此代码
if([[NSUserDefaults standardUserDefaults] objectForKey:[self getKeyForIndex:indexPath.row]]) { cell.accessoryType = UITableViewCellAccessorycheckmark; } else { cell.accessoryType = UITableViewCellAccessoryNone; }
是的,不要忘记在didSelectRowAtIndexPath中调用此方法
[self checkedCellAtIndex:indexPath.row];
请享用.