您的位置:首页 > 产品设计 > UI/UE

【IOS学习笔记】为UICollectionView设置自适应屏幕宽度以及点击效果

2015-12-27 18:28 991 查看
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)];
}


3、RGB为宏定义
#define RGB(r, g, b)             [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: