iOS 6 CollectionView动态更改布局

时间:2013-02-16 19:26:39

标签: ios objective-c ios6 uicollectionview flowlayout

我是UICollectionView中的新手,我正在一个项目中动态更改给定操作中的UICollectionViewLayout

我的CollectionView有6个部分,每个部分有10个元素。那些单元格基本上是UIImageView,我的自定义布局StackViewLayout堆叠了每个部分的所有元素(类似于Apple的Photos.app)。

如果用户选择堆栈的元素(对于所有部分),UICollectionView会动态地将布局更改为UICollectionViewFlowLayout,因此可以将所有元素视为网格。

我的问题是,当用户选择一个堆栈时,无论哪个部分,当布局改变时,做Flow Layout,所有部分都显示在网格中,而不是显示所选部分(堆栈)的元素,这是我想要的行为。

有没有办法只显示自定义布局中所选部分的流程布局?

以下是我的Controller Implementation代码段:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadStackLayout]; // stack all sections at first load.
}

#pragma mark - UICollectionView Data Source Methods

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 6;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 10;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    // custom UICollectionViewCell, which will hold an image.
    CVCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];        
    cell.imageView.image = _images[indexPath.row];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // element size.
    return CGSizeMake(100,100);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (isStacked)
    {
         [self loadFlowLayout]; //HERE I WANT TO LOAD FLOW LAYOUT ONLY FOR THE SECTION OF THE SELECTED ITEM!
    } else
       {
           // to implement.
       }
}

// HERE IS THE METHOD THAT CALLS MY CUSTOM LAYOUT IN ORDER TO STACK THE ELEMENTS FOR EACH SECTION IN COLLECTION VIEW. IT IS WORKING AS IT SHOULD.
-(void)loadStackLayout
{
    if (([self.collectionView.collectionViewLayout isKindOfClass:[UICollectionViewFlowLayout class]]))
    {
        isStacked = YES;
        [self.collectionView setCollectionViewLayout:[[StackViewLayout alloc] init] animated:YES];
    }
}

// HERE IS THE METHOD THAT CALLS MY FLOWLAYOUT IN ORDER TO UN-STACK THE ELEMENTS AND SHOW THEM IN A GRID. CURRENTLY IT IS SHOWING ALL SECTIONS IN THE GRID.
-(void)loadFlowLayout
{
    if (([self.collectionView.collectionViewLayout isKindOfClass:[StackViewLayout class]]))
    {
        isStacked = NO;
        [self.collectionView setCollectionViewLayout:[[UICollectionViewFlowLayout alloc] init] animated:YES];
    }
}

1 个答案:

答案 0 :(得分:1)

我认为您可以通过在numberOfItemsInSection:方法中使用if子句来执行此操作,以便为任何不是所选部分的部分返回0。显然,您需要跟踪所选部分才能执行此操作。