NSMutableAttributedString的使用

1.设置字符串中数字字符串的颜色:

// 设置字符串中数字的颜色
- (void)setTextColor:(UILabel *)label FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];
    
    NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    int remainSecond =[[label.text stringByTrimmingCharactersInSet:nonDigits] intValue];
    NSLog(@" num %d ",remainSecond);
    
    NSString *labelText = label.text;
    
    for (int i = 0; i < labelText.length; i ++) {
        //这里的小技巧,每次只截取一个字符的范围
        NSString *a = [labelText substringWithRange:NSMakeRange(i, 1)];
        //判断装有0-9的字符串的数字数组是否包含截取字符串出来的单个字符,从而筛选出符合要求的数字字符的范围NSMakeRange
        NSArray *number = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
        if ([number containsObject:a]) {
            [str setAttributes:@{NSForegroundColorAttributeName:SELECT_PERSON_BUTTON_COLOR,NSFontAttributeName:FONT_13} range:NSMakeRange(i, 1)];
        }
    }
    label.attributedText = str;
}

2.截取某个字符串段,设置字体颜色:

- (void)setBlueColorStringWithText:(NSMutableString *)text {

    NSRange startRange = [text rangeOfString:@"("];
    NSRange endRange = [text rangeOfString:@")"];
    NSRange range = NSMakeRange(startRange.location + startRange.length -1, endRange.location - startRange.location - startRange.length + 2);
    NSDictionary *attribs = @{NSForegroundColorAttributeName: SELECT_PERSON_BUTTON_COLOR,
                              NSFontAttributeName:FONT_13
                              };
    NSMutableAttributedString *textStr = [[NSMutableAttributedString alloc] initWithString:text];
   [textStr setAttributes:attribs range:range];
    self.deadlineLabel.attributedText = textStr;
}

  

转载于:https://www.cnblogs.com/pengsi/p/6229973.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值