美文网首页 ios零碎记录I love iOSiOS成长路线
UICollectionView实现的标签选择器

UICollectionView实现的标签选择器

作者: Code_Ninja | 来源:发表于2016-06-28 14:21 被阅读3093次

近来,在项目中需要实现一个类似兴趣标签的选择器。由于标签的文字长度不定,所以标签的显示长度就不定。为了实现效果,就使用了UICollectionView来实现了每行的标签数量不定、cell的宽度自适应的效果。先在此分享出来:

2017-09-07 update

现已支持多section效果和记录上一次选中的标签的效果,并解决UICollectionView在滑动过程中有些cell一会显示一会不显示的bug。bug详情见:UICollectionView滚动的时候会出现cell消失的情况,代码已更新到GitHub,欢迎star。

1、自适应UICollectionViewCell

这里只是在自适应UICollectionViewCell上放一个和UICollectionViewCell保持一样大小的按钮,当选中和取消选中时改变按钮的文字颜色和边框颜色:

#pragma mark---标签cell
@implementation YLTagsCollectionViewCell
-(instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame]){
        self.backgroundColor = [UIColor clearColor];
        _btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //此处可以根据需要自己使用自动布局代码实现
        _btn.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
        _btn.backgroundColor = [UIColor whiteColor];
        _btn.titleLabel.font = [UIFont systemFontOfSize:14];
        _btn.layer.borderWidth = 1.f;
        _btn.layer.cornerRadius = frame.size.height/2.0;
        _btn.layer.masksToBounds = YES;
        [_btn setTitleColor:HEXCOLOR(0x666666) forState:UIControlStateNormal];
        _btn.layer.borderColor = HEXCOLOR(0xdddddd).CGColor;
        _btn.userInteractionEnabled = NO;
        [self.contentView addSubview:_btn];
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    _btn.frame = CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height);
}

-(void)setSelected:(BOOL)selected
{
    [super setSelected:selected];
    _btn.layer.borderColor = selected?HEXCOLOR(0xffb400).CGColor:HEXCOLOR(0xdddddd).CGColor;
    [_btn setTitleColor:selected?HEXCOLOR(0xffb400):HEXCOLOR(0x666666) forState:UIControlStateNormal];
}

-(void)setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];
    _btn.layer.borderColor = highlighted?HEXCOLOR(0xffb400).CGColor:HEXCOLOR(0xdddddd).CGColor;
    [_btn setTitleColor:highlighted?HEXCOLOR(0xffb400):HEXCOLOR(0x666666) forState:UIControlStateNormal];
}

@end

2、UICollectionViewFlowLayout子类--YLWaterFlowLayout的实现

.h头文件

#import <UIKit/UIKit.h>

@class YLWaterFlowLayout;
@protocol  YLWaterFlowLayoutDelegate <NSObject>
/**通过代理获得每个cell的宽度*/
- (CGFloat)waterFlowLayout:(YLWaterFlowLayout *)layout 
widthAtIndexPath:(NSIndexPath *)indexPath;

@end

@interface YLWaterFlowLayout : UICollectionViewFlowLayout
@property (nonatomic,assign) id<YLWaterFlowLayoutDelegate> delegate;
@property(nonatomic,assign)CGFloat rowHeight;///< 固定行高

@end

.m文件

#import "YLWaterFlowLayout.h"

@interface YLWaterFlowLayout()
@property(nonatomic,strong)NSMutableArray *originxArray;
@property(nonatomic,strong)NSMutableArray *originyArray;
@end

@implementation YLWaterFlowLayout
#pragma mark - 初始化属性
- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupLayout];
        _originxArray = [NSMutableArray array];
        _originyArray = [NSMutableArray array];
    }
    return self;
}

- (void)setupLayout
{
    self.minimumInteritemSpacing = 5;//同一行不同cell间距
    self.minimumLineSpacing = 5;//行间距
    self.headerReferenceSize = CGSizeMake(0, 50);//设置section header 固定高度,如果需要的话
    self.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.scrollDirection = UICollectionViewScrollDirectionVertical;
}

#pragma mark - 重写父类的方法,实现瀑布流布局
#pragma mark - 当尺寸有所变化时,重新刷新
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return NO;
}

- (void)prepareLayout {
    [super prepareLayout];
}

#pragma mark - 所有cell和view的布局属性
//sectionheader sectionfooter decorationview collectionviewcell的属性都会走这个方法
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    for(UICollectionViewLayoutAttributes *attrs in array){
        //类型判断
        if(attrs.representedElementCategory == UICollectionElementCategoryCell){
            UICollectionViewLayoutAttributes *theAttrs = [self layoutAttributesForItemAtIndexPath:attrs.indexPath];
            attrs.frame = theAttrs.frame;
        }
    }
    return array;
}

#pragma mark - 指定cell的布局属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat x = self.sectionInset.left;
    //如果有sectionheader需要加上sectionheader高度
    CGFloat y = self.headerReferenceSize.height + self.sectionInset.top;
    //判断获得前一个cell的x和y
    NSInteger preRow = indexPath.row - 1;
    if(preRow >= 0){
        if(_originyArray.count > preRow){
            x = [_originxArray[preRow]floatValue];
            y = [_originyArray[preRow]floatValue];
        }
        NSIndexPath *preIndexPath = [NSIndexPath indexPathForItem:preRow inSection:indexPath.section];
        CGFloat preWidth = [self.delegate waterFlowLayout:self widthAtIndexPath:preIndexPath];
        x += preWidth + self.minimumInteritemSpacing;
    }
    
    CGFloat currentWidth = [self.delegate waterFlowLayout:self widthAtIndexPath:indexPath];
    //保证一个cell不超过最大宽度
    currentWidth = MIN(currentWidth, self.collectionView.frame.size.width - self.sectionInset.left - self.sectionInset.right);
    if(x + currentWidth > self.collectionView.frame.size.width - self.sectionInset.right){
        //超出范围,换行
        x = self.sectionInset.left;
        y += _rowHeight + self.minimumLineSpacing;
    }
    // 创建属性
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attrs.frame = CGRectMake(x, y, currentWidth, _rowHeight);
    _originxArray[indexPath.row] = @(x);
    _originyArray[indexPath.row] = @(y);
    return attrs;
}

#pragma mark - CollectionView的滚动范围
- (CGSize)collectionViewContentSize
{
    CGFloat width = self.collectionView.frame.size.width;
    __block CGFloat maxY = 0;
    [_originyArray enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat y = [number floatValue];
        if (y > maxY) {
            maxY = y;
        }
    }];
    return CGSizeMake(width, maxY + _rowHeight + self.sectionInset.bottom);
}

@end

实现思路:在YLWaterFlowLayout中使用originxArray和originyArray两个个数组记录了每一个自定义YLTagsCollectionViewCell的位置x和y。

-(UICollectionViewLayoutAttributes *) layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath方法中通获得与当前YLTagsCollectionViewCell临近的“上一个YLTagsCollectionViewCell”的位置和尺寸信息,将上一个cell的x加上上一个cell的width来得到当前cell的x。同时还要判断当前cell的x+width是否会超越出屏幕右边缘,如果超出,则表明需要换行显示了,这时候就要修改y的值了。

3、效果图

YLTagsChooser.gif

大家可以参考这种思路来实现其他类似的标签选择视图。
demo地址YLTagsChooser

相关文章

  • UICollectionView实现的标签选择器

    近来,在项目中需要实现一个类似兴趣标签的选择器。由于标签的文字长度不定,所以标签的显示长度就不定。为了实现效果,就...

  • 【问题收集】UICollectionView:设置content

    场景 上面的标签栏是使用 UICollectionView 实现的,需要实现的效果是: 规则:上面的标签栏,选中的...

  • iOS 多标签控制器

    使用 UIScrollView 与 UICollectionView 实现的多标签控制器,可实现拖动、排序等功能 ...

  • 学习CSS初识

    标签选择器 HTML标签作为标签选择器的名称 … 、 、 类选择器 <标签名 class= "类名称">标签内容<...

  • CSS

    CSS基本语法结构 eg: style标签 标签选择器HTML标签作为标签选择器的名称 … 、 、 类选择器<标签...

  • iOS不同宽度的标签(用简单的UILabel来实现)

    这篇文章是用UILabel配合模型来实现不同宽度的标签、今后我会出一篇用UICollectionView来实现同样...

  • 2018-08-14 HTML学习CSS选择器与伪类选择器

    选择器 1. 元素选择器(标签选择器):标签名 选中所有的标签名对应的标签例:所有a标签 2.id选择器:#id属...

  • css选择器和文本标签

    1、css选择器 标签选择器 id选择器 类选择器 层级选择器 组选择器 伪类选择器 文本标签 em标签用于表示一...

  • No.7 CSS选择器

    一、CSS基础选择器 1.标签选择器 标签选择器(元素选择器)是指用 HTML 标签名称作为选择器,按标签名称分类...

  • css中的target选择器

    :target选择器可用于当前活动的target元素的样式。通过a标签绑定id元素,实现点击a标签修改当前a标签链...

网友评论

  • paintingStyle:能增加拖动排序吗
  • 啥子都不会_f7fc:楼主 为啥我用了这个layout 不能滑动?
    Code_Ninja:检查一下代码逻辑:smile:
  • 不会游泳的飞鱼:有没有点击选中 再次点击取消 最后将选择的所有标签返回
    Code_Ninja:github最新代码有这个逻辑
  • cute赵:先显示collectionview 然后再请求数据,空白。只能先请求数据,再addsubview collectionview
    captain_Lu:修改此处代码即可
    if(_framesArray.count > 0){
    // return;
    [_framesArray removeAllObjects];
    }
  • Z了个Y:楼主 如果有多个分区 高度算不准啊
    Code_Ninja:@Z了个Y 你的需求是多个section,每个section一个header的效果吧?等我抽时间改成多个section的效果。
    Z了个Y:@Code_Ninja 尝试修改了下 但是没有实现 可否指点一下 :blush:
    Code_Ninja:我这里只是做了一个分区的demo,需要多个分区的话,需要修改代码哦,参照demo修改一下代码吧。
  • 透支未来:设置多个区 ,怎么只显示第一个区里的内容
    Code_Ninja:@MasterY 你先看看我的demo,然后模仿着做吧,做不了再问我。
    MasterY:@Code_Ninja 怎么改呢?
    Code_Ninja:@透支未来 :smile: 我这里只是做了一个分区的demo,需要多个分区的话,需要修改代码哦,参照demo修改一下源码即可。
  • 秘制鸭腿:楼主, 自定义flowLayout的话 你viewForSupplementaryElementOfKind方法能执行吗?
    Code_Ninja:@秘制鸭腿 :joy: 我刚才更新的代码,你再去看看。
    秘制鸭腿:@Code_Ninja 楼主,我在你的Demo基础上,按你的步骤来, viewForSupplementaryElementOfKind依旧不执行.如果你换成UICollectionViewFlowLayout就可以,好奇怪
    Code_Ninja:@秘制鸭腿 可以。拿sectionheader举例:
    第一步:你需要设置layout的headerReferenceSize属性或者实现UICollectionViewDelegateFlowLayout的- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section方法;
    第二步:注册sectionheader:[_myCollectionView registerClass:[YLCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YLCollectionReusableView"];
    第三步:在方法- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath中返回自定义sectionheader
    需要注意的是在- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect方法中应该加上判断当前UICollectionViewLayoutAttributes的representedElementCategory属性是否是UICollectionElementCategoryCell类型的,不能在这里改变了sectionheader的高度导致显示异常。因为所有view和cell的属性都会调用该方法。
  • carson6931:不错
  • Cocoa_Coder:感谢分享 :smile:

本文标题:UICollectionView实现的标签选择器

本文链接:https://www.haomeiwen.com/subject/oojtjttx.html