iOS 輕量級富文本方案

項目中多多少少會遇到一些需求,需要給部分文案添加點擊事件。例如:"我已閱讀《xxx協(xié)議》",這個時候最簡單的實現(xiàn)方案是:添加一個button覆蓋上去。但如果有多處文案需要添加點擊事件,就會比較懵逼。下面我說下我的實現(xiàn)方案。

最初的時候我打算使用CoreText實現(xiàn),查詢了相關(guān)資料后發(fā)現(xiàn)自己不能很快的造出輪子,雖然網(wǎng)上有很多現(xiàn)成的輪子可以用,但是我并不想只純粹的搬運代碼。需要直接拿輪子的可以點擊這里。于是我把目光轉(zhuǎn)移到TextKit上面,發(fā)現(xiàn)相關(guān)代碼要比CoreText易讀易懂很多,于是就有了下面的事情。

言歸正傳,給Label的文字添加點擊事件,首先需要讓文字有不同的顏色,不同的字號,這個時候就需要用到 NSMutableAttributedString,下面是一些常規(guī)的處理。

NSMutableAttributedString

  • 設(shè)置顏色
///根據(jù)range設(shè)置顏色
-(void)addColor:(UIColor *)color range:(NSRange)range
{
    if (range.length > self.attributedText.length) {
        return;
    }
    [self.attributedText addAttribute:NSForegroundColorAttributeName value:color range:range];
}
  • 設(shè)置字體大小
///根據(jù)range設(shè)置字體大小
-(void)addFontSize:(CGFloat)size range:(NSRange)range
{
    if (range.length > self.attributedText.length) {
        return;
    }
    UIFont * font;
    //判斷是其他字體
    if (self.fontName.length == 0) {
        //判斷是否是粗體
        if (self.isBold) {
            font = [UIFont boldSystemFontOfSize:size];
        }
        else
        {
            font = [UIFont systemFontOfSize:size];
        }
    }
    else
    {
        font = [UIFont fontWithName:self.fontName size:size];
    }
    [self.attributedText addAttribute:NSFontAttributeName value:font range:range];
}
  • 設(shè)置字間距
///設(shè)置字間距
-(void)addKerningWithSpace:(CGFloat)space
{
    [self.attributedText addAttribute:NSKernAttributeName value:[NSNumber numberWithFloat:space] range:NSMakeRange(0, 10)];
}
  • 添加單刪除線
///添加單刪除線
-(void)addSingleStrikethroughWithColor:(UIColor * )color range:(NSRange)range
{
    [self.attributedText addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:range];
    if (color) {
        [self.attributedText addAttribute:NSStrikethroughColorAttributeName value:color range:range];
    }
}
  • 添加單下劃線
///添加單下劃線
-(void)addSingleUnderlineWithColor:(UIColor * )color range:(NSRange)range
{
    [self.attributedText addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:range];
    if (color) {
        [self.attributedText addAttribute:NSUnderlineColorAttributeName value:color range:range];
    }
}
  • 設(shè)置基線偏移值
///設(shè)置基線偏移值
-(void)addBaselineOffset:(CGFloat)offset range:(NSRange)range
{
    [self.attributedText addAttribute:NSBaselineOffsetAttributeName value:[NSNumber numberWithFloat:offset] range:range];
}
  • 設(shè)置凸版印刷體效果
///設(shè)置凸版印刷體效果
-(void)addEffectLetterpressWithRange:(NSRange)range
{
    [self.attributedText addAttribute:NSTextEffectAttributeName value:NSTextEffectLetterpressStyle range:range];
}
  • 插入圖片
///在某個位置插入圖片 不要在結(jié)尾處插入圖片,在iOS8的某個小版本會出現(xiàn)bug
-(void)addAttachmentWithImageName:(NSString *)imageName index:(NSInteger)index size:(CGSize)size
{
    UIImage * image = [UIImage imageNamed:imageName];
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //設(shè)置默認(rèn)大小
    if (CGSizeEqualToSize(size, CGSizeZero)) {
        attachment.bounds = CGRectMake(0, 0, 20, 20);
    }
    else
    {
        attachment.bounds = CGRectMake(0, 0, size.width, size.height);
    }
    NSAttributedString * attibutedString = [NSAttributedString attributedStringWithAttachment:attachment];
    [self.attributedText insertAttributedString:attibutedString atIndex:index];
}
  • 設(shè)置字體段落樣式
//把字體樣式添加到可變字符串中
     [self.attributedText addAttribute:NSParagraphStyleAttributeName value:_desParagraphStyle range:NSMakeRange(0, [self.attributedText length])];

NSMutableParagraphStyle 字體段落樣式

  • 設(shè)置字體行間距
///設(shè)置字體行間距
-(void)setLineSpacing:(CGFloat)lineSpacing
{
    self.desParagraphStyle.lineSpacing = lineSpacing;
}
  • 設(shè)置換行方式
///設(shè)置換行方式
-(void)setLineBreakMode:(NSLineBreakMode)lineBreakMode
{
    self.desParagraphStyle.lineBreakMode = lineBreakMode;
}
  • 設(shè)置首行縮進(jìn)
///設(shè)置首行縮進(jìn)
-(void)setFirstLineHeadIndent:(CGFloat)firstLineHeadIndent
{
    self.desParagraphStyle.firstLineHeadIndent = firstLineHeadIndent;
}
  • 設(shè)置文本對齊方式
//文本對齊方式
-(void)setNSTextAlignment:(NSTextAlignment)alignment
{
    self.desParagraphStyle.alignment = alignment;
}
  • 設(shè)置段落間距
//段與段之間的間距
-(void)setParagraphSpacing:(CGFloat)paragraphSpacing
{
    self.desParagraphStyle.paragraphSpacing = paragraphSpacing;
}

高度的計算

///獲取最終大小
-(CGSize)getSizeWithMaxWidth:(CGFloat)maxWidth
{
    
    if (self.maxWidth == maxWidth) {
        return self.stringSize;
    }
    self.maxWidth = maxWidth;
    
    CGRect rect = [self.attributedText boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
    //誤差值
    rect.size.height += 0.5;
    self.stringSize = rect.size;
    return self.stringSize;
}

以上方法設(shè)置了常用的屬性,下面要設(shè)置點擊事件的屬性。因為NSMutableAttributedString并不包含點擊事件的屬性,所以我們需要自定義一個Key,設(shè)置我們的value。

  • 添加自定義屬性(為點擊事件服務(wù))
///添加自定義屬性,為自定義label(ZHHitLabel)提供服務(wù)
- (void)addRichHelpWithType:(ZHRichHelpType)type range:(NSRange)range color:(UIColor *)textColor
{
    if (range.length > self.attributedText.length) {
        return;
    }
    if (textColor) {
        [self addColor:textColor range:range];
    }
    
    ZHRichHelpModel * model = [[ZHRichHelpModel alloc] init];
    model.richHelpType = type;
    model.valueRange = range;
    model.valueStr = [self.attributedText.string substringWithRange:range];
    [self.attributedText addAttribute:RichKey value:model range:range];
}


///其中我們自定義了一個Model,枚舉了常用的事件,添加了一些后續(xù)可能用到的屬性。
typedef enum : NSUInteger {
    ZHRichHelpTypeNone  = 0,  //啥事不干
    ZHRichHelpTypeLink  = 1,  //鏈接
    ZHRichHelpTypePhone = 2,  //電話號碼
    ZHRichHelpTypeClick = 3,  //點擊事件
} ZHRichHelpType;

@interface ZHRichHelpModel : NSObject
///記錄目標(biāo)類型
@property (nonatomic, assign) ZHRichHelpType richHelpType;
///記錄目標(biāo)字符串
@property (nonatomic, strong) NSString * valueStr;
///記錄目標(biāo)范圍
@property (nonatomic, assign) NSRange valueRange;
@end


  • 自定義UILable

擁有了有自定義屬性和富文本格式的NSMutableAttributedString后,我們需要一個展示的控件,系統(tǒng)默認(rèn)可以設(shè)置NSAttributedString的控件都可以直接賦值,并且展示出富文本效果。如果需要點擊事件,就需要自定義label了

#import <UIKit/UIKit.h>
#import "ZHRichHelpModel.h"

typedef void(^HitLableTouchBlock)(ZHRichHelpModel * model);

@interface ZHHitLabel : UILabel
///點擊事件回調(diào)
@property (nonatomic, copy) HitLableTouchBlock clickBlock;

@end

在觸摸的時候,檢測觸摸的文字是否擁有點擊事件

#pragma mark - Touch
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    self.richModel = [self touchStrAtPoint:touchPoint];
    if (!self.richModel) {
        [super touchesBegan:touches withEvent:event];
    }
    else
    {
        [self drawBackgroundColorWithState:NO withRange:self.richModel.valueRange];
    }

}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.richModel) {
        UITouch * touch = [touches anyObject];
        CGPoint touchPoint = [touch locationInView:self];
        ZHRichHelpModel * moveRichModel = [self touchStrAtPoint:touchPoint];
        if (self.richModel != moveRichModel) {
            [self drawBackgroundColorWithState:YES withRange:self.richModel.valueRange];
            self.richModel = nil;
        }
    }
    else
    {
        [super touchesMoved:touches withEvent:event];
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.richModel) {
        if (self.clickBlock) {
            self.clickBlock(self.richModel);
        }
        [self drawBackgroundColorWithState:YES withRange:self.richModel.valueRange];
    }
    else
    {
        [super touchesEnded:touches withEvent:event];
    }
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.richModel) {
        [self drawBackgroundColorWithState:YES withRange:self.richModel.valueRange];
        self.richModel = nil;
    } else {
        [super touchesCancelled:touches withEvent:event];
    }
}

#pragma mark - CGSize CGRect CGPoint
- (ZHRichHelpModel *)touchStrAtPoint:(CGPoint)location
{
    
    CGPoint textOffset;
    //在執(zhí)行usedRectForTextContainer之前最好還是執(zhí)行下glyphRangeForTextContainer relayout
    [self.layoutManager glyphRangeForTextContainer:self.textContainer];
    textOffset = [self textOffsetWithTextSize:[self.layoutManager usedRectForTextContainer:self.textContainer].size];
    
    //location轉(zhuǎn)換成在textContainer的繪制區(qū)域的坐標(biāo)
    location.x -= textOffset.x;
    location.y -= textOffset.y;
    
    
    //返回觸摸區(qū)域的字形  如果location的區(qū)域沒字形,可能返回的是最近的字形index,所以需要再找到這個字形所處于的rect來確認(rèn)
    NSUInteger glyphIndex = [self.layoutManager glyphIndexForPoint:location inTextContainer:self.textContainer];
    CGRect glyphRect = [self.layoutManager boundingRectForGlyphRange:NSMakeRange(glyphIndex, 1) inTextContainer:self.textContainer];
    if (!CGRectContainsPoint(glyphRect, location)) {
        return nil;
    }
    
    for (ZHRichHelpModel * model in self.helpValueArray) {
        if (NSLocationInRange(glyphIndex, model.valueRange)) {
            return model;
        }
    }
    
    return nil;
}

//這個計算出來的是繪制起點
- (CGPoint)textOffsetWithTextSize:(CGSize)textSize
{
    CGPoint textOffset = CGPointZero;
    //根據(jù)insets和默認(rèn)垂直居中來計算出偏移
    textOffset.x = 0;
    CGFloat paddingHeight = (_textContainer.size.height - textSize.height) / 2.0f;
    textOffset.y = paddingHeight+ 0;
    
    return textOffset;
}

///繪制背景顏色 根據(jù)觸摸的狀態(tài) 以及范圍
- (void)drawBackgroundColorWithState:(BOOL)isEnd withRange:(NSRange)range
{
    NSMutableAttributedString * mutableStr = [self.lastAttributedString mutableCopy];
    if (!isEnd) {
        [mutableStr addAttribute:NSBackgroundColorAttributeName value:[UIColor colorWithRed:239/255.0 green:253/255.0 blue:1 alpha:1] range:range];
    }
    else
    {
        [mutableStr removeAttribute:NSBackgroundColorAttributeName range:range];
    }
    
    self.attributedText = mutableStr;
    
}

源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容