平时使用UITableView比较多,一直对CollectionView不怎么熟悉,为了加深对CollectionVew的理解,特意写几个小的Demo熟悉一下。
关键代码:
_collectionView = ({
UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
layout.itemSize = CGSizeMake(130, 130);
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
layout.minimumLineSpacing = 2;
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 244, self.view.frame.size.width,130) collectionViewLayout:layout];
collectionView.backgroundColor = [UIColor whiteColor];
collectionView.delegate = self;
collectionView.dataSource = self;
collectionView.scrollsToTop = NO;
collectionView.showsVerticalScrollIndicator = NO;
collectionView.showsHorizontalScrollIndicator = NO;
[collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:kMyCollectionViewCellID];
[self.view addSubview:collectionView];
collectionView;
});
设置代理
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 8;
}
- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
return [collectionView dequeueReusableCellWithReuseIdentifier:kMyCollectionViewCellID forIndexPath:indexPath];
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
[(MyCollectionViewCell *)cell configureCellWithPostURL:@"postImage.jpg"];
}
```
[GitHub地址: https://github.com/JnLuffy/CollectionViewDemo1](https://github.com/JnLuffy/CollectionViewDemo1)