UICollectionView单元格起始边距

时间:2013-10-20 06:45:18

标签: customization uicollectionview

我正在使用UICollectionView来显示彩票号码。 我希望collectionView的单元格在自定义间距后启动,并且在该间距中我想显示一个Header,或者某种自定义UIView。

现在我的集合视图如下所示: 123 456 789

我希望它看起来像这样:

view12 345678 9 .....

我正在考虑使用自定义布局,但UICollectionViewFlowLayout符合我的目的。

这个问题有什么解决方案吗?

1 个答案:

答案 0 :(得分:2)

解决。

因为我只需调整布局,只是为了一点点,我决定使用UICollectionViewFlowLayout的子类。 这样,我可以按照自己的意愿“播放”布局,更改页眉/页脚的框架等。

我的解决方案是这样的:

·H

@interface MyUICollectionViewFlowLayout : UICollectionViewFlowLayout

@end

的.m

#define HEADER_VIEW_WIDTH 132
#define HEADER_VIEW_HEIGHT 44

@interface MyUICollectionViewFlowLayout ()

@end

@implementation MyUICollectionViewFlowLayout

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *allAttributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];

    for (UICollectionViewLayoutAttributes *attribute in allAttributes) {

// if it's a cell, change it's layout to be right after the Header, and in the same line.
        if (attribute.representedElementCategory == UICollectionElementCategoryCell) {

            switch (attribute.indexPath.row) {
                case 0:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH, 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 1:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 2:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 2 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 3:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 3 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 4:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 4 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 5:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 5 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 6:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 6 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
            // if it's a header view, move it to the same line as all the cells.
        } else if (attribute.representedElementCategory == UICollectionElementCategorySupplementaryView){

            attribute.frame = CGRectMake(0, 0 , HEADER_VIEW_WIDTH, HEADER_VIEW_HEIGHT);
        }
    }
    return allAttributes;
}



@end

我想这不是切换/情况,我可以写一些算法,但我更喜欢留下优化问题以供日后使用。