溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

iOS利用Label實現(xiàn)的簡單高性能標簽TagView

發(fā)布時間:2020-08-22 18:50:17 來源:腳本之家 閱讀:502 作者:恩說吧 欄目:移動開發(fā)

前言

我相信很多人在開發(fā)者都有這樣的需求,標簽展示(如下圖)

iOS利用Label實現(xiàn)的簡單高性能標簽TagView

很多人都可以自己實現(xiàn)(網(wǎng)上別人寫的也很多,但是別人寫的總有不滿足自己需求的點),實現(xiàn)的方法也很多種,比如動態(tài)添加view,使用UICollectionView等等。這種實現(xiàn)方法不是不好,但是當列表比較復雜,數(shù)據(jù)比較多的時候,可曾想過性能會怎么樣呢?

在一次深入了解富文本的時候,突發(fā)其想,好像富文本能達到這種效果,也就是一個label就可以實現(xiàn)這種標簽的效果了,效果性能就不用多說了,再加上YYLabel的異步繪制,真是錦上添花啊。

XWTagView(高性能標簽)

優(yōu)勢:

  • 支持自定義標簽外觀,上下距離,左右距離,對齊方式;
  • 異步繪制性能得到很大提升。

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;

//標簽內(nèi)容內(nèi)邊距
@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的內(nèi)部實現(xiàn)很簡單,只是簡單的富文本賦值

-(instancetype)init{
 if (self = [super init]) {
  [self initTagView];
 }
 return self;
}

-(instancetype)initWithFrame:(CGRect)frame{
 if (self = [super initWithFrame:frame]) {
  [self initTagView];
 }
 return self;
}

-(void)initTagView{
 self.numberOfLines = 0;
 self.lineBreakMode = NSLineBreakByWordWrapping;
 self.displaysAsynchronously = YES;
}

-(void)setTagAttr:(NSMutableAttributedString *)tagAttr{
 _tagAttr = tagAttr;
 [self initTagView];
 self.attributedText = _tagAttr;
}

NSMutableAttributedString +XWTagView的核心代碼

1.tip:創(chuàng)建標簽的時候在子線程體驗更好(生成富文本比較耗時)

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "XWTagMaker.h"
@interface NSMutableAttributedString (XWTagView)
//當前標簽富文本的高度
@property (nonatomic,assign) CGFloat tagHeight;
/**
 快速創(chuàng)建tag標簽所需樣式
 @param tags 字符串數(shù)組
 @param maskBlock 初始化標簽樣式
 @return 標簽所需的NSMutableAttributedString
 */
+(NSMutableAttributedString *)xw_makeTagAttributedString:(NSArray<NSString *> *)tags tagMaker:(void (^)(XWTagMaker *))maskBlock;
@end
+(NSMutableAttributedString *)xw_makeTagAttributedString:(NSArray<NSString *> *)tags tagMaker:(void (^)(XWTagMaker *))maskBlock{
 NSMutableAttributedString *text = [NSMutableAttributedString new];
 NSInteger height = 0;
 XWTagMaker *maker = [[XWTagMaker alloc] init];
 if (maskBlock) {
  maskBlock(maker);
 }
 for (int i = 0; i < tags.count; i++) {
  NSString *tag = tags[i];
  NSMutableAttributedString *tagText = [[NSMutableAttributedString alloc] init];
  //標簽左內(nèi)邊距
  [tagText appendAttributedString:[self creatEmptyAttributeString:fabs(maker.insets.left)]];
  //標簽內(nèi)容
  [tagText yy_appendString:tag];
  //標簽右內(nèi)邊距
  [tagText appendAttributedString:[self creatEmptyAttributeString:fabs(maker.insets.right)]];
  //設(shè)置外觀
  [self beautifyAttributedStringWithText:tagText ranges:NSMakeRange(0, tagText.length) maker:maker];
  //左右間距
  [tagText appendAttributedString:[self creatEmptyAttributeString:maker.space]];
  //行間距等設(shè)置
  [text appendAttributedString:tagText];
  text.yy_lineSpacing = maker.lineSpace;
  text.yy_lineBreakMode = NSLineBreakByWordWrapping;
  //高度計算(超最大范圍加換行符手動換行)
  YYTextContainer *tagContarer = [YYTextContainer new];
  tagContarer.size = CGSizeMake(maker.maxWidth - 3,CGFLOAT_MAX);
  YYTextLayout *tagLayout = [YYTextLayout layoutWithContainer:tagContarer text:text];
  if (tagLayout.textBoundingSize.height > height) {
   if (height != 0) {
    [text yy_insertString:@"\n" atIndex:text.length - tagText.length];
    
   }
   tagLayout = [YYTextLayout layoutWithContainer:tagContarer text:text];
   height = tagLayout.textBoundingSize.height;
  }
 }
 
 //高度記錄(富文本已擴展高度屬性)
 text.tagHeight = height + maker.lineSpace + fabs(maker.insets.top) + fabs(maker.insets.bottom) ;
 //對齊方向設(shè)置(頭尾自動縮進1.5)
 [text addAttribute:NSParagraphStyleAttributeName value:[self creatTextStyle:maker]
     range:NSMakeRange(0, text.length)];
 return text;
}

+(void) beautifyAttributedStringWithText:(NSMutableAttributedString * )tagText ranges:(NSRange)range maker:(XWTagMaker *)maker{
 //標簽字體顏色設(shè)置
 tagText.yy_font = maker.font;
 tagText.yy_color = maker.textColor;
 [tagText yy_setTextBinding:[YYTextBinding bindingWithDeleteConfirm:NO] range:tagText.yy_rangeOfAll];
 //設(shè)置item外觀樣式
 [tagText yy_setTextBackgroundBorder:[self creatTextBoard:maker] range:range]; 
}

/**
 外觀樣式
 @param maker tag外觀配置
 @return 返回YYTextBorder
 */
+(YYTextBorder *)creatTextBoard:(XWTagMaker *)maker{
 YYTextBorder *border = [YYTextBorder new];
 border.strokeWidth = maker.strokeWidth;
 border.strokeColor = maker.strokeColor;
 border.fillColor = maker.fillColor;
 border.cornerRadius = maker.cornerRadius; // a huge value
 border.lineJoin = maker.lineJoin;
 border.insets = UIEdgeInsetsMake(maker.insets.top, 0, maker.insets.bottom, 0);
 return border;
}

+(NSMutableAttributedString *)creatEmptyAttributeString:(CGFloat)width{
 NSMutableAttributedString *spaceText = [NSMutableAttributedString yy_attachmentStringWithContent:[[UIImage alloc]init] contentMode:UIViewContentModeScaleToFill attachmentSize:CGSizeMake(width, 1) alignToFont:[UIFont systemFontOfSize:0] alignment:YYTextVerticalAlignmentCenter];
 return spaceText;
 
}

+(NSMutableParagraphStyle *)creatTextStyle:(XWTagMaker *)maker{
 NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
 style.lineSpacing = maker.lineSpace;
 style.firstLineHeadIndent = 1.5;
 style.headIndent = 1.5 ;//設(shè)置與首部的距離
 style.tailIndent = maker.tagAlignment == NSTextAlignmentRight ? maker.maxWidth - fabs(maker.insets.right) : maker.maxWidth - 1.5; //設(shè)置與尾部的距離
 switch (maker.tagAlignment) {
  case XWTagAlignmentLeft:
   style.alignment = NSTextAlignmentLeft;
   break;
  case XWTagAlignmentCenter:
   style.alignment = NSTextAlignmentCenter;
   break;
  case XWTagAlignmentRight:
   style.alignment = NSTextAlignmentRight;
   break;
  default:
   break;
 }
 return style;
}

細心的同學會發(fā)現(xiàn)要怎么知道他的高度?(當然如果您用的是自動布局可以不用管這個屬性,畢竟label自動布局會自動自適應(yīng))從上面代碼可以看出來,最后返回的是富文本NSMutableAttributedString,為了更加方便,我便為NSMutableAttributedString擴展了個高度屬性tagHeight(當前標簽富文本的高度以便外部獲取使用和緩存。

看起來很簡單,也很容易理解(就是把標簽數(shù)組變成一個富文本已達到標簽的效果),接下來就看看怎么用吧

XWTagView *tagView = [[XWTagView alloc] initWithFrame:CGRectMake(10, 100, self.view.bounds.size.width-20, 50)];
 NSArray<NSString *> *tags = @[
         @"標簽tag1",@"表面",@"哈哈哈",@"測試測試",@"不不不不",@"無敵啊",@"標簽",@"這樣喊得好嗎",
         @"哈哈哈",@"嘻嘻嘻",@"呵呵呵",@"標簽",@"表面兄弟",@"你好啊",@"不想你了哦",@"不要這樣子啦"
         ];
 NSMutableAttributedString *attr = [NSMutableAttributedString xw_makeTagAttributedString: tags tagMaker:^(XWTagMaker *make){
  make.strokeColor = [UIColor redColor];
  make.fillColor = [UIColor clearColor];
  make.strokeWidth = 1;
  make.cornerRadius = 100;
  make.insets = UIEdgeInsetsMake(-2, -6, -2, -6);
  make.font = [UIFont systemFontOfSize:16];
  make.textColor = [UIColor blackColor];
  make.lineSpace = 10;
  make.space = 10;
  make.maxWidth = [UIScreen mainScreen].bounds.size.width - 20;
  make.tagAlignment = XWTagAlignmentLeft;
 }];
 tagView.tagAttr = attr;
 tagView.frame = CGRectMake(10, 100, self.view.bounds.size.width - 20, attr.tagHeight);
 [self.view addSubview:tagView];

看起來是不是很簡單,一個make就可以配置標簽樣式了,如果您是比較復雜的列表的話,這樣一個label實現(xiàn)的標簽性能完全不用擔心,如果您是個追求性能的人,可以開啟YYLabel的異步繪制displaysAsynchronously(在iPhone4s上有明顯效果)。

效果圖如下

iOS利用Label實現(xiàn)的簡單高性能標簽TagView

iOS利用Label實現(xiàn)的簡單高性能標簽TagView

當我以為大功告成的時候,最后還是讓我發(fā)現(xiàn)了個問題,從上面代碼可以看出標簽的的左右間隔是用空字符串隔開的(這是一個缺陷,有比較好的解決方法的可以聯(lián)系我),說到這細心的同學應(yīng)該可以猜到是什么問題了,你們可曾注意過當label右對齊的時候,最右邊的空格或者空字符串是不起作用的,最終想到了個解決辦法(首尾自動縮進1.5),可能不是最好的解決方案,但是足以解決出現(xiàn)的問題,詳細的見如下代碼

 NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
 style.lineSpacing = maker.lineSpace;
 style.firstLineHeadIndent = 1.5;
 style.headIndent = 1.5 ;//設(shè)置與首部的距離
 style.tailIndent = maker.tagAlignment == NSTextAlignmentRight ? maker.maxWidth - fabs(maker.insets.right) : maker.maxWidth - 1.5; //設(shè)置與尾部的距離
 switch (maker.tagAlignment) {
  case XWTagAlignmentLeft:
   style.alignment = NSTextAlignmentLeft;
   break;
  case XWTagAlignmentCenter:
   style.alignment = NSTextAlignmentCenter;
   break;
  case XWTagAlignmentRight:
   style.alignment = NSTextAlignmentRight;
   break;
  default:
   break;
 }

熟悉富文本的同學都知道tailIndent是與尾部的距離,利用好這一點可以很好的解決問題,后續(xù)會加上點擊事件。

總結(jié)

富文本很強大,能做的不只只這些,很多黑科技等著你去發(fā)現(xiàn)哦,當然如果您覺得我寫的不錯,希望您點個贊。

好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI