iOS UICollectionView实现标签选择器

 更新时间:2020年6月30日 23:42  点击:1893

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

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.minimumInteritemSpacing = 5;//同一行不同cell间距
  self.minimumLineSpacing = 5;//行间距
  self.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
  self.scrollDirection = UICollectionViewScrollDirectionVertical;
  _originxArray = [NSMutableArray array];
  _originyArray = [NSMutableArray array];
 }
 return self;
}
 
#pragma mark - 重写父类的方法,实现瀑布流布局
#pragma mark - 当尺寸有所变化时,重新刷新
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
 return YES;
}
 
- (void)prepareLayout {
 [super prepareLayout];
}
 
#pragma mark - 处理所有的Item的layoutAttributes
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
 NSArray *array = [super layoutAttributesForElementsInRect:rect];
 NSMutableArray *mutArray = [NSMutableArray arrayWithCapacity:array.count];
 for(UICollectionViewLayoutAttributes *attrs in array){
  UICollectionViewLayoutAttributes *theAttrs = [self layoutAttributesForItemAtIndexPath:attrs.indexPath];
  [mutArray addObject:theAttrs];
 }
 return mutArray;
}
 
#pragma mark - 处理单个的Item的layoutAttributes
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
 CGFloat x = self.sectionInset.left;
 CGFloat y = 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) {
  if ([number floatValue] > maxY) {
   maxY = [number floatValue];
  }
 }];
 
 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的值了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • MySQL性能监控软件Nagios的安装及配置教程

    这篇文章主要介绍了MySQL性能监控软件Nagios的安装及配置教程,这里以CentOS操作系统为环境进行演示,需要的朋友可以参考下...2015-12-14
  • iOS APP h5快捷程序 .mobileconfig的生成

    1.从APP Store 下载Apple Configurator 2从一个管理点管理所有iOS设备应用程序,文档和配置文件。想要确保您的所有家庭成员在其每台iOS设备上都有类似的应用和文档,管理日益增...2021-12-23
  • iOS设置UIButton文字显示位置和字体大小、颜色的方法

    这篇文章给大家分享了iOS如何设置UIButton的文字显示位置和字体的大小、颜色,文中给出了示例代码,相信对大家的学习和理解很有帮助,有需要的朋友们下面来一起看看吧。...2020-06-30
  • iOS如何将图片裁剪成圆形

    这篇文章主要为大家详细介绍了iOS如何将图片裁剪成圆形,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-30
  • iOS给border设置渐变色的方法实例

    这篇文章主要给大家介绍了关于iOS给border设置渐变色的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-09
  • Jquery 获取指定标签的对象及属性的设置与移除

    1、先讲讲JQuery的概念,JQuery首先是由一个 America 的叫什么 John Resig的人创建的,后来又很多的JS高手也加入了这个团队。其实 JQuery是一个JavaScript的类库,这个类库集合了很多功能方法,利用类库你可以用简单的一些代...2014-05-31
  • iOS新版微信底部返回横条问题的解决

    这篇文章主要介绍了iOS新版微信底部返回横条问题的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-30
  • vue+axios全局添加请求头和参数操作

    这篇文章主要介绍了vue+axios全局添加请求头和参数操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-07-24
  • iOS蓝牙设备名称缓存问题的解决方法

    这篇文章主要给大家介绍了关于iOS蓝牙设备名称缓存问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-08
  • iOS新版微信底部工具栏遮挡问题完美解决

    这篇文章主要介绍了iOS新版微信底部工具栏遮挡问题完美解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-30
  • C# 如何设置label(标签)控件的背景颜色为透明

    这篇文章主要介绍了C# 如何设置label(标签)控件的背景颜色为透明,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2020-12-08
  • matplotlib之pyplot模块坐标轴标签设置使用(xlabel()、ylabel())

    这篇文章主要介绍了matplotlib之pyplot模块坐标轴标签设置使用(xlabel()、ylabel()),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
  • JS创建Tag标签的方法详解

    这篇文章主要介绍了JS创建Tag标签的方法,结合具体实例形式分析了javascript动态操作页面HTML元素实现tag标签功能的步骤与相关操作技巧,需要的朋友可以参考下...2017-06-15
  • C#删除UL LI中指定标签里文字的方法

    这篇文章主要介绍了C#删除UL LI中指定标签里文字的方法,涉及C#针对页面HTML元素进行正则匹配与替换的相关操作技巧,需要的朋友可以参考下...2020-06-25
  • 帝国CMS用灵动标签调用实现各种幻灯(焦点图)效果

    用灵动标签(e:loop)可以实现各种幻灯效果,本节讲解制作幻灯的基本方法。 如本站JS焦点图频道里的大部分幻灯图片效果都可以用灵动标签调用的。 ...2015-12-30
  • iOS新增绘制圆的方法实例代码

    这篇文章主要给大家介绍了关于iOS新增绘制圆的方法,文中通过示例代码介绍的非常详细,对各位iOS开发者们具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-06-30
  • iOS UIBezierPath实现饼状图

    这篇文章主要为大家详细介绍了iOS UIBezierPath实现饼状图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-03-20
  • 封装 axios+promise通用请求函数操作

    这篇文章主要介绍了封装 axios+promise通用请求函数操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-12
  • IOS获取各种文件目录路径的方法

    ios获取文件路径的方法,iphone沙箱模型的四个文件夹,通过documents,tmp,app,Library得到模拟器路径的简单方式,下面小编整理相关资料,把IOS获取各种文件目录路径的方式总结如下,需要的朋友可以参考下...2020-06-30
  • iOS UICollectionView实现卡片效果

    这篇文章主要为大家详细介绍了iOS UICollectionView实现卡片效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-30