2016-12-11 123 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',原因:'試圖滾動到索引路徑無效:

相關問題