iOS 字符串不同位置显示不同颜色

//"/人"置灰
    NSString *grayString = @"/人";
    NSString *string = [NSString stringWithFormat:@"¥%@/人", [FeeUtil priceStringWithPrice:self.insuranceModel.price]];
    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = [string rangeOfString:grayString];
    [aString addAttribute:NSForegroundColorAttributeName value:TNA_ONLINE_BOOK_COLOR_TEXT_DEEP_GRAY range:range];
    _priceLabel.attributedText = aString;

    self.priceLabel.attributedText = viewModel.price;
    NSString *string = self.priceLabel.text;
    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:string];
    NSString *subString = @"/";
    NSString *temp;
    //"/"后的单位置灰
    for (int i = 0; i < string.length; i++) {
        temp = [string substringWithRange:NSMakeRange(i, subString.length)];
        if ([temp isEqualToString:subString]) {
            NSRange range = {i, subString.length + 2};
            [aString addAttribute:NSForegroundColorAttributeName value:TNA_ONLINE_BOOK_COLOR_TEXT_DEEP_GRAY range:range];
        }
    }
    self.priceLabel.attributedText = aString;

PS:字符串的attributedText这个属性只要被赋值,那么该字符串的text就会自动有attributedText中的text属值了 不用再给字符串的text设置值

你可能感兴趣的:(iOS 字符串不同位置显示不同颜色)