为什么UICollectionView.indexPathsForSelectedItems忘记了我在viewWillAppear中选择了一个项目?

时间:2013-10-08 01:27:16

标签: objective-c ios7 uicollectionview

这曾经在iOS 6中运行但在iOS 7中失败

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:0];
    [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    NSArray *selectedPaths = self.collectionView.indexPathsForSelectedItems;
    NSAssert(selectedPaths.count == 1, @"viewWillAppear - Should be 1 but is %d", selectedPaths.count);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *selectedPaths = collectionView.indexPathsForSelectedItems;
    NSAssert(selectedPaths.count == 1, @"cellForItemAtIndexPath - Should be 1 but is %d", selectedPaths.count);
}

cellForItemAtIndexPath中的断言失败:

  

* 由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'cellForItemAtIndexPath - 应为1但是为0'

我使用selectItemAtIndexPath:indexPath API在viewWillAppear中选择一个项目,但是当调用cellForItemAtIndexPath时,collectionView忘记了已选择任何内容。知道为什么吗?

1 个答案:

答案 0 :(得分:3)

卫生署!

UICollectionViewController.clearsSelectionOnViewWillAppear