下面直接上代码:
第一步,首先在视图控制器中实例化:
//1.初始化layout
UICollectionViewFlowLayout *layout1 = [[UICollectionViewFlowLayout alloc] init];
layout1.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//设置headerView的尺寸大小
//layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 100);
//该方法也可以设置itemSize
layout1.itemSize =CGSizeMake(LXP_SCREEN_WIDTH/4,45);
// 设置列的最小间距
layout1.minimumInteritemSpacing = 5;
// 设置最小行间距
layout1.minimumLineSpacing = 0;
//2.初始化collectionView
_typeCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, LXP_SCREEN_WIDTH,45) collectionViewLayout:layout1];
_typeCollectionView.backgroundColor = [UIColor whiteColor];
_typeCollectionView.dataSource = self;
_typeCollectionView.delegate = self;
_typeCollectionView.showsVerticalScrollIndicator = NO;
_typeCollectionView.showsHorizontalScrollIndicator = NO;
[_typeCollectionView registerClass:[DSHChoiceTypeCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
第二步:实现cell ,cell自己实现只要在cell上加一个Label,宽度随着按钮文字宽度变化即可,然后返回按钮个数即可,最重点的是点击cell的效果,点击一个,其他是灰色,选中的是选中的颜色,下面是重点.
第三步:实例化一个数组,保存选中的cellItem,例如数组名是_rightLabelArray,则现在代理方法中实现下面俩代理:
//UICollectionView被选中时调用的方法
- ( void )collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath
*)indexPath {
//点击后添加因为只需要一个所以直接初始化掉重新赋值
_rightLabelArray = [NSMutableArray arrayWithObject:_nodeArr[indexPath.item]];
[collectionView reloadData];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
DSHChoiceTypeCollectionViewCell *cell = (DSHChoiceTypeCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
DSHMerchantTypeModel *MO = _nodeArr[indexPath.row];
[cell setNodeTitle:MO.nodeName];
[cell setBackgroundColor:[UIColor whiteColor]];
// 选中一个的方法
if (_rightLabelArray.count ==0)
{
// 第一次加载的方法
if (indexPath.row ==0
) {
cell.redLine.hidden = NO;
cell.nodeLabel.textColor = [UIColor navigationTintColor];
cell.nodeLabel.font = BIGTEXTFONTSIZE;
}else{
cell.redLine.hidden = YES;
cell.nodeLabel.textColor = LXP_TEXT_NORMCOLOR;
cell.nodeLabel.font = SMALLTEXTFONTSIZE;
}
}else{
if ([_rightLabelArray containsObject:_nodeArr[indexPath.item]])
{
cell.redLine.hidden = NO;
cell.nodeLabel.textColor = [UIColor navigationTintColor];
cell.nodeLabel.font = BIGTEXTFONTSIZE;
} else {
cell.redLine.hidden = YES;
cell.nodeLabel.textColor = LXP_TEXT_NORMCOLOR;
cell.nodeLabel.font = SMALLTEXTFONTSIZE;
}
}
}