UILabel添加點(diǎn)擊事件、刪除線、下劃線、特殊字符串改變顏色

1、創(chuàng)建空白項(xiàng)目,在屏幕中間添加一個(gè)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 = @"按到了卡時(shí)間段昆侖決拉屎肯德基";
    lTips.center = self.view.center;
    lTips.textColor = [UIColor redColor];
    [self.view addSubview:lTips];
    
}

@end

2、command + N打開文件選擇頁面,選擇Object-C File,然后大力的按一下肥車(回車),F(xiàn)ile Type選Category,Class選UILabel,F(xiàn)ile文件名自己隨便寫,再大力的按一下肥車

源碼:

  • .h文件

NS_ASSUME_NONNULL_BEGIN

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

//帶點(diǎn)擊事件的字符串
@property(nonatomic, copy)NSString *string;
//帶點(diǎn)擊事件字符串的range
@property(nonatomic, assign)NSRange range;

@end

/*
 *
 */
@interface UILabel (LYTouchAction)

//點(diǎn)擊效果,默認(rèn)是打開
@property(nonatomic)BOOL enabledTapEffect;

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

//特殊字符串下劃線
@property(nonatomic)BOOL underLine;

//特殊字符串刪除線
@property(nonatomic)BOOL throughLine;

/**
 *  給文本添加點(diǎn)擊事件Block回調(diào)
 *
 *  @param strings  需要添加的字符串?dāng)?shù)組
 *  @param tapClick 點(diǎn)擊事件回調(diào)
 */
-(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);
}

//點(diǎn)擊手勢(shì)
-(BOOL)isTapAction{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

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

//回調(diào)
-(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);
}

//點(diǎn)擊效果
-(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 - 設(shè)置特殊字符串并獲取回調(diào)結(jié)果
-(void)addAttributeTapActionWithStrings:(NSArray <NSString *> *)strings tapClicked:(void (^) (NSString *string , NSRange range , NSInteger index))tapClick{
    
    //獲取特殊字符串的Range
    [self getRangesWithArrayStrings:strings];
    
    //設(shè)置block回調(diào)
    if (self.tapBlock != tapClick) {
        self.tapBlock = tapClick;
    }
    
}

#pragma mark - 為Label添加點(diǎn)擊手勢(shì)
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    //如果沒有設(shè)置關(guān)鍵,則直接跳出,不添加手勢(shì)
    if (!self.isTapAction) {
        return;
    }
    
    //獲取點(diǎn)擊效果是否開啟
    if (objc_getAssociatedObject(self, @selector(enabledTapEffect))) {
        self.isTapEffect = self.enabledTapEffect;
    }
    
    //獲取手勢(shì)
    UITouch *touch = [touches anyObject];
    //在當(dāng)前View獲取點(diǎn)擊位置
    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]);
        
        //點(diǎn)擊效果的背景顏色
        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{
    
    //容錯(cuò)處理
    if (self.attributedText == nil) {
        self.isTapAction = NO;
        return;
    }
    
    //添加手勢(shì)
    self.isTapAction = YES;
    
    //添加點(diǎn)擊效果
    self.isTapEffect = YES;
    
    //設(shè)置弱引用接收字符串
    __block NSString *totalStr = self.attributedText.string;
    
    //初始化可變數(shù)組存儲(chǔ)特殊字符串
    self.attributeStrings = [NSMutableArray array];
    
    __weak typeof(self) weakSelf = self;
    
    //開始遍歷整個(gè)字符串,獲取到對(duì)應(yīng)的特殊字符串和對(duì)應(yīng)的range,并存到self.attributeStrings可變數(shù)組中
    [arrayStrings enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //獲取到對(duì)應(yīng)特殊字符串的range
        NSRange range = [totalStr rangeOfString:obj];
        
        //特殊字符串存在,則繼續(xù)處理
        if (range.length != 0) {
            
            //特殊字符串用空格替換掉
            totalStr = [totalStr stringByReplacingCharactersInRange:range withString:[weakSelf getStringWithRange:range]];
            
            //獲取特殊字符串的位置和內(nèi)容,并存儲(chǔ)到可變數(shù)組中
            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”件添加如下代碼,然后自主注釋編譯運(yùn)行

UILabel *lTips = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 20)];
lTips.text = @"按到了卡時(shí)間段昆侖決拉屎肯德基";
lTips.center = self.view.center;
lTips.textColor = [UIColor redColor];
lTips.attributeColor = [UIColor blueColor];//特殊字符串字體顏色
lTips.underLine = YES;//特殊字符串是否添加下劃線
lTips.throughLine = YES;//特殊字符串是否添加刪除線
[self.view addSubview:lTips];
    
//給Label添加特殊字符串的點(diǎn)擊事件
[lTips addAttributeTapActionWithStrings:@[@"時(shí)間",@"肯德基"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
    NSLog(@"str = %@ index = %ld",string,index);
}];
    
//    //特殊字符串被點(diǎn)擊是否顯示效果,默認(rèn)為YES
//    lTips.enabledTapEffect = NO;

說明:本類源碼是同事找到的,原地址我是真的不知道,這個(gè)類是我后期整理項(xiàng)目的時(shí)候看到的,覺得不錯(cuò),所以在原基礎(chǔ)上添加了一些功能,看起來稍微有點(diǎn)容易讓自己接受,簡(jiǎn)單封裝,叩首敬上,如有得罪,不關(guān)我事啊!別找我別找我……欠身了!

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

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

  • 對(duì)于城市里面的人來說,公共廁所是極普通的建筑,話雖如此,假如城市中沒有公共廁所,城市就會(huì)亂套了。公共廁所對(duì)城市來說...
    煤場(chǎng)封閉閱讀 376評(píng)論 0 0
  • 我們談一談,要怎么樣才可以越活越年輕? 我自己是覺得越活越年輕,那不同的人,可能還有不同的看人方式和標(biāo)準(zhǔn),呃!前兩...
    陳嘉玲閱讀 341評(píng)論 0 3
  • 蘇子出生于1992年的蘇村。這個(gè)村子的重男輕女思想從古延續(xù)至今。蘇叔叔在1989年南下云南一個(gè)貧窮落后的小村子花了...
    昔野酒肆閱讀 486評(píng)論 1 1

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