将且仅将UILabel上的所有数字变色指定的字体颜色

来源:互联网 发布:淘宝优惠券领取faquan 编辑:程序博客网 时间:2024/06/07 01:45

先提出一个场景,一个UILabel上面有各种数字字符中文字符以及字母等,现在我们想将其中的数字找出来并且变为和其他字符不同的颜色。

这里提出一个解决方法,通过for循环来截取一个一个字符,判断其是不是0-9的数字,如果是就设置他的字体属性,我们使用了 NSMutableAttributedString实现富文本(带属性的字符串)。



NSAttributedString的使用方法,跟NSMutableString,NSString类似

1.使用方法:

为某一范围内文字设置多个属性

- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

为某一范围内文字添加某个属性

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

为某一范围内文字添加多个属性

- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;

移除某范围内的某个属性

- (void)removeAttribute:(NSString *)name range:(NSRange)range;

2.     常见的属性及说明

NSFontAttributeName 字体

NSParagraphStyleAttributeName 段落格式 

NSForegroundColorAttributeName 字体颜色

NSBackgroundColorAttributeName  背景颜色

NSStrikethroughStyleAttributeName删除线格式

NSUnderlineStyleAttributeName     下划线格式

NSStrokeColorAttributeName       删除线颜色

NSStrokeWidthAttributeName删除线宽度

NSShadowAttributeName 阴影

//PS:下划线属性的设置方法

 //[attributeString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(i, 1)];

  那么进入正题!,首先我们创建好UILabel,然后通过for循环来查找符合条件的数字

@property (nonatomic,strong)UILabel *myLabel;

    self.myLabel = [[UILabelalloc]initWithFrame:CGRectMake(0,0,375,100)];

    self.myLabel.backgroundColor = [UIColorcyanColor];//天蓝色背景

    self.myLabel.textAlignment =1;//居中

    [self.viewaddSubview:self.myLabel];

//这是我们的测试用的文本字符串数据

NSString *content =@"abc123a1b2c3你懂得888";

    NSArray *number =@[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];

    NSMutableAttributedString *attributeString  = [[NSMutableAttributedStringalloc]initWithString:content];

    for (int i =0; i < content.length; i ++) {

//这里的小技巧,每次只截取一个字符的范围

        NSString *a = [content substringWithRange:NSMakeRange(i, 1)];

//判断装有0-9的字符串的数字数组是否包含截取字符串出来的单个字符,从而筛选出符合要求的数字字符的范围NSMakeRange

        if ([number containsObject:a]) {

            [attributeString setAttributes:@{NSForegroundColorAttributeName:[UIColorblueColor],NSFontAttributeName:[UIFontsystemFontOfSize:25],NSUnderlineStyleAttributeName:[NSNumbernumberWithInteger:NSUnderlineStyleSingle]}range:NSMakeRange(i,1)];      

        }

        

    }

    //完成查找数字,最后将带有字体下划线的字符串显示在UILabel上

    self.myLabel.attributedText = attributeString;



 




5 0