iOS 轻量级富文本方案

2016-09-01  本文已影响0人  zhangbo1992

项目中多多少少会遇到一些需求,需要给部分文案添加点击事件。例如:"我已阅读《xxx协议》",这个时候最简单的实现方案是:添加一个button覆盖上去。但如果有多处文案需要添加点击事件,就会比较懵逼。下面我说下我的实现方案。

最初的时候我打算使用CoreText实现,查询了相关资料后发现自己不能很快的造出轮子,虽然网上有很多现成的轮子可以用,但是我并不想只纯粹的搬运代码。需要直接拿轮子的可以点击这里。于是我把目光转移到TextKit上面,发现相关代码要比CoreText易读易懂很多,于是就有了下面的事情。

言归正传,给Label的文字添加点击事件,首先需要让文字有不同的颜色,不同的字号,这个时候就需要用到 NSMutableAttributedString,下面是一些常规的处理。

NSMutableAttributedString

///根据range设置颜色
-(void)addColor:(UIColor *)color range:(NSRange)range
{
    if (range.length > self.attributedText.length) {
        return;
    }
    [self.attributedText addAttribute:NSForegroundColorAttributeName value:color range:range];
}
///根据range设置字体大小
-(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];
}
///设置字间距
-(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];
    }
}
///设置基线偏移值
-(void)addBaselineOffset:(CGFloat)offset range:(NSRange)range
{
    [self.attributedText addAttribute:NSBaselineOffsetAttributeName value:[NSNumber numberWithFloat:offset] range:range];
}
///设置凸版印刷体效果
-(void)addEffectLetterpressWithRange:(NSRange)range
{
    [self.attributedText addAttribute:NSTextEffectAttributeName value:NSTextEffectLetterpressStyle range:range];
}
///在某个位置插入图片 不要在结尾处插入图片,在iOS8的某个小版本会出现bug
-(void)addAttachmentWithImageName:(NSString *)imageName index:(NSInteger)index size:(CGSize)size
{
    UIImage * image = [UIImage imageNamed:imageName];
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //设置默认大小
    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];
}
//把字体样式添加到可变字符串中
     [self.attributedText addAttribute:NSParagraphStyleAttributeName value:_desParagraphStyle range:NSMakeRange(0, [self.attributedText length])];

NSMutableParagraphStyle 字体段落样式

///设置字体行间距
-(void)setLineSpacing:(CGFloat)lineSpacing
{
    self.desParagraphStyle.lineSpacing = lineSpacing;
}
///设置换行方式
-(void)setLineBreakMode:(NSLineBreakMode)lineBreakMode
{
    self.desParagraphStyle.lineBreakMode = lineBreakMode;
}
///设置首行缩进
-(void)setFirstLineHeadIndent:(CGFloat)firstLineHeadIndent
{
    self.desParagraphStyle.firstLineHeadIndent = firstLineHeadIndent;
}
//文本对齐方式
-(void)setNSTextAlignment:(NSTextAlignment)alignment
{
    self.desParagraphStyle.alignment = alignment;
}
//段与段之间的间距
-(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;
}

以上方法设置了常用的属性,下面要设置点击事件的属性。因为NSMutableAttributedString并不包含点击事件的属性,所以我们需要自定义一个Key,设置我们的value。

///添加自定义属性,为自定义label(ZHHitLabel)提供服务
- (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,枚举了常用的事件,添加了一些后续可能用到的属性。
typedef enum : NSUInteger {
    ZHRichHelpTypeNone  = 0,  //啥事不干
    ZHRichHelpTypeLink  = 1,  //链接
    ZHRichHelpTypePhone = 2,  //电话号码
    ZHRichHelpTypeClick = 3,  //点击事件
} ZHRichHelpType;

@interface ZHRichHelpModel : NSObject
///记录目标类型
@property (nonatomic, assign) ZHRichHelpType richHelpType;
///记录目标字符串
@property (nonatomic, strong) NSString * valueStr;
///记录目标范围
@property (nonatomic, assign) NSRange valueRange;
@end


拥有了有自定义属性和富文本格式的NSMutableAttributedString后,我们需要一个展示的控件,系统默认可以设置NSAttributedString的控件都可以直接赋值,并且展示出富文本效果。如果需要点击事件,就需要自定义label了

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

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

@interface ZHHitLabel : UILabel
///点击事件回调
@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;
    //在执行usedRectForTextContainer之前最好还是执行下glyphRangeForTextContainer relayout
    [self.layoutManager glyphRangeForTextContainer:self.textContainer];
    textOffset = [self textOffsetWithTextSize:[self.layoutManager usedRectForTextContainer:self.textContainer].size];
    
    //location转换成在textContainer的绘制区域的坐标
    location.x -= textOffset.x;
    location.y -= textOffset.y;
    
    
    //返回触摸区域的字形  如果location的区域没字形,可能返回的是最近的字形index,所以需要再找到这个字形所处于的rect来确认
    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;
    //根据insets和默认垂直居中来计算出偏移
    textOffset.x = 0;
    CGFloat paddingHeight = (_textContainer.size.height - textSize.height) / 2.0f;
    textOffset.y = paddingHeight+ 0;
    
    return textOffset;
}

///绘制背景颜色 根据触摸的状态 以及范围
- (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;
    
}

源码

上一篇下一篇

猜你喜欢

热点阅读