您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

擴展 RCLabel:讓文字中的某幾個詞可點擊,並支援異步網路配圖

編輯:iOS 開發綜合

iOS 是個極度重視用戶體驗的平台,交互方案琳瑯滿目。但有個需求一直不好做:讓 label 裡的某幾個字可點擊。若改用 Button 之類的控件去拼,文字排版又會變成另一場噩夢。

這個需求在專案裡真實出現過:某個界面的文案中嵌著幾個廣告標籤,使用者點擊標籤位置要跳到對應的廣告頁。

CoreText 框架和若干第三方庫能解決,但直接用 CoreText 過於繁瑣;多數第三方庫側重富文本排版,對「文字超鏈接」這類能力的支持並不夠簡潔。與其硬啃,不如找一個輕巧的基礎再做針對性封裝。

RCLabel 就是這樣一個選擇:它把 HTML 字串排版成富文本,代碼量很小,且基於 CoreText,原生性與擴展性都不錯。

一、擴展 RCLabel 支援異步網路配圖

圖文混排是 UI 編程的常年重點,這塊最有名的框架是 DTCoreText。但某個專案中我沒有選它,原因有兩個:一是體積龐大,而需求其實不複雜;二是要在它內部改動東西的成本太高。最終選了 RCLabel,稍作優化便達標。

先明確需求:從服務器取到的是一個字串,其中需要放圖的位置是 HTML 的 img 標籤,標籤裡的資源路徑就是圖片請求地址。要求是最初渲染時先把圖片位置留白,再異步下載並填入。

幸運的是 RCLabel 本身就能解析帶 HTML 標籤的資料。以下是我封裝的展示 view:

@interface YHBaseHtmlView()<YHRTLabelImageDelegate>
{
    //RCLabel對象
    RCLabel * _rcLabel;
    //保存屬性 用於異步加載完成後刷新
    RTLabelComponentsStructure * _origenComponent;
    //含html標簽的數據字符串
    NSString * _srt;
}
@end
@implementation YHBaseHtmlView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
    //將rclabel初始化
        _rcLabel = [[RCLabel alloc]init];
        [self addSubview:_rcLabel];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _rcLabel = [[RCLabel alloc]initWithFrame:frame];
        [self addSubview:_rcLabel];
    }
    return self;
}
-(void)reSetHtmlStr:(NSString *)htmlStr{
    _srt = htmlStr;
    //這個代理是我額外添加的 後面解釋
    _rcLabel.imageDelegate=self;
    //設置frame
    _rcLabel.frame=CGRectMake(0, 0, self.frame.size.width, 0);
    //設置屬性
    _origenComponent = [RCLabel extractTextStyle:htmlStr IsLocation:NO withRCLabel:_rcLabel];
    _rcLabel.componentsAndPlainText = _origenComponent;
    //獲取排版後的size
    CGSize size = [_rcLabel optimumSize];
    //重新設置frame
    _rcLabel.frame=CGRectMake(0, 0, _rcLabel.frame.size.width, size.height);
    self.frame=CGRectMake(self.frame.origin.x, self.frame.origin.y, _rcLabel.frame.size.width, size.height);
}
//這是我額外添加的代理方法的實現
-(void)YHRTLabelImageSuccess:(RCLabel *)label{
    _origenComponent = [RCLabel extractTextStyle:_srt IsLocation:NO withRCLabel:_rcLabel];
    _rcLabel.componentsAndPlainText = _origenComponent;
   
    CGSize size = [_rcLabel optimumSize];
    _rcLabel.frame=CGRectMake(0, 0, _rcLabel.frame.size.width, size.height);
    self.frame=_rcLabel.frame;
    if ([self.delegate respondsToSelector:@selector(YHBaseHtmlView:SizeChanged:)]) {
        [self.delegate YHBaseHtmlView:self SizeChanged:self.frame.size];
    }
}

總結一下,RCLabel 的用法只有三步:

  1. 初始化並設置 frame;
  2. 用帶 HTML 標籤的資料初始化屬性;
  3. 把屬性設回去,並依 optimumSize 重設視圖 frame。

它強大且精簡,但處理圖片的部分只支援本地圖片——內部是透過 [UIImage imageNamed:] 渲染的,所以 img 標籤裡的路徑必須是本地圖檔名。要支援網路圖,需要動兩處:

1、在屬性設置方法中增加一個參數,用來區分本地與網路圖片:

//我在這個方法中添加了location這個bool值,實際上rclabel這個參數也是我添加的,是為了後面代理使用的
+ (RTLabelComponentsStructure*)extractTextStyle:(NSString*)dataimage IsLocation:(BOOL)location withRCLabel:(RCLabel *)rcLabel;

2、在實作中加入分支處理。原檔一千九百多行,理清邏輯花了不小的力氣,這裡只列出新增的部分:

#warning 這裡進行了兼容性處理
                if (location) {
                //本地圖片的渲染
                    if (tempURL) {
                        UIImage  *tempImg = [UIImage imageNamed:tempURL];
                        component.img = tempImg;
                    
                }
                }else{//這裡做遠程圖片數據的處理
                //這裡我進行了緩存的操作,這個緩存中心是我封裝的框架中的另一套東西,這裡可以不用在意
                    //先讀緩存
                    NSData * ceche = [[YHBaseCecheCenter sharedTheSingletion] readCecheFile:tempURL fromPath:YHBaseCecheImage];
                    if (ceche) {
                        UIImage * tempImg = [UIImage imageWithData:ceche];
                        component.img=tempImg;
                    }else{
                     //在分線程中進行圖片數據的獲取
                            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                            if (tempURL) {
                                NSData * data = [YHBaseData getDataWithUrl:tempURL];
                                if (data) {
                                    //獲取完成後村緩存
                                    //做緩存
                                    [[YHBaseCecheCenter sharedTheSingletion]writeCecheFile:data withFileID:tempURL toPath:YHBaseCecheImage];
                                         //賦值 回調代理
                                                   UIImage * tempImg = [UIImage imageWithData:data];
                                                   component.img=tempImg;
                                                          //這裡代理是我添加的,當圖片下載完成後 通知視圖重新排版
                                                      if ([[rcLabel imageDelegate]respondsToSelector:@selector(YHRTLabelImageSuccess:)]) {
                                                      //在主線程中執行回調
                                                                   //這個地方要在主線程中執行,否則刷新會有延時
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                     [[rcLabel imageDelegate] YHRTLabelImageSuccess:rcLabel];
                                        });
                                                                           
                                                                      
                                                   }
                                                     
                                          }
                                                           
                                                              
                                                  });
                                                 }                                              
                                                
                                                 }

兩個實作要點:緩存先讀後下載,命中就直接用;回調必須切回主線程,否則排版刷新會出現延時甚至閃現。

二、視圖類與模型類的設計

RCLabel 的核心能力是把 HTML 轉成富文本排版視圖。既然如此,我們可以把要顯示的文案拼成 HTML 字串,把可交互的部分包成 a 標籤,RCLabel 就會在你點擊該區域時回呼。

.h 檔:

//文本與超鏈接地址關聯的model類 後面會說
@class YHBaseLinkingLabelModel;
@protocol YHBaseLinkingLabelProtocol <NSObject>
@optional
/**
 *點擊超鏈接後出發的代理方法 model中有鏈接地址和文字
 */
-(void)YHBaseLinkingLabelClickLinking:(YHBaseLinkingLabelModel *)model;
/**
 *尺寸改變後出發的方法
 */
-(void)YHBaseLinkingLabelSizeChange:(CGSize)size;
@end
@interface YHBaseLinkingLabel : YHBaseView
/**
 *文字數組 裡面存放這文字對應的超鏈接對象
 */
@property(nonatomic,strong)NSArray<YHBaseLinkingLabelModel *> * textArray;
@property(nonatomic,weak)id<YHBaseLinkingLabelProtocol>delegate;
/**
 *設置文字顏色
 */
@property(nonatomic,strong)UIColor * textColor;
/**
 *設置超鏈接文字顏色
 */
@property(nonatomic,strong)UIColor * linkColor;
/**
 *設置字體大小
 */
@property(nonatomic,assign)NSUInteger fontSize;
/**
 *設置超鏈接字體大小
 */
@property(nonatomic,assign)int linkingFontSize;
/**
 *設置是否顯示下劃線
 */
@property(nonatomic,assign)BOOL isShowUnderLine;
@end

.m 檔:

@interface YHBaseLinkingLabel()<YHBaseHtmlViewProcotop>
@end
@implementation YHBaseLinkingLabel
{
    //以前博客中 封裝的顯示HTML字符串富文本的視圖
    YHBaseHtmlView * _label;
}
/*
// 重載一些初始化方法
- (instancetype)init
{
    self = [super init];
    if (self) {
        _label = [[YHBaseHtmlView alloc]init];
        [self addSubview:_label];
        [_label mas_makeConstraints:^(MASConstraintMaker *make) {
             make.leading.equalTo(@0);
             make.trailing.equalTo(@0);
             make.top.equalTo(@0);
             make.bottom.equalTo(@0);
        }];
        _label.delegate=self;
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        _label = [[YHBaseHtmlView alloc]init];
        [self addSubview:_label];
        [_label mas_makeConstraints:^(MASConstraintMaker *make) {
             make.leading.equalTo(@0);
             make.trailing.equalTo(@0);
             make.top.equalTo(@0);
             make.bottom.equalTo(@0);
        }];
        _label.delegate=self;
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _label = [[YHBaseHtmlView alloc]init];
        [self addSubview:_label];
        [_label mas_makeConstraints:^(MASConstraintMaker *make) {
             make.leading.equalTo(@0);
             make.trailing.equalTo(@0);
             make.top.equalTo(@0);
             make.bottom.equalTo(@0);
        }];
        _label.delegate=self;
    }
    return self;
}
//設置文本數組
-(void)setTextArray:(NSArray<YHBaseLinkingLabelModel *> *)textArray{
    _textArray = textArray;
    //進行html轉換
    NSString * htmlString = [self transLinkingDataToHtmlStr:textArray];
    //進行布局
    [_label reSetHtmlStr:htmlString];
   
}
-(void)setTextColor:(UIColor *)textColor{
    _textColor = textColor;
    _label.fontColor = textColor;
}
-(void)setLinkColor:(UIColor *)linkColor{
    _linkColor = linkColor;
    _label.linkingColor = linkColor;
}
-(void)setFontSize:(NSUInteger)fontSize{
    _fontSize = fontSize;
    [_label setFontSize:(int)fontSize];
}
-(void)setLinkingFontSize:(int)linkingFontSize{
    _linkingFontSize = linkingFontSize;
    [_label setLinkingSize:linkingFontSize];
}
-(void)setIsShowUnderLine:(BOOL)isShowUnderLine{
    _isShowUnderLine = isShowUnderLine;
    [_label setShowUnderLine:isShowUnderLine];
}
-(NSString *)transLinkingDataToHtmlStr:(NSArray<YHBaseLinkingLabelModel *> *)data{
    NSMutableString * mutStr = [[NSMutableString alloc]init];
    for (int i=0; i<data.count; i++) {
        //這個model中存放的是超鏈接部分的文字和對應的url
        YHBaseLinkingLabelModel * model = data[i];
        if (!model.linking) {
             [mutStr appendString:model.text];
        }else {
             [mutStr appendString:@"<a href="];
            [mutStr appendString:model.linking];
            [mutStr appendString:@">"];
            [mutStr appendString:model.text];
            [mutStr appendString:@"</a>"];
        }
    }
    return mutStr;
}
#pragma mark delegate
//點擊的回調
-(void)YHBaseHtmlView:(YHBaseHtmlView *)htmlView ClickLink:(NSString *)url{
    for (YHBaseLinkingLabelModel * model in _textArray) {
        if ([model.linking isEqualToString:url]) {
            if ([self.delegate respondsToSelector:@selector(YHBaseLinkingLabelClickLinking:)]) {
                [self.delegate YHBaseLinkingLabelClickLinking:model];
            return;
        }
        }
    }
}
//布局尺寸改變的回調
-(void)YHBaseHtmlView:(YHBaseHtmlView *)htmlView SizeChanged:(CGSize)size{
    if ([self.delegate respondsToSelector:@selector(YHBaseLinkingLabelSizeChange:)]) {
        [self.delegate YHBaseLinkingLabelSizeChange:size];
    }
}
@end

這裡用到的 YHBaseLinkingLabelModel 負責「文字 ↔ 鏈接」的映射,設計很樸素:

@interface YHBaseLinkingLabelModel : YHBaseModel
/**
 *文字內容
 */
@property(nonatomic,strong)NSString * text;
/**
 *超鏈接地址 nil則為無
 */
@property(nonatomic,strong)NSString * linking;
@end

YHBaseHtmlView 是對 RCLabel 的一層封裝,同時做了前述的網路圖擴展,代碼較長且在此前的文章中已有介紹,這裡不再重複。

使用端非常直觀:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    YHBaseLinkingLabel * label = [[YHBaseLinkingLabel alloc]initWithFrame:CGRectMake(100, 100, 200, 100)];
    NSMutableArray * array = [[NSMutableArray alloc]init];
    for (int i=0; i<6; i++) {
        YHBaseLinkingLabelModel * model = [[YHBaseLinkingLabelModel alloc]init];
        if (!(i%2)) {
             model.text =[NSString stringWithFormat:@"第%d個標簽",i];
             model.linking = [NSString stringWithFormat:@"第%d個標簽",i];
        }else{
             model.text = @",不能點得文字,";
        }
        [array addObject:model];
    }
    label.textColor = [UIColor blackColor];
    label.linkColor = [UIColor purpleColor];
    label.fontSize = 15;
    label.linkingFontSize = 17;
    label.isShowUnderLine=YES;
    label.delegate=self;
    label.textArray = array;
    [self.view addSubview:label];
   
}
-(void)YHBaseLinkingLabelClickLinking:(YHBaseLinkingLabelModel *)model{
    NSLog(@"%@",model.linking);
}

運行效果如下:

奇偶交錯的文案裡,只有偶數項可點擊並帶下劃線,點擊後直接拿到對應的 model——既保留了 label 的自然排版,又獲得了接近按鈕的交互能力。相對於自己啃 CoreText,這種「輕量庫 + 針對性封裝」的路子投入更小,可控性也更高。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved