CollectionViewFlowLayout
@implementationTagCollectionViewFlowLayout
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray*attributesList = [[NSArrayalloc]initWithArray:[superlayoutAttributesForElementsInRect:rect]copyItems:YES];
if(attributesList.firstObject!=nil) {//首个cell的Frame重置
UICollectionViewLayoutAttributes*currentLayoutAttributes = attributesList.firstObject;
if([selfcollectionViewLayoutAttributesIsCell:currentLayoutAttributes]) {
CGRectframe = currentLayoutAttributes.frame;
frame.origin.x=self.sectionInset.left;
currentLayoutAttributes.frame= frame;
}
}
for(NSUIntegeri =1; i < [attributesListcount]; i++) {
UICollectionViewLayoutAttributes*currentLayoutAttributes = attributesList[i];
if(![selfcollectionViewLayoutAttributesIsCell:currentLayoutAttributes]) {//判断是不是cell有可能是区头区尾
continue;
}
UICollectionViewLayoutAttributes*prevLayoutAttributes = attributesList[i -1];
NSIntegerorigin =CGRectGetMaxX(prevLayoutAttributes.frame);
NSIntegerprevLayoutY =CGRectGetMinY(prevLayoutAttributes.frame);
NSIntegercurrentCellY =CGRectGetMinY(currentLayoutAttributes.frame);
//判断上一个cell的最大x值+间距+当前cell的宽是否小于显示视图减去左右边距&&上一个cell和当前cell必须是同一个section
CGFloatcurrentCellMaxX = origin +self.minimumInteritemSpacing+ currentLayoutAttributes.frame.size.width;
CGFloatcontentWidth =self.collectionViewContentSize.width-self.sectionInset.left-self.sectionInset.right;
if(currentCellMaxX < contentWidth &&
prevLayoutAttributes.indexPath.section== currentLayoutAttributes.indexPath.section) {//如果小于并且是同一个区则当前cell给予换行
CGRectframe = currentLayoutAttributes.frame;
frame.origin.x= origin +self.minimumInteritemSpacing;
currentLayoutAttributes.frame= frame;
}
elseif(prevLayoutY != currentCellY) {
CGRectframe = currentLayoutAttributes.frame;
frame.origin.x=self.sectionInset.left;
currentLayoutAttributes.frame= frame;
}
}
returnattributesList;
}
- (BOOL)collectionViewLayoutAttributesIsCell:(UICollectionViewLayoutAttributes*)attributes
{
if(attributes.representedElementKind==UICollectionElementKindSectionHeader
|| attributes.representedElementKind==UICollectionElementKindSectionFooter) {
returnNO;
}
returnYES;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
returnYES;
}
@end
网友评论