在.h中声明
@property (nonatomic, strong) UICollectionView *myCollecionView;
遵循CollectionView协议
<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
.m文件中实现
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_collectionView.delegate = self;
_collectionView.dataSource = self;
//创建布局对象
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//itme与item之间的最小间距--默认是10
// flowLayout.minimumInteritemSpacing = 110;
// flowLayout.minimumLineSpacing = 100;
// flowLayout.itemSize = CGSizeMake(80, 80);
// flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//初始化CollectionView
_myCollecionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 667 - 284, 375, 284) collectionViewLayout:flowLayout];
_myCollecionView.tag = 200;
_myCollecionView.delegate = self;
_myCollecionView.dataSource = self;
_myCollecionView.backgroundColor = [UIColor redColor];
[self.view addSubview:_myCollecionView];
//注册单元格
[_myCollecionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"myCollecionViewCell"];
}
#pragma mark -UICollectionViewDataSource
//指定组的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 2;
}
//指定单元格的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 21;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
if (collectionView.tag == 100) {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewCell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:arc4random() % 10 * 0.1 green:arc4random() % 10 * 0.1 blue:arc4random() % 10 * 0.1 alpha:1];
return cell;
}else if (collectionView.tag == 200) {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCollecionViewCell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:arc4random() % 10 * 0.1 green:arc4random() % 10 * 0.1 blue:arc4random() % 10 * 0.1 alpha:1];
return cell;
}
return nil;
}
//动态地设置单元格的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(80, arc4random() % 80);
}
@end
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。