UICollectionView

自定义布局:

@interface XMGLayout()

@property (nonatomic,strong) NSMutableArray * arrAttributs;

@end

//边距
static UIEdgeInsets inset={10.0,10.0,10.0,10.0};

@implementation XMGLayout

-(void)prepareLayout
{
    [super prepareLayout];
    
    self.arrAttributs=[NSMutableArray array];
    //
    NSInteger numberOfItem=[self.collectionView numberOfItemsInSection:0];
    for (NSInteger i=0; i<numberOfItem; i++) {
        NSIndexPath * indexpath=[NSIndexPath indexPathForRow:i inSection:0];
        UICollectionViewLayoutAttributes * attribute=[self layoutAttributesForItemAtIndexPath:indexpath];
        [self.arrAttributs addObject:attribute];
    }
    
}

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //创建cell属性
    UICollectionViewLayoutAttributes * attribute=[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    if (indexPath.row<=2) {
        attribute.frame=CGRectMake(inset.left, inset.top, 50, 50);
    }
    return attribute;
}

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    //返回cell属性的集合
    return self.arrAttributs;
}
-(CGSize)collectionViewContentSize
{
    return CGSizeMake(0, 600);
}

 //初始化(系统流式布局)

UICollectionViewFlowLayout * layout=[[UICollectionViewFlowLayout alloc]init];
UICollectionView *  collectionView= [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 200, 100) collectionViewLayout:layout];
collectionView.center = self.view.center;
[self.view addSubview:collectionView];
collectionView.backgroundColor = [UIColor colorWithRed:76/255.0 green:76/255.0 blue:76/255.0 alpha:0.8];
collectionView.dataSource = self;
collectionView.delegate = self;
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

//常用代理方法

//定义每个UICollectionViewcell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
}
//定义UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
}

//UICollectionViewcell被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}
//定义cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
}
//
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
}
//
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
}