Class

NSAttributedString

An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string. The cluster’s two public classes, NSAttributedString and NSMutableAttributedString, declare the programmatic interface for read-only attributed strings and modifiable attributed strings, respectively.

Overview

An attributed string identifies attributes by name, using an NSDictionary object to store a value under the given name. You can assign any attribute name/value pair you wish to a range of characters—it is up to your application to interpret custom attributes (see Attributed String Programming Guide). If you are using attributed strings with the Core Text framework, you can also use the attribute keys defined by that framework.

You use attributed strings with any APIs that accept them, such as Core Text. The AppKit and UIKit frameworks also provide a subclass of NSMutableAttributedString, called NSTextStorage, to provide the storage for the extended text-handling system. In iOS 6 and later you can use attributed strings to display formatted text in text views, text fields, and some other controls. Both AppKit and UIKit also define extensions to the basic attributed string interface that allows you to draw their contents in the current graphic context.

The default font for NSAttributedString objects is Helvetica 12-point, which may differ from the default system font for the platform. Thus, you might want to create new strings with non-default attributes suitable for your application. You can also use the NSParagraphStyle class and its subclass NSMutableParagraphStyle to encapsulate the paragraph or ruler attributes used by the NSAttributedString classes.

Be aware that comparisons of NSAttributedString objects using the isEqual: method look for exact equality. The comparison includes both a character-by-character string equality check and an equality check of all attributes. Such a comparison is not likely to yield a match if the string has many attributes, such as attachments, lists, and tables, for example.

The NSAttributedString class is “toll-free bridged” with its Core Foundation counterpart, CFAttributedString. See Toll-Free Bridging for more information.

Nested Types

Symbols

Creating an NSAttributedString Object

init(string: String)

Returns an NSAttributedString object initialized with the characters of a given string and no attribute information.

init(string: String, attributes: [String : Any]? = nil)

Returns an NSAttributedString object initialized with a given string and attributes.

init(attributedString: NSAttributedString)

Returns an NSAttributedString object initialized with the characters and attributes of another given attributed string.

init(data: Data, options: [String : Any] = [:], documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes and returns a new attributed string object from the data contained in the given data object.

init?(docFormat: Data, documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes and returns a new NSAttributedString object from Microsoft Word format data contained in the given NSData object.

init?(html: Data, documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes and returns a new NSAttributedString object from HTML contained in the given data object.

init?(html: Data, baseURL: URL, documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes and returns a new NSAttributedString object from the HTML contained in the given object and base URL.

init?(html: Data, options: [AnyHashable : Any] = [:], documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes and returns a new attributed string object from HTML contained in the given data object.

init?(rtf: Data, documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes a new attributed string object by decoding the stream of RTF commands and data contained in the given data object.

init?(rtfd: Data, documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes a new attributed string object by decoding the stream of RTFD commands and data contained in the given data object.

init?(rtfdFileWrapper: FileWrapper, documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes a new attributed string object from the specified file wrapper containing an RTFD document.

init(url: URL, options: [String : Any] = [:], documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes a new NSAttributedString object from the contents of the given URL.

init(attachment: NSTextAttachment)

Creates an attributed string with an attachment.

Retrieving Character Information

var string: String

The character contents of the receiver as an NSString object.

var length: Int

The length of the receiver’s string object.

Retrieving Attribute Information

func attributes(at: Int, effectiveRange: NSRangePointer?)

Returns the attributes for the character at a given index.

func attributes(at: Int, longestEffectiveRange: NSRangePointer?, in: NSRange)

Returns the attributes for the character at a given index, and by reference the range over which the attributes apply.

func attribute(String, at: Int, effectiveRange: NSRangePointer?)

Returns the value for an attribute with a given name of the character at a given index, and by reference the range over which the attribute applies.

func attribute(String, at: Int, longestEffectiveRange: NSRangePointer?, in: NSRange)

Returns the value for the attribute with a given name of the character at a given index, and by reference the range over which the attribute applies.

Comparing Attributed Strings

func isEqual(to: NSAttributedString)

Returns a Boolean value that indicates whether the receiver is equal to another given attributed string.

Extracting a Substring

func attributedSubstring(from: NSRange)

Returns an NSAttributedString object consisting of the characters and attributes within a given range in the receiver.

Retrieving Font Attribute Information

func fontAttributes(in: NSRange)

Returns the font attributes in effect for the character at the given location.

func rulerAttributes(in: NSRange)

Returns the ruler (paragraph) attributes in effect for the characters within the given range.

Calculating Linguistic Units

func doubleClick(at: Int)

Returns the range of characters that form a word (or other linguistic unit) surrounding the given index, taking language characteristics into account.

func lineBreak(before: Int, within: NSRange)

Returns the appropriate line break when the character at the index won’t fit on the same line as the character at the beginning of the range.

func lineBreakByHyphenating(before: Int, within: NSRange)

Returns the index of the closest character before the given index, and within the given range, that can be placed on a new line by hyphenating.

func nextWord(from: Int, forward: Bool)

Returns the index of the first character of the word after or before the given index.

Calculating Ranges

func itemNumber(in: NSTextList, at: Int)

Returns the index of the item at the given location within the list.

func range(of: NSTextBlock, at: Int)

Returns the range of the individual text block that contains the given location.

func range(of: NSTextList, at: Int)

Returns the range of the given text list that contains the given location.

func range(of: NSTextTable, at: Int)

Returns the range of the given text table that contains the given location

Generating Data

func data(from: NSRange, documentAttributes: [String : Any] = [:])

Returns an data object that contains a text stream corresponding to the characters and attributes within the given range.

func fileWrapper(from: NSRange, documentAttributes: [String : Any] = [:])

Returns an NSFileWrapper object that contains a text stream corresponding to the characters and attributes within the given range.

func docFormat(from: NSRange, documentAttributes: [String : Any] = [:])

Returns a data object that contains a Microsoft Word–format stream corresponding to the characters and attributes within the specified range.

func rtf(from: NSRange, documentAttributes: [String : Any] = [:])

Returns an NSData object that contains an RTF stream corresponding to the characters and attributes within the given range, omitting all attachment attributes.

func rtfd(from: NSRange, documentAttributes: [String : Any] = [:])

Returns an data object that contains an RTFD stream corresponding to the characters and attributes within the range.

func rtfdFileWrapper(from: NSRange, documentAttributes: [String : Any] = [:])

Returns an NSFileWrapper object that contains an RTFD document corresponding to the characters and attributes within the given range.

Drawing the String

func draw(at: CGPoint)

Draws the attributed string starting at the specified point in the current graphics context.

func draw(in: CGRect)

Draws the attributed string inside the specified bounding rectangle in the current graphics context.

func draw(with: CGRect, options: NSStringDrawingOptions = [], context: NSStringDrawingContext?)

Draws the attributed string in the specified bounding rectangle using the provided options.

Getting Metrics for the String

func size()

Returns the size required to draw the string.

func containsAttachments(in: NSRange)

Returns a Boolean value that indicates if the attributed string contains a property configured in the specified range.

Testing String Data Sources

class func textTypes()

Returns an array of UTI strings identifying the file types supported by the receiver, either directly or through a user-installed filter service.

class func textUnfilteredTypes()

Returns an array of UTI strings identifying the file types supported directly by the receiver.

Deprecated Methods

init?(path: String, documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes a new attribute string object from RTF or RTFD data contained in the file at the given path.

Deprecated
init?(url: URL, documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes a new attributed string object from the data at the given URL.

Deprecated
init(fileURL: URL, options: [AnyHashable : Any] = [:], documentAttributes: AutoreleasingUnsafeMutablePointer<NSDictionary?>?)

Initializes a new attributed string object from the data at the given URL.

Deprecated
var containsAttachments: Bool

Returns whether the attribute string contains any attachment attributes.

Deprecated
func url(at: Int, effectiveRange: NSRangePointer)

Returns a URL, either from a link attribute or from text at the given location that appears to be a URL string, for use in automatic link detection.

Deprecated
func draw(with: NSRect, options: NSStringDrawingOptions = [])

Draws the receiver with the specified options, within the given rectangle in the current graphics context.

Deprecated
func boundingRect(with: NSSize, options: NSStringDrawingOptions = [])

Calculates and returns bounding rectangle for the receiver drawn using the options specified, within the given rectangle in the current graphics context.

Deprecated

Constants

EnumerationOptions

These constants describe the options available to the enumerateAttribute(_:in:options:using:) and enumerateAttributes(in:options:using:) methods.

NSUnderlineStyle

Constants for specifying both the NSUnderlineStyleAttributeName and NSStrikethroughStyleAttributeName attributes of an attributed string.

NSWritingDirectionFormatType

Options for specifying writing direction used with NSWritingDirectionAttributeName.

Character Attributes

Attributes that you can apply to text in an attributed string.

Glyph Info Attribute

This object provides a means to override the standard glyph generation.

Character Shape Attribute

The character shape feature type (kCharacterShapeType) is used when a single font contains different appearances for the same character shape, and these shapes are not traditionally treated as swashes. It is needed for languages such as Chinese that have both traditional and simplified character sets.

Document Types

The following values can be returned for the NSDocumentTypeDocumentAttribute key in the document attributes dictionary.

Document Attributes

The init... methods can return a dictionary with the following document-wide attributes (attribute identifiers available in macOS 10.4 and later; use actual string value keys for earlier systems):

Attributes for Generating HTML

These document-wide attributes provide control over the form of generated HTML—you use them only for writing HTML

NSSpellingStateAttributeName Flags

These constants control the display of the spelling and grammar indicators on text, highlighting portions of the text that are flagged for spelling or grammar issues. These regions are denoted by a temporary attribute on the layout manager, using the NSSpellingStateAttributeName key.

NSTextWritingDirection

Options for specifying text writing direction used with NSWritingDirectionAttributeName.

Deprecated
Underline Masks

This constant defines the underlining style for NSUnderlineStyleAttributeName and NSStrikethroughStyleAttributeName.