标签:uicollectionview cell size ios space
在IOS项目中有时会用到UICollectionView控件,大家应该都不太陌生,即便有没用过的同学,看一下教程也能轻松的掌握。不过要实现cell大小不同,又要等间距,应该怎么做呢?如下图:
一、首先需要创建EqualSpaceFlowLayout继承UICollectionViewFlowLayout,如下面的代码:
#import <UIKit/UIKit.h> @protocol EqualSpaceFlowLayoutDelegate<UICollectionViewDelegateFlowLayout> @end @interface EqualSpaceFlowLayout : UICollectionViewFlowLayout @property (nonatomic,weak) id<EqualSpaceFlowLayoutDelegate> delegate; @end
在EqualSpaceFlowLayout.m文件中重载- (void)prepareLayout方法实现每个cell的布局,如下
#pragma mark - Methods to Override
- (void)prepareLayout
{
[super prepareLayout];
NSInteger itemCount = [[self collectionView] numberOfItemsInSection:0];
self.itemAttributes = [NSMutableArray arrayWithCapacity:itemCount];
CGFloat xOffset = self.sectionInset.left;
CGFloat yOffset = self.sectionInset.top;
CGFloat xNextOffset = self.sectionInset.left;
for (NSInteger idx = 0; idx < itemCount; idx++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:idx inSection:0];
CGSize itemSize = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
xNextOffset+=(self.minimumInteritemSpacing + itemSize.width);
if (xNextOffset > [self collectionView].bounds.size.width - self.sectionInset.right) {
xOffset = self.sectionInset.left;
xNextOffset = (self.sectionInset.left + self.minimumInteritemSpacing + itemSize.width);
yOffset += (itemSize.height + self.minimumLineSpacing);
}
else
{
xOffset = xNextOffset - (self.minimumInteritemSpacing + itemSize.width);
}
UICollectionViewLayoutAttributes *layoutAttributes =
[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
layoutAttributes.frame = CGRectMake(xOffset, yOffset, itemSize.width, itemSize.height);
[_itemAttributes addObject:layoutAttributes];
}
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
return (self.itemAttributes)[indexPath.item];
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
return [self.itemAttributes filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UICollectionViewLayoutAttributes *evaluatedObject, NSDictionary *bindings) {
return CGRectIntersectsRect(rect, [evaluatedObject frame]);
}]];
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return NO;
}
UICollectionView 不同大小Cell 等间距的实现
标签:uicollectionview cell size ios space
原文地址:http://blog.csdn.net/chchong1234/article/details/45671801