1、根据业务需要 弄了一个不规则cell 排版
主要是cell的size 的设定
方法一:继承UICollectionViewFlowLayout 做的操作
// 分组 section 设定size 可根据需要自动调整cell 的size
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
NSArray *array = [super layoutAttributesForElementsInRect:rect];
for (int i = 1; i < array.count; i++){
UICollectionViewLayoutAttributes * attribute = array[i];
UICollectionViewLayoutAttributes * attribute2 = array[i-1];
if (attribute.indexPath.section == attribute2.indexPath.section && attribute.frame.origin.x != 0) {
NSInteger maximumSpacing = 10;
NSInteger origin = CGRectGetMaxX(attribute2.frame);
if (origin + maximumSpacing + attribute.frame.size.width <= self.collectionView.frame.size.width - 10) {
CGRect frame = attribute.frame;
frame.origin.x = origin + maximumSpacing;
attribute.frame = frame;
} else {
CGRect frame = attribute.frame;
frame.origin.x = maximumSpacing;
frame.origin.y = CGRectGetMaxY(attribute2.frame) + maximumSpacing;
attribute.frame = frame;
}
}
}
return array;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
return YES;
}
正常添加一个collectionView
主要需要实现自定义cell 根据文本内容设定size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *txt = self.tags[indexPath.row];
CGSize size = [txt boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
return CGSizeMake(size.width + 15, 25);
}
代码:地址