我在UICollectionView
有點新手,我正在一個項目中動態更改給定動作中的UICollectionViewLayout
。iOS 6 CollectionView動態更改佈局
我的CollectionView有6個部分,每個部分都有10個元素。這些單元基本上是一個UIImageView
,我的自定義佈局被稱爲StackViewLayout
堆疊每個部分的所有元素(如Apple的Photos.app)。
如果用戶選擇堆棧的元素(對於所有部分),UICollectionView
會動態地將佈局更改爲UICollectionViewFlowLayout
,因此所有元素都可以被視爲網格。
我的問題是,當用戶選擇一個堆棧時,無論哪個區域,當佈局改變時都會執行Flow Layout,所有區域都顯示在網格中,而不是顯示選定區域(堆棧)的元素,這是我想要的行爲。
有沒有什麼方法可以只顯示自定義佈局中選定部分的流佈局?
這裏是我的控制器實現代碼片段:
- (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];
}
}
那麼我試圖返回0的所有部分,但在numberOfItensInSection中選定的一個,但事實證明xcode給我很壞訪問(沒有任何進一步的細節)。如果我爲未選擇的部分設置了返回1項並在堆棧中選擇部分0(點擊它),則if條款才起作用。任何其他組合會使應用程序崩潰。 – lsp 2013-02-17 05:55:11