2016-12-11 196 views

回答

0

在一个viewcontroller中,您不能直接从集合视图单元中获得一个segue,而是转到另一个视图控制器中的另一个单元格。但是应该可以做类似下面的东西来达到你想要的东西:

父视图控制器

1)添加类型的属性selectedIndexPath NSIndexPath

2)故事板安装(或代码),这个视图控制器实现了UICollectionViewDelegate

3)实施didSelectItemAtIndexPath委托方法为您收集查看

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

4)selectedIndexPath值传递给你的第二个视图控制器

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    // :: Should do other checking - if we have segues to other screens 
    SecondViewController *secondViewController = (SecondViewController *)segue.destinationViewController; 
    secondViewController.initialDisplayedCellIndexPath = selectedIndexPath 
} 

}

SecondViewController代码

1)添加类型的属性initialDisplayCellIndexPath NSIndexPath

2)重写viewWillAppear中

(这是假设你的collectionV IEW属性命名的CollectionView)

[self.view layoutIfNeeded]; 
[self.collectionView scrollToItemAtIndexPath:initialDisplayCellIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically 

基本上什么上面做的是做从一个视图控制器正常SEGUE你的第二个视图控制器 - 触发在代码中单击单元格的结果。作为prepareForSegue的一部分,我们可以将数据传递给第二个视图控制器(在这种情况下,它是所选项目的indexPath)。然后,当第二个viewcontroller显示,我们然后告诉集合视图滚动到我们想要去的地方。

希望有道理:-)

+0

谢谢你的回答。我做了你所说的一切,但当我点击单元格时它崩溃了。当我注释掉viewWillAppear中的scrollToItemAtIndexPath部分时,segue可以工作,但所有单元格都从第二个视图控制器转到第一个单元格 –

+0

这是我得到的错误:终止应用程序,由于未捕获异常'NSInvalidArgumentException',原因:'试图滚动到索引路径无效:

相关问题