我是 UICollectionView
的新手,我正在从事一个在给定操作中动态更改 UICollectionViewLayout
的项目。
我的 CollectionView 有 6 个部分,每个部分有 10 个元素。这些 Cells 基本上是一个 UIImageView
,我的名为 StackViewLayout
的自定义布局堆叠了每个部分的所有元素(类似于 Apple 的 Photos.app)。
如果用户选择堆栈的元素(对于所有部分),UICollectionView
会动态将布局更改为 UICollectionViewFlowLayout
,因此所有元素都可以视为网格。
我的问题是,当用户选择一个堆栈时,无论是哪个部分,当布局更改为 Flow Layout 时,所有部分都显示在网格中,而不是显示所选部分(堆栈)的元素,这是我想要的行为。
有没有办法在自定义布局中只显示所选部分的流布局?
这是我的 Controller 实现片段代码:
- (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];
}
}
最佳答案
我认为您可以通过在您的 numberOfItemsInSection: 方法中添加一个 if 子句来做到这一点,以便为任何未选定的部分返回 0。显然,您需要跟踪所选部分才能执行此操作。
关于iOS 6 CollectionView 动态改变布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14914217/