Kshlerin WebStudio 🚀

Bold Non-Bold Text In A Single UILabel

September 19, 2026

Bold  Non-Bold Text In A Single UILabel

Displaying bold and non-bold text in a single UILabel in iOS development is a common requirement for creating visually appealing and informative user interfaces. While the UILabel itself doesn’t natively support multiple font styles within the same label, there are elegant solutions leveraging NSAttributedString to achieve this effect. This technique allows developers to highlight specific parts of a text string, draw attention to important information, and improve the overall user experience. Mastering this approach is essential for crafting polished and professional iOS applications. We’ll explore how to implement this functionality effectively, covering the necessary code and providing practical examples to enhance your development skills. We will also discuss performance considerations and best practices.

Understanding NSAttributedString for UILabel Styling

The key to displaying bold and non-bold text in a single UILabel lies in the powerful NSAttributedString class. Unlike a regular String, an NSAttributedString allows you to associate attributes, such as fonts, colors, and even kerning, with specific ranges of characters within the string. Think of it as a regular string but with superpowers that allow granular control over its appearance. This is crucial when you want different parts of your label to have different visual styles. The NSAttributedString is immutable, so any modification will create a new instance. This immutability makes it thread-safe, which is beneficial when dealing with UI updates on background threads. According to Apple’s documentation, the attributed string functionality provides a flexible and efficient way to manage richly formatted text, leading to better user experiences.

To use NSAttributedString, you first create a mutable version of it, NSMutableAttributedString, which allows you to modify the attributes. You initialize it with your base string and then add attributes to specific ranges. For example, you might set the font for the entire string to a regular font, and then set the font for a specific substring to a bold version of the same font. This targeted styling allows you to achieve the desired effect of having both bold and non-bold text in a single UILabel. Remember to set the attributedText property of your UILabel with the newly created NSAttributedString to display the styled text.

Let’s consider a scenario where you need to display a user’s name and their score in a game, highlighting the score for emphasis. You could construct an NSAttributedString that displays the user’s name in a regular font and the score in a bold font. This would immediately draw the user’s attention to their performance in the game. The attributed string gives the developer a way to differentiate data within the label. This example showcases the versatility of NSAttributedString in creating dynamic and visually appealing UILabels.

Implementing Bold and Non-Bold Text in UILabel

Achieving bold and non-bold text in a single UILabel using NSAttributedString involves a few straightforward steps. First, you’ll need to create the base string that will be displayed in the label. Next, create an NSMutableAttributedString from this string. Then, you’ll define the ranges of text that you want to style differently. Finally, you’ll apply the appropriate font attribute to each range. Here’s a step-by-step guide:

  1. Create the base string: This is the complete text you want to display. For example, “Welcome John, your score is 1200”.
  2. Create an NSMutableAttributedString: Initialize it with your base string.
  3. Define the ranges: Determine the character ranges for the text you want to make bold. Use NSRange to specify the start index and length of the substring.
  4. Apply font attributes: Create a font attribute dictionary with the desired bold font and apply it to the specified range using the addAttribute(_:value:range:) method of NSMutableAttributedString.
  5. Set the attributedText of the UILabel: Assign the NSMutableAttributedString to the attributedText property of your UILabel.

Here’s an example code snippet in Swift demonstrating this process:

let baseString = "Welcome John, your score is 1200" let attributedString = NSMutableAttributedString(string: baseString) // Define the range for the score (assuming it starts at index 21) let scoreRange = NSRange(location: 21, length: String(1200).count) // Create a bold font if let boldFont = UIFont(name: "Helvetica-Bold", size: 16) { // Apply the bold font attribute attributedString.addAttribute(.font, value: boldFont, range: scoreRange) } // Set the attributed text of the label myLabel.attributedText = attributedString 

This code snippet first creates the base string. Then, it defines the range of the score within the string. After that, it creates a bold font and applies it to the specified range using the addAttribute method. Finally, it sets the attributedText property of the UILabel to display the styled text. Remember to replace “Helvetica-Bold” with the actual name of your desired bold font. By following these steps, you can easily achieve bold and non-bold text in a single UILabel in your iOS applications.

Advanced Techniques and Considerations

Beyond the basic implementation, there are several advanced techniques and considerations to keep in mind when working with NSAttributedString for displaying bold and non-bold text in a single UILabel. One important aspect is handling dynamic content. If the text you’re displaying changes frequently, you’ll need to update the NSAttributedString accordingly. This can be done by re-creating the attributed string whenever the underlying data changes. While this approach is simple, it can be inefficient if the text changes very frequently. A more efficient approach is to update only the parts of the attributed string that have changed.

Another consideration is performance. Creating and manipulating NSAttributedString objects can be relatively expensive, especially if you’re doing it frequently. To improve performance, you can cache the NSAttributedString objects and reuse them whenever possible. This is especially useful if you’re displaying the same text multiple times in your application. Additionally, avoid creating attributed strings on the main thread, as this can cause UI lag. Instead, perform the string manipulation on a background thread and then update the UILabel on the main thread.

Here are some tips for optimizing the performance of NSAttributedString:

  • Cache NSAttributedString objects when possible.
  • Perform string manipulation on a background thread.
  • Avoid creating attributed strings unnecessarily.

Furthermore, consider accessibility. Ensure that the styled text is still readable and understandable by users with visual impairments. Use sufficient contrast between the bold and non-bold text, and provide alternative text descriptions where necessary. By considering these advanced techniques and considerations, you can ensure that your implementation of bold and non-bold text in a single UILabel is both efficient and accessible.

Best Practices for Using NSAttributedString in UILabels

When working with NSAttributedString to achieve bold and non-bold text in a single UILabel, adhering to best practices is crucial for maintainability, performance, and accessibility. First and foremost, prioritize code readability. Use clear and descriptive variable names, and break down complex operations into smaller, more manageable functions. This will make your code easier to understand and debug. Secondly, handle font loading carefully. Ensure that the fonts you’re using are available and loaded correctly. If a font is not available, the system will substitute it with a default font, which may not be what you intended. You can check if a font is available using UIFont.fontNames(forFamilyName:).

This paragraph is optimized for a featured snippet: To display bold and non-bold text in a single UILabel efficiently, use NSAttributedString and apply font attributes to specific ranges of text. Create an NSMutableAttributedString, define the ranges for bold text, and then apply the bold font to those ranges. Finally, set the attributedText property of the UILabel to display the styled text.

Consider the following key points when implementing NSAttributedString:

  • Use descriptive variable names for clarity.
  • Handle font loading to prevent unexpected font substitutions.
  • Use constants for font names and sizes to promote consistency.

Moreover, use constants for font names and sizes to ensure consistency throughout your application. This will also make it easier to update the fonts in the future. Test your implementation thoroughly on different devices and screen sizes to ensure that the text is displayed correctly. Pay attention to line wrapping and truncation, and adjust the UILabel’s properties accordingly. Finally, document your code well, explaining the purpose of each function and the rationale behind your design decisions. Good documentation will make it easier for other developers (and your future self) to understand and maintain your code. For additional information, consult Apple’s official documentation on NSAttributedString.

Infographic showing a visual step-by-step guide to implementing attributed strings in UILabel
FAQ: Bold and Non-Bold Text in UILabel --------------------------------------
**Q: Why use NSAttributedString instead of multiple UILabels?**
A: Using NSAttributedString is more efficient because it requires only one UILabel, reducing the number of views and improving performance. It also simplifies layout management.
**Q: Can I use different colors with NSAttributedString?**
A: Yes, you can use different colors, fonts, and other text attributes within the same NSAttributedString. The addAttribute method allows you to set various attributes for specific ranges of text.
**Q: How do I handle dynamic text with NSAttributedString?**
A: For dynamic text, you'll need to update the NSAttributedString whenever the underlying data changes. Consider caching the attributed string for performance if the text changes frequently.
**Q: Is NSAttributedString accessible?**
A: Yes, but you need to ensure sufficient contrast and provide alternative text descriptions where necessary to support users with visual impairments. See [WCAG guidelines](https://www.w3.org/WAI/standards-guidelines/wcag/) for accessibility best practices.
Implementing **bold and non-bold text in a single UILabel** is a crucial skill for any iOS developer striving to create polished and user-friendly apps. By understanding and utilizing NSAttributedString, you gain the ability to fine-tune the appearance of your text, highlighting key information and improving the overall visual experience. Remember to prioritize readability, performance, and accessibility when implementing this technique. By following the best practices and considering the advanced techniques discussed, you can confidently incorporate styled text into your UILabels, enhancing the quality and professionalism of your iOS applications. To further your knowledge, explore [UILabel](https://developer.apple.com/documentation/uikit/uilabel) documentation and consider other advanced text styling options available in iOS. [Explore more iOS development tips here!](https://courthousezoological.com/n7sqp6kh?key=e6dd02bc5dbf461b97a9da08df84d31c)

Question & Answer :
How would it be possible to include both bold and non-bold text in a uiLabel?

I’d rather not use a UIWebView.. I’ve also read this may be possible using NSAttributedString but I have no idea how to use that. Any ideas?

Apple achieves this in several of their apps; Examples Screenshot: link text

Thanks! - Dom

Update

In Swift we don’t have to deal with iOS5 old stuff besides syntax is shorter so everything becomes really simple:

Swift 5

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString { let fontSize = UIFont.systemFontSize let attrs = [ NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize), NSAttributedString.Key.foregroundColor: UIColor.black ] let nonBoldAttribute = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize), ] let attrStr = NSMutableAttributedString(string: string, attributes: attrs) if let range = nonBoldRange { attrStr.setAttributes(nonBoldAttribute, range: range) } return attrStr } 

Swift 3

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString { let fontSize = UIFont.systemFontSize let attrs = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: fontSize), NSForegroundColorAttributeName: UIColor.black ] let nonBoldAttribute = [ NSFontAttributeName: UIFont.systemFont(ofSize: fontSize), ] let attrStr = NSMutableAttributedString(string: string, attributes: attrs) if let range = nonBoldRange { attrStr.setAttributes(nonBoldAttribute, range: range) } return attrStr } 

Usage:

let targetString = "Updated 2012/10/14 21:59 PM" let range = NSMakeRange(7, 12) let label = UILabel(frame: CGRect(x:0, y:0, width:350, height:44)) label.backgroundColor = UIColor.white label.attributedText = attributedString(from: targetString, nonBoldRange: range) label.sizeToFit() 

Bonus: Internationalisation

Some people commented about internationalisation. I personally think this is out of scope of this question but for instructional purposes this is how I would do it

// Date we want to show let date = Date() // Create the string. // I don't set the locale because the default locale of the formatter is `NSLocale.current` so it's good for internationalisation :p let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short let targetString = String(format: NSLocalizedString("Update %@", comment: "Updated string format"), formatter.string(from: date)) // Find the range of the non-bold part formatter.timeStyle = .none let nonBoldRange = targetString.range(of: formatter.string(from: date)) // Convert Range<Int> into NSRange let nonBoldNSRange: NSRange? = nonBoldRange == nil ? nil : NSMakeRange(targetString.distance(from: targetString.startIndex, to: nonBoldRange!.lowerBound), targetString.distance(from: nonBoldRange!.lowerBound, to: nonBoldRange!.upperBound)) // Now just build the attributed string as before :) label.attributedText = attributedString(from: targetString, nonBoldRange: nonBoldNSRange) 

Result (Assuming English and Japanese Localizable.strings are available)

enter image description here

enter image description here


Previous answer for iOS6 and later (Objective-C still works):

In iOS6 UILabel, UIButton, UITextView, UITextField, support attributed strings which means we don’t need to create CATextLayers as our recipient for attributed strings. Furthermore to make the attributed string we don’t need to play with CoreText anymore :) We have new classes in obj-c Foundation.framework like NSParagraphStyle and other constants that will make our life easier. Yay!

So, if we have this string:

NSString *text = @"Updated: 2012/10/14 21:59" 

We only need to create the attributed string:

if ([_label respondsToSelector:@selector(setAttributedText:)]) { // iOS6 and above : Use NSAttributedStrings // Create the attributes const CGFloat fontSize = 13; NSDictionary *attrs = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize], NSForegroundColorAttributeName:[UIColor whiteColor] }; NSDictionary *subAttrs = @{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize] }; // Range of " 2012/10/14 " is (8,12). Ideally it shouldn't be hardcoded // This example is about attributed strings in one label // not about internationalisation, so we keep it simple :) // For internationalisation example see above code in swift const NSRange range = NSMakeRange(8,12); // Create the attributed string (text + attributes) NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attrs]; [attributedText setAttributes:subAttrs range:range]; // Set it in our UILabel and we are done! [_label setAttributedText:attributedText]; } else { // iOS5 and below // Here we have some options too. The first one is to do something // less fancy and show it just as plain text without attributes. // The second is to use CoreText and get similar results with a bit // more of code. Interested people please look down the old answer. // Now I am just being lazy so :p [_label setText:text]; } 

There is a couple of good introductory blog posts here from guys at invasivecode that explain with more examples uses of NSAttributedString, look for “Introduction to NSAttributedString for iOS 6” and “Attributed strings for iOS using Interface Builder” :)

PS: Above code it should work but it was brain-compiled. I hope it is enough :)


Old Answer for iOS5 and below

Use a CATextLayer with an NSAttributedString ! much lighter and simpler than 2 UILabels. (iOS 3.2 and above)

Example.

Don’t forget to add QuartzCore framework (needed for CALayers), and CoreText (needed for the attributed string.)

#import <QuartzCore/QuartzCore.h> #import <CoreText/CoreText.h> 

Below example will add a sublayer to the toolbar of the navigation controller. à la Mail.app in the iPhone. :)

- (void)setRefreshDate:(NSDate *)aDate { [aDate retain]; [refreshDate release]; refreshDate = aDate; if (refreshDate) { /* Create the text for the text layer*/ NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MM/dd/yyyy hh:mm"]; NSString *dateString = [df stringFromDate:refreshDate]; NSString *prefix = NSLocalizedString(@"Updated", nil); NSString *text = [NSString stringWithFormat:@"%@: %@",prefix, dateString]; [df release]; /* Create the text layer on demand */ if (!_textLayer) { _textLayer = [[CATextLayer alloc] init]; //_textLayer.font = [UIFont boldSystemFontOfSize:13].fontName; // not needed since `string` property will be an NSAttributedString _textLayer.backgroundColor = [UIColor clearColor].CGColor; _textLayer.wrapped = NO; CALayer *layer = self.navigationController.toolbar.layer; //self is a view controller contained by a navigation controller _textLayer.frame = CGRectMake((layer.bounds.size.width-180)/2 + 10, (layer.bounds.size.height-30)/2 + 10, 180, 30); _textLayer.contentsScale = [[UIScreen mainScreen] scale]; // looks nice in retina displays too :) _textLayer.alignmentMode = kCAAlignmentCenter; [layer addSublayer:_textLayer]; } /* Create the attributes (for the attributed string) */ CGFloat fontSize = 13; UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize]; CTFontRef ctBoldFont = CTFontCreateWithName((CFStringRef)boldFont.fontName, boldFont.pointSize, NULL); UIFont *font = [UIFont systemFontOfSize:13]; CTFontRef ctFont = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, NULL); CGColorRef cgColor = [UIColor whiteColor].CGColor; NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: (id)ctBoldFont, (id)kCTFontAttributeName, cgColor, (id)kCTForegroundColorAttributeName, nil]; CFRelease(ctBoldFont); NSDictionary *subAttributes = [NSDictionary dictionaryWithObjectsAndKeys:(id)ctFont, (id)kCTFontAttributeName, nil]; CFRelease(ctFont); /* Create the attributed string (text + attributes) */ NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes]; [attrStr addAttributes:subAttributes range:NSMakeRange(prefix.length, 12)]; //12 is the length of " MM/dd/yyyy/ " /* Set the attributes string in the text layer :) */ _textLayer.string = attrStr; [attrStr release]; _textLayer.opacity = 1.0; } else { _textLayer.opacity = 0.0; _textLayer.string = nil; } } 

In this example I only have two different types of font (bold and normal) but you could also have different font size, different color, italics, underlined, etc. Take a look at NSAttributedString / NSMutableAttributedString and CoreText attributes string keys.