NSUserDefaults不保存Selected Cells的indexPath

时间:2017-09-22 21:06:41

标签: objective-c nsuserdefaults cells

我知道我无法在NSUserDefaults中保存indexPath。我想保存用户选择的单元格,这样当用户打开视图控制器AGAIN时 - 集合视图中选定的单元格显示。但是,下面的代码不会保存选定的单元格。第一个代码块假设保存选定的单元格(但不是),第二个代码块表示永远不会执行此代码(如下所述)。

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [[NSUserDefaults standardUserDefaults] setObject:@{@"row": @(indexPath.row),
                                                       @"section": @(indexPath.section)}
                                              forKey:@"CollectionIndex"];

    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    NSIndexPath *storedIndexPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"CollectionIndex"];

    static NSString *identifier = @"cell";
    UICollectionViewCell *myCell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:storedIndexPath];

    myCell.contentView.backgroundColor = [UIColor purpleColor];
    myCell.layer.masksToBounds = YES;
    myCell.layer.cornerRadius = 6; 

    return myCell;

}

我的收藏视图 代码永远不会执行

if (collectionView ==self.septView) {
    // Call identifier
    static NSString *identifier = @"cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    cell.layer.masksToBounds = YES;
    cell.layer.cornerRadius = 6;

    // cell.contentView.backgroundColor = [UIColor purpleColor];


    // Color
    self.septView.backgroundColor = [UIColor clearColor];

    // Label
    self.titles = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, cell.bounds.size.width, 40)];
    self.titles.tag = 0;
    self.titles.textColor = [UIColor whiteColor];
    self.titles.textAlignment = NSTextAlignmentCenter;
    self.titles.font = [UIFont fontWithName:@"Avenir" size:15];
    self.titles.text = [self.sept objectAtIndex: indexPath.row];
    [cell.contentView addSubview:self.titles];



    return cell;
}

1 个答案:

答案 0 :(得分:0)

您可以在cellForItemAtIndexPath中获取索引路径,如下所示:

    NSDictionary *storedIndexDictionary = [[NSUserDefaults standardUserDefaults] objectForKey:@"CollectionIndex"];
    NSInteger row = [[storedIndexDictionary objectForKey:@"row"] integerValue];
    NSInteger section = [[storedIndexDictionary objectForKey:@"section"] integerValue];

    NSIndexPath *storedIndexPath = [NSIndexPath indexPathForRow:row inSection:section];