Using attributedText to Create a Single UILabel with Multiple Styles

Sometimes, a design requires a label to have multiple separate styles, while the code would be easier with one label or string. In this case, it’s useful to know about attributedText on UILabels. This approach lets you style strings without changing the style on the label directly. Below is a step-by-step guide for how to simply add a single UILabel with multiple styles throughout.

1. Create a Dictionary of Base Attributes

To start, you can create a dictionary of base attributes for the label. This will be the label’s style if you don’t set other attributes for parts of the string.

NSDictionary *baseAttributes = @{
     NSForegroundColorAttributeName:[UIColor blackColor],
     NSFontAttributeName:[UIFont systemFontOfSize:15.0f]

2. Initialize an Attributed String Using Those Attributes

Using the dictionary of attributes you just created along with the string you wish to style, initialize a new NSMutableAttributedString.

NSString *helloWorldString = @"Hello World!";
NSMutableAttributedString *attributedString = 
     [[NSMutableAttributedString alloc] 

3. Create Dictionaries for as Many Styles as You Desire

Just as you created a dictionary of base attributes, you’ll want to create dictionaries for the different styles within the string. In this example, there is only one, but you could have as many attributes applied to the string and label as you want.

NSDictionary *attributes0 = @{
     NSForegroundColorAttributeName:[UIColor whiteColor],
     NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f],
     NSBackgroundColorAttributeName:[UIColor blackColor]

4. Using Ranges, Set the Attributes for Each String within the Attributed String

Now you will need to decide which substrings you want to style. You can do this by giving each substring ranges with different attributes from the base style of the string.

NSRange range0 = [helloWorldString rangeOfString:@"Hello"];
[attributedString setAttributes:attributes0 range:range0];

5. Set the attributedText on the UILabel to Be the Newly Styled String

Finally, you can use the newly created and styled attributed string to set the text of your UILabel.

UILabel *label = [[UILabel alloc] init];
label.attributedText = attributedString;

As a result, you should end up with a multi-styled UILabel.