CollectionViewController单元格选择 - 空数组

时间:2015-02-10 16:13:44

标签: ios objective-c iphone

在我的CustomCollectionViewController类中,我有一个检测单元格选择的方法:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{   
    UIAlertView *messageAlert = [[UIAlertView alloc] initWithTitle:@"Category selected" message:[NSString stringWithFormat:@"%ld", (long)indexPath.item + 1] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [messageAlert show];
}

运作良好。

但如果我把这个方法改为简单:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self performSegueWithIdentifier:@"showLevelsSegue" sender:self];
}

崩溃时出现错误:

' NSRangeException',原因:' *** - [__ NSArrayI objectAtIndex:]:索引0超出空数组的范围'。

我在故事板中创建了一个带有showLevelsSegue标识符的segue。我有简单的结构:导航控制器 - > CustomCollectionViewController - >视图控制器。

任何人都可以帮助我吗?

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
     if ([segue.identifier isEqualToString:@"showLevelsSegue"]) { 
         UICollectionViewCell *cell = (UICollectionViewCell *)sender;
         NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];   
         DataManager *sharedManager = [DataManager sharedManager];
         sharedManager.categoryId = indexPath.row; 
     } 
} 

编辑2 - 根据@Larme的回答,它还没有解决问题

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showLevelsSegue"]) {
        NSArray *arrayOfIndexPaths = [self.collectionView indexPathsForSelectedItems];
        NSIndexPath *selectedIndexPath = [arrayOfIndexPaths objectAtIndex:0];
        DataManager *sharedManager = [DataManager sharedManager];

        sharedManager.categoryId = selectedIndexPath.row;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    [self performSegueWithIdentifier:@"showLevelsSegue" sender:nil];
}

1 个答案:

答案 0 :(得分:0)

CustomCollectionViewController

[self performSegueWithIdentifier:@"showLevelsSegue" sender:self];

selfCustomCollectionViewController类的实例。

所以当你这样做时:

UICollectionViewCell *cell = (UICollectionViewCell *)sender;

你错了,除非CustomCollectionViewController继承自UICollectionViewCell,但我显然对此表示怀疑。

所以,有几种方法可以做到:

•由于您似乎使用performSegueWithIdentifier:sender触发了showLevelSegue,因此您可以在其中检索使用

选择的UICollectionViewCell
NSArray *arrayOfIndexPaths = [yourCollectionView indexPathsForSelectedItems];
NSIndexPath selectedIndexPath = [arrayOfIndexPaths objectAtIndex:0];

无需将self作为参数传递,只发送nil[ZzZ sender:nil];

•或者您可以在那里发送NSIndexPath[self performSegueWithIdentifier:@"showLevelsSegue" sender:indexPath]; 并检索它:

NSIndexPath *indexPath = (NSIndexPath *)sender;