1. 程式人生 > >【IOS學習筆記】為UICollectionView設定自適應螢幕寬度以及點選效果

【IOS學習筆記】為UICollectionView設定自適應螢幕寬度以及點選效果

1、設定代理

@property (weak, nonatomic) IBOutlet UICollectionView *gridview;

_gridview.dataSource=self;
_gridview.delegate=self;


2、實現方法

筆者使用了一行3個,所以在計算寬度時除了3;間距是2所以3個子試圖一共2個間距減去了4。

*注意:由於sizeForItemAtIndexPathUICollectionViewDelegateFlowLayout的實現方法,但是

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)];
}


3、RGB為巨集定義

#define RGB(r, g, b)             [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]