iOS利用Label实现的简单高性能标签TagView

2020-01-21 05:10:31刘景俊

前言

我相信很多人在开发者都有这样的需求,标签展示(如下图)

ios,label,标签,富文本label,tagview

很多人都可以自己实现(网上别人写的也很多,但是别人写的总有不满足自己需求的点),实现的方法也很多种,比如动态添加view,使用UICollectionView等等。这种实现方法不是不好,但是当列表比较复杂,数据比较多的时候,可曾想过性能会怎么样呢?

在一次深入了解富文本的时候,突发其想,好像富文本能达到这种效果,也就是一个ios/203357.html">ios/299281.html">label就可以实现这种标签的效果了,效果性能就不用多说了,再加上YYLabel的异步绘制,真是锦上添花啊。

XWTagView(高性能标签)

优势:

支持自定义标签外观,上下距离,左右距离,对齐方式; 异步绘制性能得到很大提升。

XWTagMaker(标签外观配置)


#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef enum : NSUInteger {
 XWTagAlignmentLeft = 0,
 XWTagAlignmentCenter = 1,
 XWTagAlignmentRight = 2,
} XWTagAlignment;
@interface XWTagMaker : NSObject

//标签边框
@property (nonatomic) CGFloat strokeWidth;

//标签边框颜色
@property (nullable, nonatomic, strong) UIColor *strokeColor;

//路径的连接点形状,] kCGLineJoinMiter(默认全部连接),kCGLineJoinRound(圆形连接),kCGLineJoinBevel(斜角连接)
@property (nonatomic) CGLineJoin lineJoin;

//标签内容内边距
@property (nonatomic) UIEdgeInsets insets;

//标签圆角
@property (nonatomic) CGFloat cornerRadius;

//标签填充颜色
@property (nullable, nonatomic, strong) UIColor *fillColor;

//字体大小
@property (nonatomic,strong) UIFont * _Nullable font;

//字体颜色
@property (nonatomic,strong) UIColor * _Nonnull textColor;

//标签上下间距
@property (nonatomic,assign) CGFloat lineSpace;

//标签左右间距
@property (nonatomic,assign) CGFloat space;

//标签的最大宽度-》以便计算高度
@property (nonatomic,assign) CGFloat maxWidth;

//对齐方式
@property (nonatomic,assign) XWTagAlignment tagAlignment;
@end

以上就是标签外观的一些属性,注释得很清楚,包含了对齐方式,每个属性都有默认值,maxWidth这个属性是必须非空的以便计算高度和换行(默认值是屏幕宽度)

XWTagView(继承自YYLabel)

XWTagView.h


#import "YYText.h"
#import "XWTagMaker.h"
#import "NSMutableAttributedString+XWTagView.h"
@interface XWTagView : YYLabel
/**
 *NSMutableAttributedString
 */
@property (nonatomic,strong) NSMutableAttributedString * tagAttr;
@end

XWTagView.m主要代码

XWTagView的内部实现很简单,只是简单的富文本赋值