您的位置:首页 > 产品设计 > UI/UE

UICollectionView 不同大小Cell 等间距的实现

2015-05-12 17:17 225 查看
在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];
}
}


最后返回每个cell的layout情况

- (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;
}


提供项目下载地址:http://download.csdn.net/detail/chchong1234/8692121
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: