我有一个UITableView,用户可以点击一个单元格,单元格附件视图上会出现一个复选标记。轻触单元格后,索引路径将保存到阵列中,阵列将保存到磁盘中。
当我离开并返回视图控制器时,我无法在UITableView上重新显示复选标记。
- (void)viewWillAppear:(BOOL)animated {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"selectedCells"];
self.retrievedIndexPaths = [[NSArray alloc] initWithObjects:
[NSKeyedUnarchiver unarchiveObjectWithData:data], nil];
NSLog(@"%@", self.retrievedIndexPaths);
}
可能我做错了什么:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
cell.textLabel.text = self.categoriesArray[indexPath.row];
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor whiteColor];
for (NSIndexPath *retrievedIndexPath in self.retrievedIndexPaths)
{
if (retrievedIndexPath == indexPath)
{ // Never hits here
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
return cell;
}
保存复选标记数据:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.selectedRowsArray addObject:cell.textLabel.text];
self.lastIndexPath = indexPath;
[self.selectedIndexPathsMutableArray addObject:self.lastIndexPath];
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
[self.selectedRowsArray removeObject:cell.textLabel.text];
[self.selectedIndexPathsMutableArray removeObject:indexPath];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSLog(@"%@", self.selectedRowsArray);
NSLog(@"%@", self.selectedIndexPathsMutableArray);
}
#pragma mark - UIBUTTON
- (IBAction)doneButton:(UIBarButtonItem *)sender
{
NSLog(@"button pressed");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:self.selectedIndexPathsMutableArray] forKey:@"selectedCells"];
[defaults synchronize];
[[PFUser currentUser] setObject:self.selectedRowsArray forKey:@"interests"];
[[PFUser currentUser] saveInBackground];
}
答案 0 :(得分:2)
indexPath是一个对象,所以你不应该用“==”来测试相等性。也没有必要循环遍历数组,只需使用containsObject,
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
cell.textLabel.text = self.categoriesArray[indexPath.row];
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor whiteColor];
if ([self.retrievedIndexPaths containsObject:indexPath]){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
答案 1 :(得分:0)
cell.accessoryType = UITableViewCellAccessoryCheckmark