1、设置代理
@property (weak, nonatomic) IBOutlet UICollectionView *gridview;
_gridview.dataSource=self;
_gridview.delegate=self;
2、实现方法
笔者使用了一行3个,所以在计算宽度时除了3;间距是2所以3个子试图一共2个间距减去了4。
*注意:由于sizeForItemAtIndexPath是UICollectionViewDelegateFlowLayout的实现方法,但是
UICollectionViewDelegateFlowLayout协议的父级协议是UICollectionViewDelegate 所以可以直接实现sizeForItemAtIndexPath方法
//设置大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
float width=(self.view.bounds.size.width-4)/3;
return CGSizeMake(width, width);
}
//设置行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
return 2.0f;
}
//触发点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}
//设置允许高亮
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
//点击结束
- (void)collectionView:(UICollectionView *)colView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell=[colView cellForItemAtIndexPath:indexPath];
cell.backgroundColor=[UIColor whiteColor];
}
//点击中
- (void)collectionView:(UICollectionView *)colView didHighlightItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
UICollectionViewCell *cell=[colView cellForItemAtIndexPath:indexPath];
// cell.backgroundColor=RGB(226, 226, 226);
[cell setBackgroundColor:RGB(226, 226, 226)];
}
#define RGB(r, g, b) [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]