UILabel
iOS
Text Formatting
Swift
Attributed Strings

Bold Non-Bold Text In A Single UILabel?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

UILabel is a fundamental component in iOS development used for displaying a small amount of read-only text. While UILabel provides a straightforward way to present text, developers may find a need to differentiate parts of the text by using different font styles, such as bold and regular, within the same label. This article will delve into how you can achieve bold and non-bold text styling in a single UILabel, exploring both technical and practical aspects.

Basic UILabel Setup

At its core, UILabel is designed to display text content in a single style, defined by properties such as font, textColor, textAlignment, and others. However, with the introduction of NSAttributedString, developers can apply different styles to parts of the text within a single UILabel.

Here's a basic setup of a UILabel:

swift
1let label = UILabel()
2label.frame = CGRect(x: 10, y: 20, width: 200, height: 50)
3label.text = "Hello, World!"
4label.textColor = .black
5view.addSubview(label)

This initial code snippet will display "Hello, World!" in default font style and color. To apply mixed text styles, we would leverage NSAttributedString.

Using NSAttributedString for Mixed Styles

NSAttributedString is an immutable string object that helps apply multiple attributes to texts, such as font, color, underline, and many more. NSMutableAttributedString, a subclass of NSAttributedString, provides the flexibility to modify these attributes for different text ranges.

Step-by-step Example

  1. Initialize a NSMutableAttributedString:
swift
   let attributedText = NSMutableAttributedString(string: "Bold and Regular Text")
  1. Define Attributes:
    Attributes are defined using key-value pairs where the key is NSAttributedString.Key and the value is the corresponding attribute setting.
swift
1   let boldAttributes: [NSAttributedString.Key: Any] = [
2       .font: UIFont.boldSystemFont(ofSize: 16),
3       .foregroundColor: UIColor.black
4   ]
5
6   let regularAttributes: [NSAttributedString.Key: Any] = [
7       .font: UIFont.systemFont(ofSize: 16),
8       .foregroundColor: UIColor.darkGray
9   ]
  1. Apply Attributes to Text Ranges:
    To apply different attributes to different parts of the text, we use the addAttributes(_:range:) method of NSMutableAttributedString.
swift
   attributedText.addAttributes(boldAttributes, range: NSRange(location: 0, length: 4))
   attributedText.addAttributes(regularAttributes, range: NSRange(location: 5, length: 14))
  1. Assign Attributed Text to UILabel:
    Finally, we assign the attributed text to the label's attributedText property.
swift
   label.attributedText = attributedText

The above code will result in a UILabel displaying the words "Bold" in bold font and "and Regular Text" in a regular font.

Considerations

While using attributed strings allows more flexibility and visual differentiation within UILabels, there are considerations and caveats to keep in mind:

  • Performance: Using NSAttributedString for very long texts could impact performance, especially during dynamic updates.
  • Text Alignment: Alignment can be mixed by applying paragraph styles with different alignments to different text segments.
  • Internationalization: Care should be taken with languages that modify sentence structure. The provided ranges must be adjusted accordingly.

Summary Table

FeatureDescriptionExample Usage
NSAttributedStringImmutable styled text objectNSAttributedString(string: "Text")
NSMutableAttributedStringMutable subclass for applying stylesNSMutableAttributedString(...)
AttributesDictionary with NSAttributedString.Keylet attributes: [NSAttributedString.Key: Any]
Font StyleDefined via UIFont.font: UIFont.boldSystemFont(ofSize: 16)
Text RangeApply styles to specific text ranges using NSRangeUsed in addAttributes(_:range:)

Additional Techniques

Dynamic Text Support

When dealing with user accessibility preferences, it is crucial to support dynamic text settings. This can be achieved by listening to notification changes on text size preferences and adjusting UIFont accordingly.

swift
1NotificationCenter.default.addObserver(
2    self,
3    selector: #selector(preferredContentSizeChanged(_:)),
4    name: UIContentSizeCategory.didChangeNotification,
5    object: nil
6)

Localization

Internationalization and localization require careful attention when working with attributed strings. Developers should ensure that localized text maintains the desired style attributes and correctly applies them to appropriate text segments given the variability in text length across languages.

Alternative Solutions

For more complex text content, consider using a UITextView, which offers greater flexibility and editing capabilities, yet can still leverage NSAttributedString for static content presentation.

By understanding and utilizing NSAttributedString, developers can efficiently create visually appealing and dynamic text displays within their iOS applications, enhancing the user experience while adhering to design standards.


Course illustration
Course illustration

All Rights Reserved.