布局切換.gif
- 我們就進(jìn)行設(shè)定,當(dāng)點(diǎn)擊屏幕的時(shí)候,進(jìn)行布局的切換.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 根據(jù)布局類型進(jìn)行切換(如果是圓形布局)
if ([self.collectionView.collectionViewLayout isKindOfClass:[LXLCircleLayout class]]) {
// 設(shè)置布局為流水布局
LXLFlowLayout *flow = [[LXLFlowLayout alloc]init];
[self.collectionView setCollectionViewLayout:flow animated:YES];
}else{
// 如果不是圓形布局,就設(shè)置成圓形布局
[self.collectionView setCollectionViewLayout:self.circleLayout animated:YES];
}
}
- 我們發(fā)覺,我們確實(shí)能做到相互的切換,但是如果再次切換回圓形布局時(shí),發(fā)現(xiàn)程序直接就處于崩潰了. 因?yàn)槿绻袚Q回去的話可能由于cell 數(shù)目的不確定性,或者重新切換的原因,造成布局再次出現(xiàn)錯(cuò)誤,而無法正常顯示. 我們通過查找,找到對應(yīng)方法進(jìn)行重寫.(其中原因,我也不是很明白).
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray *layoutAtts = [NSMutableArray array];
NSInteger count = [self.collectionView numberOfItemsInSection:0];
for (int i = 0; i < count ; i ++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
// 調(diào)用方法,直接返回對應(yīng)索引的布局
UICollectionViewLayoutAttributes *layoutAtt = [self layoutAttributesForItemAtIndexPath:indexPath];
// 如果返現(xiàn)只有一個(gè) cell 的時(shí)候讓你直接設(shè)置到中心點(diǎn)(相當(dāng)于將以前的布局覆蓋掉)
if (count == 1) {
layoutAtt.center = CGPointMake(self.collectionView.frame.size.width * 0.5, self.collectionView.frame.size.height * 0.5);
}
[layoutAtts addObject:layoutAtt];
}
return layoutAtts;
}
// 對應(yīng)索引的布局.(不會主動調(diào)用)
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger count = [self.collectionView numberOfItemsInSection:0];
CGFloat WH = 50;
CGFloat centerX = self.collectionView.frame.size.width * 0.5;
CGFloat centerY = self.collectionView.frame.size.height * 0.5;
CGFloat randius = centerY- 30;
CGFloat angelMargin = M_PI * 2 / count;
UICollectionViewLayoutAttributes *layoutAtt = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGFloat a = sin(indexPath.row * angelMargin) * randius;
CGFloat b = cos(indexPath.row * angelMargin) * randius;
layoutAtt.center = CGPointMake(centerX + a, b+ centerY);
layoutAtt.size = CGSizeMake(WH, WH);
return layoutAtt;
}
3.點(diǎn)擊 cell 去掉對應(yīng)的 cell, 并且重新布局
- (void)collectionView:(nonnull UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
[self.images removeObjectAtIndex:indexPath.row];
[self.collectionView reloadData];
}