Search code examples
iosnsstringuilabelnsattributedstring

Displaying a string with multiple attributes in a label


I need to display a string which will change every second.

For example :

View will refresh in 10 sec
View will refresh in 09 sec
View will refresh in 08 sec
View will refresh in 07 sec
..
View will refresh in 0 sec

The above string needs to be displayed with multiple properties of text, like-

1) The color of text - 'View will refresh in _ sec' will be White
2) The color of number - '10' , '09' ... will be Yellow.

As displayed in reference below :

enter image description here

How can I achieve this using only one label?

Many thanks in advance.


Solution

  • NSMutableAttributedString *str = [[NSMutableAttributedString alloc] init];
    [str appendAttributedString:[[NSAttributedString alloc] initWithString:@"Will change in " attributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:17], NSForegroundColorAttributeName : [UIColor whiteColor] }]];
    [str appendAttributedString:[[NSAttributedString alloc] initWithString:@"10 sec" attributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:19], NSForegroundColorAttributeName : [UIColor yellowColor] }]];
    myLabel.attributedText = str;