UILabel添加点击事件、删除线、下划线、特殊字符串改变颜色

1、创建空白项目,在屏幕中间添加一个UILabel

#import "LabelTapController.h"

@interface LabelTapController ()

@end

@implementation LabelTapController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lTips = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 20)];
    lTips.text = @"按到了卡时间段昆仑决拉屎肯德基";
    lTips.center = self.view.center;
    lTips.textColor = [UIColor redColor];
    [self.view addSubview:lTips];
    
}

@end

2、command + N打开文件选择页面,选择Object-C File,然后大力的按一下肥车(回车),File Type选Category,Class选UILabel,File文件名自己随便写,再大力的按一下肥车

源码:

  • .h文件

NS_ASSUME_NONNULL_BEGIN

/*
 特殊字符串model
 */
@interface LYAttributeModel : NSObject

//带点击事件的字符串
@property(nonatomic, copy)NSString *string;
//带点击事件字符串的range
@property(nonatomic, assign)NSRange range;

@end

/*
 *
 */
@interface UILabel (LYTouchAction)

//点击效果,默认是打开
@property(nonatomic)BOOL enabledTapEffect;

//特殊字符串字体颜色
@property(nonatomic, strong)UIColor *attributeColor;

//特殊字符串下划线
@property(nonatomic)BOOL underLine;

//特殊字符串删除线
@property(nonatomic)BOOL throughLine;

/**
 *  给文本添加点击事件Block回调
 *
 *  @param strings  需要添加的字符串数组
 *  @param tapClick 点击事件回调
 */
-(void)addAttributeTapActionWithStrings:(NSArray <NSString *> *)strings
                             tapClicked:(void (^) (NSString *string , NSRange range , NSInteger index))tapClick;

@end

NS_ASSUME_NONNULL_END
  • .m文件
#import "UILabel+LYTouchAction.h"
#import <objc/runtime.h>
#import <CoreText/CoreText.h>
#import <Foundation/Foundation.h>

/*
 特殊字符串model
 */
@implementation LYAttributeModel
@end

/*
 *
 */
@implementation UILabel (LYTouchAction)

#pragma mark - AssociatedObjects ** <
-(NSMutableArray *)attributeStrings{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setAttributeStrings:(NSMutableArray *)attributeStrings{
    objc_setAssociatedObject(self, @selector(attributeStrings), attributeStrings, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSMutableDictionary *)effectDic{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setEffectDic:(NSMutableDictionary *)effectDic{
    objc_setAssociatedObject(self, @selector(effectDic), effectDic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

//点击手势
-(BOOL)isTapAction{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

-(void)setIsTapAction:(BOOL)isTapAction{
    objc_setAssociatedObject(self, @selector(isTapAction), @(isTapAction), OBJC_ASSOCIATION_ASSIGN);
}

//回调
-(void (^)(NSString *, NSRange, NSInteger))tapBlock{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setTapBlock:(void (^)(NSString *, NSRange, NSInteger))tapBlock{
    objc_setAssociatedObject(self, @selector(tapBlock), tapBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

//点击效果
-(BOOL)enabledTapEffect{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

-(void)setEnabledTapEffect:(BOOL)enabledTapEffect{
    objc_setAssociatedObject(self, @selector(enabledTapEffect), @(enabledTapEffect), OBJC_ASSOCIATION_ASSIGN);
    self.isTapEffect = enabledTapEffect;
}

-(BOOL)isTapEffect{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

-(void)setIsTapEffect:(BOOL)isTapEffect{
    objc_setAssociatedObject(self, @selector(isTapEffect), @(isTapEffect), OBJC_ASSOCIATION_ASSIGN);
}

//特殊字符串字体颜色
-(UIColor *)attributeColor{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setAttributeColor:(UIColor *)attributeColor{
    objc_setAssociatedObject(self, @selector(attributeColor), attributeColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

//下划线
-(BOOL)underLine{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

-(void)setUnderLine:(BOOL)underLine{
    objc_setAssociatedObject(self, @selector(underLine), @(underLine), OBJC_ASSOCIATION_ASSIGN);
}

//删除线
-(BOOL)throughLine{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

-(void)setThroughLine:(BOOL)throughLine{
    objc_setAssociatedObject(self, @selector(throughLine), @(throughLine), OBJC_ASSOCIATION_ASSIGN);
}
#pragma mark - AssociatedObjects ** >



#pragma mark - 设置特殊字符串并获取回调结果
-(void)addAttributeTapActionWithStrings:(NSArray <NSString *> *)strings tapClicked:(void (^) (NSString *string , NSRange range , NSInteger index))tapClick{
    
    //获取特殊字符串的Range
    [self getRangesWithArrayStrings:strings];
    
    //设置block回调
    if (self.tapBlock != tapClick) {
        self.tapBlock = tapClick;
    }
    
}

#pragma mark - 为Label添加点击手势
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    //如果没有设置关键,则直接跳出,不添加手势
    if (!self.isTapAction) {
        return;
    }
    
    //获取点击效果是否开启
    if (objc_getAssociatedObject(self, @selector(enabledTapEffect))) {
        self.isTapEffect = self.enabledTapEffect;
    }
    
    //获取手势
    UITouch *touch = [touches anyObject];
    //在当前View获取点击位置
    CGPoint point = [touch locationInView:self];
    
    __weak typeof(self) weakSelf = self;
    
    //
    [self getTapFrameWithTouchPoint:point result:^(NSString *string, NSRange range, NSInteger index) {
        
        if (weakSelf.tapBlock) {
            weakSelf.tapBlock (string , range , index);
        }
        
        if (self.isTapEffect) {
            [self saveEffectDicWithRange:range];
            [self tapEffectWithStatus:YES];
        }
        
    }];
    
}

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    
    if (self.isTapAction) {
        if ([self getTapFrameWithTouchPoint:point result:nil]) {
            return self;
        }
    }
    return [super hitTest:point withEvent:event];
    
}

#pragma mark - getTapFrame
-(BOOL)getTapFrameWithTouchPoint:(CGPoint)point result:(void (^) (NSString *string , NSRange range , NSInteger index))resultBlock{
    
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)self.attributedText);
    CGMutablePathRef Path = CGPathCreateMutable();
    CGPathAddRect(Path, NULL, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height));
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL);
    CFRange range = CTFrameGetVisibleStringRange(frame);
    
    if (self.attributedText.length > range.length) {
        
        UIFont *font;
        //获取字体大小
        if ([self.attributedText attribute:NSFontAttributeName atIndex:0 effectiveRange:nil]) {
            font = [self.attributedText attribute:NSFontAttributeName atIndex:0 effectiveRange:nil];
        }else if (self.font){
            font = self.font;
        }else {
            font = [UIFont systemFontOfSize:17];
        }
        
        CGPathRelease(Path);
        Path = CGPathCreateMutable();
        CGPathAddRect(Path, NULL, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height + font.lineHeight));
        frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL);
        
    }
    
    CFArrayRef lines = CTFrameGetLines(frame);
    
    if (!lines) {
        CFRelease(frame);
        CFRelease(framesetter);
        CGPathRelease(Path);
        return NO;
    }
    
    CFIndex count = CFArrayGetCount(lines);
    CGPoint origins[count];
    CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins);
    CGAffineTransform transform = [self transformForCoreText];
    CGFloat verticalOffset = 0;
    
    for (CFIndex i = 0; i < count; i++) {
        
        CGPoint linePoint = origins[i];
        CTLineRef line = CFArrayGetValueAtIndex(lines, i);
        CGRect flippedRect = [self getLineBounds:line point:linePoint];
        CGRect rect = CGRectApplyAffineTransform(flippedRect, transform);
        rect = CGRectInset(rect, 0, 0);
        rect = CGRectOffset(rect, 0, verticalOffset);
        NSParagraphStyle *style = [self.attributedText attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:nil];
        CGFloat lineSpace;
        
        if (style) {
            lineSpace = style.lineSpacing;
        }else {
            lineSpace = 0;
        }
        
        CGFloat lineOutSpace = (self.bounds.size.height - lineSpace * (count - 1) -rect.size.height * count) / 2;
        rect.origin.y = lineOutSpace + rect.size.height * i + lineSpace * i;
        
        if (CGRectContainsPoint(rect, point)) {
            
            CGPoint relativePoint = CGPointMake(point.x - CGRectGetMinX(rect), point.y - CGRectGetMinY(rect));
            CFIndex index = CTLineGetStringIndexForPosition(line, relativePoint);
            CGFloat offset;
            CTLineGetOffsetForStringIndex(line, index, &offset);
            
            if (offset > relativePoint.x) {
                index = index - 1;
            }
            
            NSInteger link_count = self.attributeStrings.count;
            
            for (int j = 0; j < link_count; j++) {
                
                LYAttributeModel *model = self.attributeStrings[j];
                
                NSRange link_range = model.range;
                
                if (NSLocationInRange(index, link_range)) {
                    if (resultBlock) {
                        resultBlock (model.string , model.range , (NSInteger)j);
                    }
                    CFRelease(frame);
                    CFRelease(framesetter);
                    CGPathRelease(Path);
                    return YES;
                }
                
            }
            
        }
        
    }
    CFRelease(frame);
    CFRelease(framesetter);
    CGPathRelease(Path);
    return NO;
    
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (self.isTapEffect) {
        [self performSelectorOnMainThread:@selector(tapEffectWithStatus:) withObject:nil waitUntilDone:NO];
    }
}

-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (self.isTapEffect) {
        [self performSelectorOnMainThread:@selector(tapEffectWithStatus:) withObject:nil waitUntilDone:NO];
    }
}

-(CGAffineTransform)transformForCoreText{
    return CGAffineTransformScale(CGAffineTransformMakeTranslation(0, self.bounds.size.height), 1.f, -1.f);
}

-(CGRect)getLineBounds:(CTLineRef)line point:(CGPoint)point{
    
    CGFloat ascent = 0.0f;
    CGFloat descent = 0.0f;
    CGFloat leading = 0.0f;
    CGFloat width = (CGFloat)CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
    CGFloat height = ascent + fabs(descent) + leading;
    
    return CGRectMake(point.x, point.y , width, height);
    
}

#pragma mark - tapEffect
-(void)tapEffectWithStatus:(BOOL)status{
    
    if (self.isTapEffect) {
        
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
        NSMutableAttributedString *subAtt = [[NSMutableAttributedString alloc] initWithAttributedString:[[self.effectDic allValues] firstObject]];
        
        NSRange range = NSRangeFromString([[self.effectDic allKeys] firstObject]);
        
        //点击效果的背景颜色
        if (status) {
            [subAtt addAttribute:NSBackgroundColorAttributeName value:[UIColor groupTableViewBackgroundColor] range:NSMakeRange(0, subAtt.string.length)];
            [attStr replaceCharactersInRange:range withAttributedString:subAtt];
        }else {
            [attStr replaceCharactersInRange:range withAttributedString:subAtt];
        }
        self.attributedText = attStr;
        
    }
    
}

-(void)saveEffectDicWithRange:(NSRange)range{
    
    self.effectDic = [NSMutableDictionary dictionary];
    NSAttributedString *subAttribute = [self.attributedText attributedSubstringFromRange:range];
    [self.effectDic setObject:subAttribute forKey:NSStringFromRange(range)];
    
}

#pragma mark - 获取特殊字符串的Range
-(void)getRangesWithArrayStrings:(NSArray <NSString *>  *)arrayStrings{
    
    //容错处理
    if (self.attributedText == nil) {
        self.isTapAction = NO;
        return;
    }
    
    //添加手势
    self.isTapAction = YES;
    
    //添加点击效果
    self.isTapEffect = YES;
    
    //设置弱引用接收字符串
    __block NSString *totalStr = self.attributedText.string;
    
    //初始化可变数组存储特殊字符串
    self.attributeStrings = [NSMutableArray array];
    
    __weak typeof(self) weakSelf = self;
    
    //开始遍历整个字符串,获取到对应的特殊字符串和对应的range,并存到self.attributeStrings可变数组中
    [arrayStrings enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //获取到对应特殊字符串的range
        NSRange range = [totalStr rangeOfString:obj];
        
        //特殊字符串存在,则继续处理
        if (range.length != 0) {
            
            //特殊字符串用空格替换掉
            totalStr = [totalStr stringByReplacingCharactersInRange:range withString:[weakSelf getStringWithRange:range]];
            
            //获取特殊字符串的位置和内容,并存储到可变数组中
            LYAttributeModel *model = [LYAttributeModel new];
            model.range = range;
            model.string = obj;
            [weakSelf.attributeStrings addObject:model];
            
        }
        
    }];
    
    NSLog(@"throughLine = %@",self.throughLine ? @"yes" : @"no");
    //修改特殊字符串字体颜色
    if (self.attributeColor) {
        
        for (int i = 0; i < self.attributeStrings.count; i ++) {
            
            LYAttributeModel *model = self.attributeStrings[i];
            NSMutableAttributedString *mutAttr = [[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText];
            [mutAttr addAttribute:NSForegroundColorAttributeName value:self.attributeColor range:model.range];
            
            //特殊字符串添加下划线
            if (self.underLine) {
                [mutAttr addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:model.range];
            }
            
            //特殊字符串添加删除线
            if (self.throughLine) {
                [mutAttr addAttributes:@{NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle),
                                         NSBaselineOffsetAttributeName:@(0)}
                                 range:model.range];
            }
            
            self.attributedText = mutAttr;
            
        }
        
    }
    
}

-(NSString *)getStringWithRange:(NSRange)range{
    
    NSMutableString *string = [NSMutableString string];
    for (int i = 0; i < range.length ; i++) {
        [string appendString:@" "];
    }
    return string;
    
}

@end

3、回头在#import “LabelTapController.m”件添加如下代码,然后自主注释编译运行

UILabel *lTips = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 20)];
lTips.text = @"按到了卡时间段昆仑决拉屎肯德基";
lTips.center = self.view.center;
lTips.textColor = [UIColor redColor];
lTips.attributeColor = [UIColor blueColor];//特殊字符串字体颜色
lTips.underLine = YES;//特殊字符串是否添加下划线
lTips.throughLine = YES;//特殊字符串是否添加删除线
[self.view addSubview:lTips];
    
//给Label添加特殊字符串的点击事件
[lTips addAttributeTapActionWithStrings:@[@"时间",@"肯德基"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
    NSLog(@"str = %@ index = %ld",string,index);
}];
    
//    //特殊字符串被点击是否显示效果,默认为YES
//    lTips.enabledTapEffect = NO;

说明:本类源码是同事找到的,原地址我是真的不知道,这个类是我后期整理项目的时候看到的,觉得不错,所以在原基础上添加了一些功能,看起来稍微有点容易让自己接受,简单封装,叩首敬上,如有得罪,不关我事啊!别找我别找我……欠身了!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容

  • 对于城市里面的人来说,公共厕所是极普通的建筑,话虽如此,假如城市中没有公共厕所,城市就会乱套了。公共厕所对城市来说...
    煤场封闭阅读 306评论 0 0
  • 我们谈一谈,要怎么样才可以越活越年轻? 我自己是觉得越活越年轻,那不同的人,可能还有不同的看人方式和标准,呃!前两...
    陈嘉玲阅读 294评论 0 3
  • 苏子出生于1992年的苏村。这个村子的重男轻女思想从古延续至今。苏叔叔在1989年南下云南一个贫穷落后的小村子花了...
    昔野酒肆阅读 423评论 1 1