NSAttributedString
iOS Development
Swift Programming
Text Styling
Apple Developer

How do you use NSAttributedString?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

NSAttributedString is a powerful and flexible class in the Foundation framework used in macOS, iOS, watchOS, and tvOS to manage text. Unlike a regular string, an NSAttributedString holds both the text and a set of attributes that pertain to how the text should be styled. This capability makes it an essential tool for developing user interfaces where styled text is necessary, such as in labels, text views, and other UI elements. Here's a deeper look into how to use NSAttributedString.

Understanding NSAttributedString

What is NSAttributedString?

An NSAttributedString is a string that has associated attributes like font, color, and paragraph style, which apply to ranges of characters within the string. It's immutable, meaning once created, the content and its attributes can't be modified. If mutability is required, one can use NSMutableAttributedString.

Key Components

  1. String Content: The actual plain text represented by the NSString object.
  2. Attributes: A dictionary mapping NSAttributedString.Key constants to their corresponding values. Each attribute affects the display style of specific ranges within the string.

Common Attributes

Here are some standard attributes with their uses:

  • NSFontAttributeName: Specifies the font of the text.
  • NSForegroundColorAttributeName: Sets the color of the text.
  • NSBackgroundColorAttributeName: Defines the background color of the text.
  • NSUnderlineStyleAttributeName: Determines whether the text is underlined.

How to Create NSAttributedString

Using a Dictionary for Attributes

To create an NSAttributedString, you'll need to define your text and attribute dictionary:

swift
1import UIKit
2
3let text = "Welcome to NSAttributedString!"
4let attributes: [NSAttributedString.Key: Any] = [
5    .font: UIFont.systemFont(ofSize: 18, weight: .bold),
6    .foregroundColor: UIColor.blue
7]
8
9let attributedString = NSAttributedString(string: text, attributes: attributes)

Creating an NSMutableAttributedString

If you need to change attributes dynamically, consider using NSMutableAttributedString:

swift
let mutableAttributedString = NSMutableAttributedString(string: "Hello, this is mutable!")
mutableAttributedString.addAttribute(.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: 5))
mutableAttributedString.addAttribute(.font, value: UIFont.italicSystemFont(ofSize: 12), range: NSRange(location: 18, length: 7))

Applying Multiple Attributes

Attributes can be combined to apply multiple styles:

swift
1let fullString = "Swift Programming"
2let multiAttributes: [NSAttributedString.Key: Any] = [
3    .font: UIFont.systemFont(ofSize: 16),
4    .backgroundColor: UIColor.yellow,
5    .underlineStyle: NSUnderlineStyle.single.rawValue
6]
7
8let multiAttributedString = NSAttributedString(string: fullString, attributes: multiAttributes)

Using NSAttributedString in UI Components

UILabel Example

To display an NSAttributedString in a UILabel:

swift
let label = UILabel()
label.attributedText = attributedString

UITextView Example

Similarly, for a UITextView:

swift
let textView = UITextView()
textView.attributedText = attributedString

Customizing Specific Text Ranges

Using NSMutableAttributedString, customizing specific text ranges becomes straightforward:

swift
let richText = NSMutableAttributedString(string: "Welcome to SwiftUI Development")
richText.addAttributes([.foregroundColor: UIColor.green], range: NSRange(location: 11, length: 7))
richText.addAttributes([.font: UIFont.boldSystemFont(ofSize: 20)], range: NSRange(location: 0, length: 7))

Summary Table

Below is a summary table of some key points regarding NSAttributedString.

AspectDescription
ImmutabilityNSAttributedString is immutable; use NSMutableAttributedString for changes.
Attribute DictionaryAttributes are specified as key-value pairs in a dictionary.
Common AttributesFont, color, background color, underline, etc.
UtilitiesIntegrates seamlessly with UI components like UILabel, UITextView.
Range UsageSpecific ranges of text can have different attributes.

Conclusion

NSAttributedString and NSMutableAttributedString provide an efficient mechanism to manage complex text styles in Apple platform applications. Whether rendering formatted text in a label, a text view, or other UI element, these classes are indispensable tools for giving your text rich multi-format styles effortlessly. With this understanding, you can harness the full potential of text styling in your applications.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.