iOS Developer Library

Developer

Foundation Framework Reference NSAttributedString Class Reference

Options
Deployment Target:

On This Page
Language:

NSAttributedString

Inheritance


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 3.2 and later.

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.

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. In iOS, standard attribute keys are described in the “Constants” section of NSAttributedString UIKit Additions Reference. In OS X, standard attribute keys are described in the “Constants” section of NSAttributedString Application Kit Additions Reference.

You use attributed strings with any APIs that accept them, such as Core Text. The Application Kit and UIKit 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, CFAttributedStringRef. See Toll-Free Bridging for more information.

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

    Declaration

    Swift

    init(string aString: String)

    Objective-C

    - (instancetype)initWithString:(NSString *)aString

    Parameters

    aString

    The characters for the new object.

    Return Value

    An NSAttributedString object initialized with the characters of aString and no attribute information The returned object might be different than the original receiver.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

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

    Declaration

    Swift

    init(attributedString attributedString: NSAttributedString)

    Objective-C

    - (instancetype)initWithAttributedString:(NSAttributedString *)attributedString

    Parameters

    attributedString

    An attributed string.

    Return Value

    An NSAttributedString object initialized with the characters and attributes of attributedString. The returned object might be different than the original receiver.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

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

    Declaration

    Swift

    init(string aString: String, attributes attributes: [NSObject : AnyObject]?)

    Objective-C

    - (instancetype)initWithString:(NSString *)aString attributes:(NSDictionary *)attributes

    Parameters

    aString

    The string for the new attributed string.

    attributes

    The attributes for the new attributed string. For information about where to find the attribute keys you can include in this dictionary, see the overview section of this document.

    Discussion

    Returns an NSAttributedString object initialized with the characters of aString and the attributes of attributes. The returned object might be different from the original receiver.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

  • string string Property

    The character contents of the receiver as an NSString object. (read-only)

    Declaration

    Swift

    var string: String { get }

    Objective-C

    @property(readonly, copy) NSString *string

    Discussion

    Attachment characters are not removed from the value of this property.

    For performance reasons, this property returns the current backing store of the attributed string object. If you want to maintain a snapshot of this as you manipulate the returned string, you should make a copy of the appropriate substring.

    This primitive property must guarantee efficient access to an attributed string’s characters; subclasses should implement it to execute in O(1) time.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

  • length length Property

    The length of the receiver’s string object. (read-only)

    Declaration

    Swift

    var length: Int { get }

    Objective-C

    @property(readonly) NSUInteger length

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

    See Also

    length (NSString)
    size (NSAttributedString)

  • Returns the attributes for the character at a given index.

    Declaration

    Swift

    func attributesAtIndex(_ index: Int, effectiveRange aRange: NSRangePointer) -> [NSObject : AnyObject]

    Objective-C

    - (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange

    Parameters

    index

    The index for which to return attributes. This value must lie within the bounds of the receiver.

    aRange

    Upon return, the range over which the attributes and values are the same as those at index. This range isn’t necessarily the maximum range covered, and its extent is implementation-dependent. If you need the maximum range, use attributesAtIndex:longestEffectiveRange:inRange:. If you don't need this value, pass NULL.

    Return Value

    The attributes for the character at index.

    Discussion

    Raises an NSRangeException if index lies beyond the end of the receiver’s characters.

    For information about where to find the attribute keys for the returned dictionary, see the overview section of this document.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

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

    Declaration

    Swift

    func attributesAtIndex(_ index: Int, longestEffectiveRange aRange: NSRangePointer, inRange rangeLimit: NSRange) -> [NSObject : AnyObject]

    Objective-C

    - (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit

    Parameters

    index

    The index for which to return attributes. This value must not exceed the bounds of the receiver.

    aRange

    If non-NULL, upon return contains the maximum range over which the attributes and values are the same as those at index, clipped to rangeLimit.

    rangeLimit

    The range over which to search for continuous presence of the attributes at index. This value must not exceed the bounds of the receiver.

    Discussion

    Raises an NSRangeException if index or any part of rangeLimit lies beyond the end of the receiver’s characters.

    If you don’t need the range information, it’s far more efficient to use the attributesAtIndex:effectiveRange: method to retrieve the attribute value.

    For information about where to find the attribute keys for the returned dictionary, see the overview section of this document.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

  • 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.

    Declaration

    Swift

    func attribute(_ attributeName: String, atIndex index: Int, effectiveRange aRange: NSRangePointer) -> AnyObject?

    Objective-C

    - (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange

    Parameters

    attributeName

    The name of an attribute.

    index

    The index for which to return attributes. This value must not exceed the bounds of the receiver.

    aRange

    If non-NULL:

    • If the named attribute exists at index, upon return aRange contains a range over which the named attribute’s value applies.

    • If the named attribute does not exist at index, upon return aRange contains the range over which the attribute does not exist.

    The range isn’t necessarily the maximum range covered by attributeName, and its extent is implementation-dependent. If you need the maximum range, use attribute:atIndex:longestEffectiveRange:inRange:. If you don't need this value, pass NULL.

    Return Value

    The value for the attribute named attributeName of the character at index index, or nil if there is no such attribute.

    Discussion

    Raises an NSRangeException if index lies beyond the end of the receiver’s characters.

    For information about where to find the attribute keys for the returned dictionary, see the overview section of this document.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

  • 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.

    Declaration

    Swift

    func attribute(_ attributeName: String, atIndex index: Int, longestEffectiveRange aRange: NSRangePointer, inRange rangeLimit: NSRange) -> AnyObject?

    Objective-C

    - (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit

    Parameters

    attributeName

    The name of an attribute.

    index

    The index at which to test for attributeName.

    aRange

    If non-NULL:

    • If the named attribute exists at index, upon return aRange contains the full range over which the value of the named attribute is the same as that at index, clipped to rangeLimit.

    • If the named attribute does not exist at index, upon return aRange contains the full range over which the attribute does not exist, clipped to rangeLimit.

    If you don't need this value, pass NULL.

    rangeLimit

    The range over which to search for continuous presence of attributeName. This value must not exceed the bounds of the receiver.

    Return Value

    The value for the attribute named attributeName of the character at index, or nil if there is no such attribute.

    Discussion

    Raises an NSRangeException if index or any part of rangeLimit lies beyond the end of the receiver’s characters.

    If you don’t need the longest effective range, it’s far more efficient to use the attribute:atIndex:effectiveRange: method to retrieve the attribute value.

    For information about where to find the attribute keys for the returned dictionary, see the overview section of this document.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

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

    Declaration

    Swift

    func isEqualToAttributedString(_ otherString: NSAttributedString) -> Bool

    Objective-C

    - (BOOL)isEqualToAttributedString:(NSAttributedString *)otherString

    Parameters

    otherString

    The attributed string with which to compare the receiver.

    Return Value

    YEStrue if the receiver is equal to otherString, otherwise NOfalse.

    Discussion

    Attributed strings must match in both characters and attributes to be equal.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

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

    Declaration

    Swift

    func attributedSubstringFromRange(_ aRange: NSRange) -> NSAttributedString

    Objective-C

    - (NSAttributedString *)attributedSubstringFromRange:(NSRange)aRange

    Parameters

    aRange

    The range from which to create a new attributed string. aRange must lie within the bounds of the receiver.

    Return Value

    An NSAttributedString object consisting of the characters and attributes within aRange in the receiver.

    Discussion

    Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters. This method treats the length of the string as a valid range value that returns an empty string.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.2 and later.

  • Executes the Block for the specified attribute run in the specified range.

    Declaration

    Swift

    func enumerateAttribute(_ attrName: String, inRange enumerationRange: NSRange, options opts: NSAttributedStringEnumerationOptions, usingBlock block: (AnyObject!, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)

    Objective-C

    - (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(id value, NSRange range, BOOL *stop))block

    Parameters

    attrName

    The name of an attribute.

    enumerationRange

    If non-NULL, contains the maximum range over which the attributes and values are enumerated, clipped to enumerationRange.

    opts

    The options used by the enumeration. The values can be combined using C-bitwise OR. The values are described in NSAttributedStringEnumerationOptions.

    block

    The Block to apply to ranges of the attribute in the attributed string.

    The Block takes three arguments:

    value

    The attrName value.

    range

    An NSRange indicating the run of the attribute.

    stop

    A reference to a Boolean value. The block can set the value to YEStrue to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.

    Discussion

    If this method is sent to an instance of NSMutableAttributedString, mutation (deletion, addition, or change) is allowed, as long as it is within the range provided to the block; after a mutation, the enumeration continues with the range immediately following the processed range, after the length of the processed range is adjusted for the mutation. (The enumerator basically assumes any change in length occurs in the specified range.)

    For example, if block is called with a range starting at location N, and the block deletes all the characters in the supplied range, the next call will also pass N as the index of the range.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Executes the Block for each attribute in the range.

    Declaration

    Swift

    func enumerateAttributesInRange(_ enumerationRange: NSRange, options opts: NSAttributedStringEnumerationOptions, usingBlock block: ([NSObject : AnyObject]!, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)

    Objective-C

    - (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(NSDictionary *attrs, NSRange range, BOOL *stop))block

    Parameters

    enumerationRange

    If non-NULL, contains the maximum range over which the attributes and values are enumerated, clipped to enumerationRange.

    opts

    The options used by the enumeration. The values can be combined using C-bitwise OR. The values are described in NSAttributedStringEnumerationOptions.

    block

    The Block to apply to ranges of the attribute in the attributed string.

    The Block takes three arguments:

    attrs

    An NSDictionary that contains the attributes for the range.

    range

    An NSRange indicating the run of the attribute.

    stop

    A reference to a Boolean value. The block can set the value to YEStrue to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YEStrue within the Block.

    Discussion

    If this method is sent to an instance of NSMutableAttributedString, mutation (deletion, addition, or change) is allowed, as long as it is within the range provided to the block; after a mutation, the enumeration continues with the range immediately following the processed range, after the length of the processed range is adjusted for the mutation. (The enumerator basically assumes any change in length occurs in the specified range.)

    For example, if block is called with a range starting at location N, and the block deletes all the characters in the supplied range, the next call will also pass N as the index of the range.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • These constants describe the options available to the enumerateAttribute:inRange:options:usingBlock: and enumerateAttributesInRange:options:usingBlock: methods.

    Declaration

    Swift

    struct NSAttributedStringEnumerationOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var Reverse: NSAttributedStringEnumerationOptions { get } static var LongestEffectiveRangeNotRequired: NSAttributedStringEnumerationOptions { get } }

    Objective-C

    enum { NSAttributedStringEnumerationReverse = (1UL << 1), NSAttributedStringEnumerationLongestEffectiveRangeNotRequired = (1UL << 20) }; typedef NSUInteger NSAttributedStringEnumerationOptions;

    Constants

    • Reverse

      NSAttributedStringEnumerationReverse

      Causes the enumeration to occur in reverse.

      Available in iOS 4.0 and later.

    • LongestEffectiveRangeNotRequired

      NSAttributedStringEnumerationLongestEffectiveRangeNotRequired

      If NSAttributedStringEnumerationLongestEffectiveRangeNotRequired option is supplied, then the longest effective range computation is not performed; the blocks may be invoked with consecutive attribute runs that have the same value.

      Available in iOS 4.0 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.