CollectionView-布局之间的切换(水平和圆形,点击
2015-09-05 本文已影响2368人
Little_Dragon
布局切换.gif
- 我们就进行设定,当点击屏幕的时候,进行布局的切换.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 根据布局类型进行切换(如果是圆形布局)
if ([self.collectionView.collectionViewLayout isKindOfClass:[LXLCircleLayout class]]) {
// 设置布局为流水布局
LXLFlowLayout *flow = [[LXLFlowLayout alloc]init];
[self.collectionView setCollectionViewLayout:flow animated:YES];
}else{
// 如果不是圆形布局,就设置成圆形布局
[self.collectionView setCollectionViewLayout:self.circleLayout animated:YES];
}
}
- 我们发觉,我们确实能做到相互的切换,但是如果再次切换回圆形布局时,发现程序直接就处于崩溃了. 因为如果切换回去的话可能由于cell 数目的不确定性,或者重新切换的原因,造成布局再次出现错误,而无法正常显示. 我们通过查找,找到对应方法进行重写.(其中原因,我也不是很明白).
- (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];
// 调用方法,直接返回对应索引的布局
UICollectionViewLayoutAttributes *layoutAtt = [self layoutAttributesForItemAtIndexPath:indexPath];
// 如果返现只有一个 cell 的时候让你直接设置到中心点(相当于将以前的布局覆盖掉)
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;
}
// 对应索引的布局.(不会主动调用)
- (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.点击 cell 去掉对应的 cell, 并且重新布局
- (void)collectionView:(nonnull UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
[self.images removeObjectAtIndex:indexPath.row];
[self.collectionView reloadData];
}