1

I have a string like this

NSString * string = [[NSString alloc]initwithformat: @"The current balance left is %@ out of %@",leftAmount,totalAmount];                 

How can i change the colour of string recieved as %@ without knowing the range of the recieved string.

Bellerofont
  • 1,081
  • 18
  • 17
  • 16

2 Answers2

3

Do something like this,

    NSString *leftAmount = @"1000";
    NSString *totalAmount = @"2000";
    UIColor *color = [UIColor redColor];
    NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:leftAmount attributes:attrs];
    NSAttributedString *attrStr1 = [[NSAttributedString alloc] initWithString:totalAmount attributes:attrs];

    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"The current balance left is "];
    [string appendAttributedString:attrStr];

    NSMutableAttributedString * string1 = [[NSMutableAttributedString alloc] initWithString:@" out of "];
    [string1 appendAttributedString:attrStr1];
    [string appendAttributedString:string1];

    NSLog(@"Your Full String - %@", string);

Hope this will help you.

KAR
  • 3,303
  • 3
  • 27
  • 50
1

do something like this,

NSString *leftAmount,*totalAmount;
            leftAmount = @"1000";
            totalAmount = @"2000";

            NSString * string = [NSString stringWithFormat:@"The current balance left is %@ out of %@",leftAmount,totalAmount];

            NSDictionary *attribs = @{
                                      NSForegroundColorAttributeName: [UIColor blueColor],
                                      NSFontAttributeName: [UIFont systemFontOfSize:12]
                                      };
            NSMutableAttributedString *attributedText =
            [[NSMutableAttributedString alloc] initWithString:string
                                                   attributes:attribs];
            UIColor *grayColor = [UIColor colorWithRed:186.0f/255.0f green:186.0f/255.0f blue:186.0f/255.0f alpha:1];

            NSRange leftAmountTextRange = [string rangeOfString:leftAmount];

            [attributedText setAttributes:@{NSForegroundColorAttributeName:grayColor}
                                    range:leftAmountTextRange];

It'll also calculate the dynamic data value range.

I hope it will helps you,

Thanks.

Samkit Shah
  • 721
  • 1
  • 7
  • 18