UICollectionView是iOS开发常用UI控件,自定义UICollectionView流程方便开发使用。
1.实现自定义CollectionView首先继承CollectionView.
#import <UIKit/UIKit.h>
@interface MyOrderMultyPartsCollectionCell : UICollectionViewCell
@end
2.重写初始化方法,实现代理以及数据源方法
#import "MyOrderMultyPartsCollectionView.h"
#import "MyOrderMultyPartsCollectionCell.h"
@interface MyOrderMultyPartsCollectionView ()<UICollectionViewDelegate,UICollectionViewDataSource>
@end
NSString * const reuseID = @"MyOrderMultyPartsCollectionCell";
@implementation MyOrderMultyPartsCollectionView
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
self=[super initWithFrame:frame collectionViewLayout:layout];
if (self) {
[self registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseID];
self.backgroundColor=[UIColor whiteColor];
self.delegate=self;
self.dataSource=self;
}
return self;
}
#pragma mark ---- UICollectionViewDataSource
//定义每个Cell的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
CGSize size = CGSizeMake(100,100);
return size;
}
//两个cell之间的间距(同一行的cell的间距)
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
// return 4;
//}
//这个是两行cell之间的间距(上下行cell的间距)
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
return 4;
}
//定义每个Section的四边间距
//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//return UIEdgeInsetsMake(10, 0, 10, 10);//分别为上、左、下、右
//}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 6;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
cell.layer.masksToBounds = YES;
cell.backgroundColor = [UIColor purpleColor];
return cell;
}
@end
3.使用的时候
UICollectionViewFlowLayout* khlayout = [[UICollectionViewFlowLayout alloc] init];
//collection滚动方向
khlayout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
//khlayout.itemSize=CGSizeMake(100, 100);
MyOrderMultyPartsCollectionView * cview = [[MyOrderMultyPartsCollectionView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, contentView.height) collectionViewLayout:khlayout];[contentView addSubview:cview];