iOS Developer Library

Developer

Foundation Framework Reference NSAttributedString Class Reference

Options
Deployment Target:

On This Page
Language:

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.

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, 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 str: 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 a given string and attributes.

    Declaration

    Swift

    init(string str: String, attributes attrs: [String : AnyObject]?)

    Objective-C

    - (instancetype)initWithString:(NSString *)aString attributes:(NSDictionary<NSString *,id> *)attributes

    Parameters

    aString

    The string for the new attributed string.

    attributes

    The attributes for the new attributed string. For a list of attributes that you can include in this dictionary, see Character Attributes.

    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.

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

    Declaration

    Swift

    init(attributedString attrStr: 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.

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

    Declaration

    Swift

    init(data data: NSData, options options: [String : AnyObject], documentAttributes dict: AutoreleasingUnsafeMutablePointer<NSDictionary?>) throws

    Objective-C

    - (instancetype)initWithData:(NSData *)data options:(NSDictionary<NSString *,id> *)options documentAttributes:(NSDictionary<NSString *,id> * _Nullable *)dict error:(NSError * _Nullable *)error

    Parameters

    data

    The data from which to create the string.

    options

    Document attributes for interpreting the document contents. NSDocumentTypeDocumentAttribute, NSCharacterEncodingDocumentAttribute, and NSDefaultAttributesDocumentAttribute are supported option keys. If you pass an empty dictionary, the method examines the data to attempt to determine the appropriate attributes.

    dict

    An in-out dictionary containing document-level attributes described in Document Attributes. May be NULL, in which case no document attributes are returned.

    error

    An in-out variable containing an encountered error, if any.

    Return Value

    Returns an initialized attributed string object, or nil if the data can’t be decoded.

    Discussion

    The HTML importer should not be called from a background thread (that is, the options dictionary includes NSDocumentTypeDocumentAttribute with a value of NSHTMLTextDocumentType). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.

    Availability

    Available in iOS 7.0 and later.

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

    Declaration

    Swift

    init(URL url: NSURL, options options: [String : AnyObject], documentAttributes dict: AutoreleasingUnsafeMutablePointer<NSDictionary?>) throws

    Objective-C

    - (instancetype)initWithURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options documentAttributes:(NSDictionary<NSString *,id> * _Nullable *)docAttributes error:(NSError * _Nullable *)error

    Parameters

    url

    An NSURL object specifying the document to load.

    options

    Specifies how the document should be loaded. Contains values described in Option keys for importing documents.

    docAttributes

    An in-out dictionary containing document-level attributes described in Document Attributes. May be NULL, in which case no document attributes are returned.

    error

    An in-out parameter that returns an error if the method returns nil.

    Return Value

    Returns an initialized object, or nil if the data can’t be decoded.

    Discussion

    Filter services can be used to convert the file into a format recognized by Cocoa. The options dictionary specifies how the document should be loaded and can contain the values described in Option keys for importing documents.

    If NSDocumentTypeDocumentOption is specified, the document is treated as being in the specified format. If NSDocumentTypeDocumentOption is not specified, the method examines the document and loads it using whatever format it seems to contain.

    Also returns by reference in dict a dictionary containing document-level attributes described in Document Attributes. The dict parameter may be nil, in which case no document attributes are returned. Returns an initialized object, or nil if the file at url can’t be decoded, after setting error to point to an NSError object that encapsulates the reason why the attributed string object could not be created.

    Availability

    Available in iOS 9.0 and later.

  • Creates an attributed string with an attachment.

    Declaration

    Swift

    init(attachment attachment: NSTextAttachment)

    Objective-C

    + (NSAttributedString *)attributedStringWithAttachment:(NSTextAttachment *)attachment

    Parameters

    attachment

    The attachment.

    Return Value

    An attributed string containing the attachment.

    Discussion

    This is a convenience method for creating an attributed string containing an attachment using NSAttachmentCharacter as the base character.

    Availability

    Available in iOS 7.0 and later.

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

  • 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(_ location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject]

    Objective-C

    - (NSDictionary<NSString *,id> *)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 a list of possible attributes, see Character Attributes.

    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(_ location: Int, longestEffectiveRange range: NSRangePointer, inRange rangeLimit: NSRange) -> [String : AnyObject]

    Objective-C

    - (NSDictionary<NSString *,id> *)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 a list of possible attributes, see Character Attributes.

    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(_ attrName: String, atIndex location: Int, effectiveRange range: 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, or nil if there is no such attribute.

    Discussion

    For a list of possible attributes, see Character Attributes.

    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(_ attrName: String, atIndex location: Int, longestEffectiveRange range: 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 a list of possible attributes, see Character Attributes.

    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(_ other: 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(_ range: 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 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.

  • Executes the block for each attribute in the range.

    Declaration

    Swift

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

    Objective-C

    - (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(NSDictionary<NSString *,id> *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

    The attributes for the range.

    range

    The run of the attributes.

    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.

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

    Declaration

    Swift

    func drawAtPoint(_ point: CGPoint)

    Objective-C

    - (void)drawAtPoint:(CGPoint)point

    Parameters

    point

    The point in the current graphics context where you want to start drawing the string. The coordinate system of the graphics context is usually defined by the view in which you are drawing.

    Discussion

    This method draws the entire string starting at the specified point. This method draws the line using the attributes specified in the attributed string itself. If newline characters are present in the string, those characters are honored and cause subsequent text to be placed on the next line underneath the starting point.

    There must be either a focused view or an active graphics context when you call this method.

    Availability

    Available in iOS 6.0 and later.

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

    Declaration

    Swift

    func drawInRect(_ rect: CGRect)

    Objective-C

    - (void)drawInRect:(CGRect)rect

    Parameters

    rect

    The bounding rectangle in which to draw the string. In AppKit, the origin is normally in the lower-left corner of the drawing area, but the origin is in the upper-left corner if the focused view is flipped.

    Discussion

    This method draws as much of the string as it can inside the specified rectangle, wrapping the string text as needed to make it fit. If the string is too long to fit inside the rectangle, the method renders as much as possible and clips the rest. It is possible for a portion of a glyph to appear outside the area of rect if the image bounding box of the particular glyph exceeds its typographic bounding box. Text is drawn according to its line sweep direction; for example, Arabic text begins at the right edge and is potentially clipped on the left.

    Layout always occurs from top to bottom. AppKit automatically adjusts the initial drawing point whether or not the view is flipped. For example, if the rect argument is {0.0, 0.0, 100.0, 100.0}, the text origin is {0.0, 0.0} when the view coordinates are flipped and {0.0, 100.0} when the view is not flipped.

    This method draws the line using the attributes specified in the attributed string itself. If newline characters are present in the string, those characters are honored and cause subsequent text to be placed on the next line underneath the starting point.

    There must be either a focused view or an active graphics context when you call this method.

    Availability

    Available in iOS 6.0 and later.

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

    Declaration

    Swift

    func drawWithRect(_ rect: CGRect, options options: NSStringDrawingOptions, context context: NSStringDrawingContext?)

    Objective-C

    - (void)drawWithRect:(CGRect)rect options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context

    Parameters

    rect

    The bounding rectangle in which to draw the string.

    options

    Additional drawing options to apply to the string during rendering. For a list of possible values, see NSStringDrawingOptions.

    context

    A context object with information about how to adjust the font tracking and scaling information. On return, the specified object contains information about the actual values used to render the string. This parameter may be nil.

    Discussion

    If NSStringDrawingUsesLineFragmentOrigin is specified in options, it wraps the string text as needed to make it fit. If the string is too big to fit completely inside the rectangle, the method scales the font or adjusts the letter spacing to make the string fit within the given bounds.

    If NSStringDrawingUsesLineFragmentOrigin is not specified in options, the origin of the rectangle is the baseline of the only line. The text will be displayed above the rectangle and not inside of it. For example, if you specify a rectangle starting at 0,0 and draw the string ‘juxtaposed’, only the descenders of the ‘j’ and ‘p’ will be seen. The rest of the text will be on the top edge of the rectangle.

    This method draws the line using the attributes specified in the attributed string itself. If newline characters are present in the string, those characters are honored and cause subsequent text to be placed on the next line underneath the starting point.

    There must be either an active graphics context when you call this method.

    Special Considerations

    This method uses the baseline origin by default, so it renders the string as a single line. To render the string in multiple lines, specify NSStringDrawingUsesLineFragmentOrigin in options.

    Availability

    Available in iOS 6.0 and later.

  • Returns the size required to draw the string.

    Declaration

    Swift

    func size() -> CGSize

    Objective-C

    - (CGSize)size

    Return Value

    The minimum size required to draw the entire contents of the string.

    Discussion

    You can use this method prior to drawing to compute how much space is required to draw the string.

    This method may return fractional sizes. When setting the size of your view, use the ceil function to round fractional values up to the nearest whole number.

    Availability

    Available in iOS 6.0 and later.

  • Returns the bounding rectangle required to draw the string.

    Declaration

    Swift

    func boundingRectWithSize(_ size: CGSize, options options: NSStringDrawingOptions, context context: NSStringDrawingContext?) -> CGRect

    Objective-C

    - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context

    Parameters

    size

    The width and height constraints to apply when computing the string’s bounding rectangle.

    options

    Additional drawing options to apply to the string during rendering. For a list of possible values, see NSStringDrawingOptions.

    context

    A context object with information about how to adjust the font tracking and scaling information. On return, the specified object contains information about the actual values used to render the string. This parameter may be nil.

    Return Value

    A rectangle whose size component indicates the width and height required to draw the entire contents of the string.

    Discussion

    You can use this method to compute the space required to draw the string. The constraints you specify in the size parameter are a guide for the renderer for how to size the string. However, the actual bounding rectangle returned by this method can be larger than the constraints if additional space is needed to render the entire string. Typically, the renderer preserves the width constraint and adjusts the height constraint as needed.

    In iOS 7 and later, this method returns fractional sizes (in the size component of the returned rectangle); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.

    Special Considerations

    To calculate the bounding rectangle, this method uses the baseline origin by default, so it behaves as a single line. To render the string in multiple lines, specify NSStringDrawingUsesLineFragmentOrigin in options.

    Availability

    Available in iOS 6.0 and later.

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

    Declaration

    Swift

    func containsAttachmentsInRange(_ range: NSRange) -> Bool

    Objective-C

    - (BOOL)containsAttachmentsInRange:(NSRange)range

    Parameters

    range

    The range.

    Return Value

    YEStrue if the attributed string contains a property configured as NSAttachmentAttributeName with NSAttachmentCharacter in range; otherwise, NOfalse.

    Availability

    Available in iOS 9.0 and later.

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

    Declaration

    Swift

    struct NSAttributedStringEnumerationOptions : OptionSetType { 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.

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

    Declaration

    Swift

    enum NSUnderlineStyle : Int { case StyleNone case StyleSingle case StyleThick case StyleDouble static var PatternSolid: NSUnderlineStyle { get } case PatternDot case PatternDash case PatternDashDot case PatternDashDotDot case ByWord }

    Objective-C

    typedef enum NSUnderlineStyle : NSInteger { NSUnderlineStyleNone = 0x00, NSUnderlineStyleSingle = 0x01, NSUnderlineStyleThick = 0x02, NSUnderlineStyleDouble = 0x09, NSUnderlinePatternSolid = 0x0000, NSUnderlinePatternDot = 0x0100, NSUnderlinePatternDash = 0x0200, NSUnderlinePatternDashDot = 0x0300, NSUnderlinePatternDashDotDot = 0x0400, NSUnderlineByWord = 0x8000 } NSUnderlineStyle;

    Constants

    • StyleNone

      NSUnderlineStyleNone

      Do not draw a line.

      Available in iOS 6.0 and later.

    • StyleSingle

      NSUnderlineStyleSingle

      Draw a single line.

      Available in iOS 6.0 and later.

    • StyleThick

      NSUnderlineStyleThick

      Draw a thick line.

      Available in iOS 7.0 and later.

    • StyleDouble

      NSUnderlineStyleDouble

      Draw a double line.

      Available in iOS 7.0 and later.

    • PatternSolid

      NSUnderlinePatternSolid

      Draw a solid line.

      Available in iOS 7.0 and later.

    • PatternDot

      NSUnderlinePatternDot

      Draw a line of dots.

      Available in iOS 7.0 and later.

    • PatternDash

      NSUnderlinePatternDash

      Draw a line of dashes.

      Available in iOS 7.0 and later.

    • PatternDashDot

      NSUnderlinePatternDashDot

      Draw a line of alternating dashes and dots.

      Available in iOS 7.0 and later.

    • PatternDashDotDot

      NSUnderlinePatternDashDotDot

      Draw a line of alternating dashes and two dots.

      Available in iOS 7.0 and later.

    • ByWord

      NSUnderlineByWord

      Draw the line only underneath or through words, not whitespace.

      Available in iOS 7.0 and later.

    Discussion

    The style, pattern, and optionally by-word mask are OR'd together to produce the value for NSUnderlineStyleAttributeName and NSStrikethroughStyleAttributeName.

    Import Statement

    Objective-C

    @import UIKit;

    Swift

    import UIKit

    Availability

    Available in iOS 7.0 and later.

  • Options for specifying writing direction used with NSWritingDirectionAttributeName.

    Declaration

    Swift

    enum NSWritingDirectionFormatType : Int { case Embedding case Override }

    Objective-C

    typedef enum NSWritingDirectionFormatType : NSInteger { NSWritingDirectionEmbedding = (0 << 1), NSWritingDirectionOverride = (1 << 1) } NSWritingDirectionFormatType;

    Constants

    • Embedding

      NSWritingDirectionEmbedding

      Text is embedded in text with another writing direction. For example, an English quotation in the middle of an Arabic sentence could be marked as being embedded left-to-right text.

      Available in iOS 9.0 and later.

    • Override

      NSWritingDirectionOverride

      Enables character types with inherent directionality to be overridden when required for special cases, such as for part numbers made of mixed English, digits, and Hebrew letters to be written from right to left.

      Available in iOS 9.0 and later.

    Discussion

    You can use the logical OR operator to combine these constants with NSWritingDirectionLeftToRight or NSWritingDirectionRightToLeft when used with NSWritingDirectionAttributeName to specify formatting controls defined by the Unicode Bidirectional Algorithm in Unicode Standard Annex #9.

    Import Statement

    Objective-C

    @import UIKit;

    Swift

    import UIKit

    Availability

    Available in iOS 9.0 and later.

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

    Declaration

    Swift

    let NSAttachmentAttributeName: String let NSBackgroundColorAttributeName: String let NSBaselineOffsetAttributeName: String let NSExpansionAttributeName: String let NSFontAttributeName: String let NSForegroundColorAttributeName: String let NSKernAttributeName: String let NSLigatureAttributeName: String let NSLinkAttributeName: String let NSObliquenessAttributeName: String let NSParagraphStyleAttributeName: String let NSShadowAttributeName: String let NSStrikethroughColorAttributeName: String let NSStrikethroughStyleAttributeName: String let NSStrokeColorAttributeName: String let NSStrokeWidthAttributeName: String let NSTextEffectAttributeName: String let NSUnderlineColorAttributeName: String let NSUnderlineStyleAttributeName: String let NSVerticalGlyphFormAttributeName: String let NSWritingDirectionAttributeName: String

    Objective-C

    NSString *const NSAttachmentAttributeName; NSString *const NSBackgroundColorAttributeName; NSString *const NSBaselineOffsetAttributeName; NSString *const NSExpansionAttributeName; NSString *const NSFontAttributeName; NSString *const NSForegroundColorAttributeName; NSString *const NSKernAttributeName; NSString *const NSLigatureAttributeName; NSString *const NSLinkAttributeName; NSString *const NSObliquenessAttributeName; NSString *const NSParagraphStyleAttributeName; NSString *const NSShadowAttributeName; NSString *const NSStrikethroughColorAttributeName; NSString *const NSStrikethroughStyleAttributeName; NSString *const NSStrokeColorAttributeName; NSString *const NSStrokeWidthAttributeName; NSString *const NSTextEffectAttributeName; NSString *const NSUnderlineColorAttributeName; NSString *const NSUnderlineStyleAttributeName; NSString *const NSVerticalGlyphFormAttributeName; NSString *const NSWritingDirectionAttributeName;

    Constants

    • NSAttachmentAttributeName

      NSAttachmentAttributeName

      The value of this attribute is an NSTextAttachment object. The default value of this property is nil, indicating no attachment.

      Available in iOS 7.0 and later.

    • NSBackgroundColorAttributeName

      NSBackgroundColorAttributeName

      The value of this attribute is a UIColor object. Use this attribute to specify the color of the background area behind the text. If you do not specify this attribute, no background color is drawn.

      Available in iOS 6.0 and later.

    • NSBaselineOffsetAttributeName

      NSBaselineOffsetAttributeName

      The value of this attribute is an NSNumber object containing a floating point value indicating the character’s offset from the baseline, in points. The default value is 0.

      Available in iOS 7.0 and later.

    • NSExpansionAttributeName

      NSExpansionAttributeName

      The value of this attribute is an NSNumber object containing a floating point value indicating the log of the expansion factor to be applied to glyphs. The default value is 0, indicating no expansion.

      Available in iOS 7.0 and later.

    • NSFontAttributeName

      NSFontAttributeName

      The value of this attribute is a UIFont object. Use this attribute to change the font for a range of text. If you do not specify this attribute, the string uses a 12-point Helvetica(Neue) font by default.

      Available in iOS 6.0 and later.

    • NSForegroundColorAttributeName

      NSForegroundColorAttributeName

      The value of this attribute is a UIColor object. Use this attribute to specify the color of the text during rendering. If you do not specify this attribute, the text is rendered in black.

      Available in iOS 6.0 and later.

    • NSKernAttributeName

      NSKernAttributeName

      The value of this attribute is an NSNumber object containing a floating-point value. This value specifies the number of points by which to adjust kern-pair characters. Kerning prevents unwanted space from occurring between specific characters and depends on the font. The value 0 means kerning is disabled. The default value for this attribute is 0.

      Available in iOS 6.0 and later.

    • NSLigatureAttributeName

      NSLigatureAttributeName

      The value of this attribute is an NSNumber object containing an integer. Ligatures cause specific character combinations to be rendered using a single custom glyph that corresponds to those characters. The value 0 indicates no ligatures. The value 1 indicates the use of the default ligatures. The value 2 indicates the use of all ligatures. The default value for this attribute is 1. (Value 2 is unsupported on iOS.)

      Available in iOS 6.0 and later.

    • NSLinkAttributeName

      NSLinkAttributeName

      The value of this attribute is and NSURL object (preferred) or an NSString object. The default value of this property is nil, indicating no link.

      Available in iOS 7.0 and later.

    • NSObliquenessAttributeName

      NSObliquenessAttributeName

      The value of this attribute is an NSNumber object containing a floating point value indicating skew to be applied to glyphs. The default value is 0, indicating no skew.

      Available in iOS 7.0 and later.

    • NSParagraphStyleAttributeName

      NSParagraphStyleAttributeName

      The value of this attribute is an NSParagraphStyle object. Use this attribute to apply multiple attributes to a range of text. If you do not specify this attribute, the string uses the default paragraph attributes, as returned by the defaultParagraphStyle method of NSParagraphStyle.

      Available in iOS 6.0 and later.

    • NSShadowAttributeName

      NSShadowAttributeName

      The value of this attribute is an NSShadow object. The default value of this property is nil.

      Available in iOS 6.0 and later.

    • NSStrikethroughColorAttributeName

      NSStrikethroughColorAttributeName

      The value of this attribute is a UIColor object. The default value is nil, indicating same as foreground color.

      Available in iOS 7.0 and later.

    • NSStrikethroughStyleAttributeName

      NSStrikethroughStyleAttributeName

      The value of this attribute is an NSNumber object containing an integer. This value indicates whether the text has a line through it and corresponds to one of the constants described in NSUnderlineStyle. The default value for this attribute is NSUnderlineStyleNone.

      Available in iOS 6.0 and later.

    • NSStrokeColorAttributeName

      NSStrokeColorAttributeName

      The value of this parameter is a UIColor object. If it is not defined (which is the case by default), it is assumed to be the same as the value of NSForegroundColorAttributeName; otherwise, it describes the outline color. For more details, see Drawing attributed strings that are both filled and stroked.

      Available in iOS 6.0 and later.

    • NSStrokeWidthAttributeName

      NSStrokeWidthAttributeName

      The value of this attribute is an NSNumber object containing a floating-point value. This value represents the amount to change the stroke width and is specified as a percentage of the font point size. Specify 0 (the default) for no additional changes. Specify positive values to change the stroke width alone. Specify negative values to stroke and fill the text. For example, a typical value for outlined text would be 3.0.

      Available in iOS 6.0 and later.

    • NSTextEffectAttributeName

      NSTextEffectAttributeName

      The value of this attribute is an NSString object. Use this attribute to specify a text effect, such as NSTextEffectLetterpressStyle. The default value of this property is nil, indicating no text effect.

      Available in iOS 7.0 and later.

    • NSUnderlineColorAttributeName

      NSUnderlineColorAttributeName

      The value of this attribute is a UIColor object. The default value is nil, indicating same as foreground color.

      Available in iOS 7.0 and later.

    • NSUnderlineStyleAttributeName

      NSUnderlineStyleAttributeName

      The value of this attribute is an NSNumber object containing an integer. This value indicates whether the text is underlined and corresponds to one of the constants described in NSUnderlineStyle. The default value for this attribute is NSUnderlineStyleNone.

      Available in iOS 6.0 and later.

    • NSVerticalGlyphFormAttributeName

      NSVerticalGlyphFormAttributeName

      The value of this attribute is an NSNumber object containing an integer. The value 0 indicates horizontal text. The value 1 indicates vertical text. In iOS, horizontal text is always used and specifying a different value is undefined.

      Available in iOS 6.0 and later.

    • NSWritingDirectionAttributeName

      NSWritingDirectionAttributeName

      The value of this attribute is an NSArray object containing NSNumber objects representing the nested levels of writing direction overrides, in order from outermost to innermost.

      This attribute provides a means to override the default bidirectional text algorithm, equivalent to using the Unicode bidi control characters LRE, RLE, LRO, or RLO paired with PDF, but as a higher-level attribute. (See Unicode Standard Annex #9 for information about the Unicode bidi formatting codes.) The NSWritingDirectionAttributeName constant is a character-level attribute that provides a higher-level alternative to the inclusion of explicit bidirectional control characters in text. It is the NSAttributedString equivalent of the HTML markup using bdo element with the dir attribute.

      The values of the NSNumber objects should be 0, 1, 2, or 3, for LRE, RLE, LRO, or RLO respectively, and combinations of NSWritingDirectionLeftToRight and NSWritingDirectionRightToLeft with NSTextWritingDirectionEmbedding or NSTextWritingDirectionOverride, as shown in Table 1.

      Table 1Values of NSWritingDirectionAttributeName and equivalent markup

      Array NSNumber Values

      Unicode Control Characters

      Writing Direction Constants

      0

      LRE

      NSWritingDirectionLeftToRight | NSTextWritingDirectionEmbedding

      1

      RLE

      NSWritingDirectionRightToLeft | NSTextWritingDirectionEmbedding

      2

      LRO

      NSWritingDirectionLeftToRight | NSTextWritingDirectionOverride

      3

      RLO

      NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride

      Available in iOS 7.0 and later.

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

    Declaration

    Swift

    let NSPlainTextDocumentType: String let NSRTFTextDocumentType: String let NSRTFDTextDocumentType: String let NSHTMLTextDocumentType: String

    Objective-C

    NSString *NSPlainTextDocumentType; NSString *NSRTFTextDocumentType; NSString *NSRTFDTextDocumentType; NSString *NSHTMLTextDocumentType;

    Constants

    • NSPlainTextDocumentType

      NSPlainTextDocumentType

      Plain text document.

      Available in iOS 7.0 and later.

    • NSRTFTextDocumentType

      NSRTFTextDocumentType

      Rich text format document.

      Available in iOS 7.0 and later.

    • NSRTFDTextDocumentType

      NSRTFDTextDocumentType

      Rich text format with attachments document.

      Available in iOS 7.0 and later.

    • NSHTMLTextDocumentType

      NSHTMLTextDocumentType

      Hypertext Markup Language (HTML) document.

      Available in iOS 7.0 and later.

    Discussion

    See also NSDocumentTypeDocumentOption.

  • The init... methods can return a dictionary with the following document-wide attributes (attribute identifiers available on OS X v10.4 and later; use actual string value keys for earlier systems):

    Declaration

    Swift

    let NSBackgroundColorDocumentAttribute: String let NSCharacterEncodingDocumentAttribute: String let NSDefaultAttributesDocumentAttribute: String let NSDefaultTabIntervalDocumentAttribute: String let NSDocumentTypeDocumentAttribute: String let NSHyphenationFactorDocumentAttribute: String let NSPaperMarginDocumentAttribute: String let NSPaperSizeDocumentAttribute: String let NSReadOnlyDocumentAttribute: String let NSTextLayoutSectionsAttribute: String let NSViewModeDocumentAttribute: String let NSViewSizeDocumentAttribute: String let NSViewZoomDocumentAttribute: String

    Objective-C

    NSString *NSBackgroundColorDocumentAttribute; NSString *NSCharacterEncodingDocumentAttribute; NSString *const NSDefaultAttributesDocumentAttribute; NSString *NSDefaultTabIntervalDocumentAttribute; NSString *NSDocumentTypeDocumentAttribute; NSString *NSHyphenationFactorDocumentAttribute; NSString *const NSPaperMarginDocumentAttribute; NSString *NSPaperSizeDocumentAttribute; NSString *NSReadOnlyDocumentAttribute; NSString *const NSTextLayoutSectionsAttribute; NSString *NSViewModeDocumentAttribute; NSString *NSViewSizeDocumentAttribute; NSString *NSViewZoomDocumentAttribute;

    Constants

    • NSBackgroundColorDocumentAttribute

      NSBackgroundColorDocumentAttribute

      The value of this attribute is an NSColor object representing the document-wide page background color.

      OS X v10.3 and earlier string constant is @"BackgroundColor".

      For applications linked on versions prior to OS X v10.5, HTML import sets the NSBackgroundColorDocumentAttribute to [NSColor whiteColor] in cases in which the HTML does not specify a background color. For applications linked on OS X v10.5 and later, no NSBackgroundColorDocumentAttribute is set in these cases.

      Available in iOS 7.0 and later.

    • NSCharacterEncodingDocumentAttribute

      NSCharacterEncodingDocumentAttribute

      The value of this attribute is an NSNumber object containing integer specifying NSStringEncoding for the file; default for plain text is the default encoding. This key in options can specify the string encoding for reading the data. Upon return, the document attributes can contain the actual encoding used. For writing methods, this value is used for generating the plain text data.

      OS X v10.3 and earlier string constant is @"CharacterEncoding".

      Available in iOS 7.0 and later.

    • NSDefaultAttributesDocumentAttribute

      NSDefaultAttributesDocumentAttribute

      The value of this attribute is an NSDictionary object containing attributes to be applied to plain files. Used by reader methods. This key in options can specify the default attributes applied to the entire document contents. Upon return, the document attributes can contain this key indicating the actual attributes used. @"DefaultAttributes"

      Available in iOS 7.0 and later.

    • NSDefaultTabIntervalDocumentAttribute

      NSDefaultTabIntervalDocumentAttribute

      The value of this attribute is an NSNumber object containing a float. Represents the document-wide default tab stop interval.

      OS X v10.3 and earlier string constant is @"DefaultTabInterval".

      Available in iOS 7.0 and later.

    • NSDocumentTypeDocumentAttribute

      NSDocumentTypeDocumentAttribute

      The value of this attribute is one of the document types declared in Document Types. For reader methods, this key in options can specify the document type for interpreting the contents. Upon return, the document attributes can contain this key for indicating the actual format used to read the contents. For write methods, this key specifies the format for generating the data. @"DocumentType",

      Available in iOS 7.0 and later.

    • NSHyphenationFactorDocumentAttribute

      NSHyphenationFactorDocumentAttribute

      The value of this attribute is an NSNumber object containing a float; 0 = off, 1 = full hyphenation.

      OS X v10.3 and earlier string constant is @"HyphenationFactor".

      Available in iOS 7.0 and later.

    • NSPaperMarginDocumentAttribute

      NSPaperMarginDocumentAttribute

      The value of this attribute is an NSValue object containing UIEdgeInsets.

      OS X v10.3 and earlier string constant is @"PaperMargin".

      Available in iOS 7.0 and later.

    • NSPaperSizeDocumentAttribute

      NSPaperSizeDocumentAttribute

      The value of this attribute is an NSValue object containing NSSize.

      OS X v10.3 and earlier string constant is @"PaperSize".

      Available in iOS 7.0 and later.

    • NSReadOnlyDocumentAttribute

      NSReadOnlyDocumentAttribute

      The value of this attribute is an NSNumber object containing an integer. If missing or 0 or negative, not read only; 1 or more, read only.

      Note that this has nothing to do with the file system protection on the file, but instead can affect how the file should be displayed to the user.

      OS X v10.3 and earlier string constant is @"ReadOnly".

      Available in iOS 7.0 and later.

    • NSTextLayoutSectionsAttribute

      NSTextLayoutSectionsAttribute

      An NSArray containing NSDictionary objects, each dictionary describing a layout orientation section. The dictionary can have two attributes: NSTextLayoutSectionOrientation and NSTextLayoutSectionRange. When there is a gap between sections, it's assumed to have NSTextLayoutOrientationHorizontal.

      Available in iOS 7.0 and later.

    • NSViewModeDocumentAttribute

      NSViewModeDocumentAttribute

      The value of this attribute is an NSValue object containing an int; 0 = normal; 1 = page layout (use value of @"PaperSize").

      OS X v10.3 and earlier string constant is @"ViewMode".

      Available in iOS 7.0 and later.

    • NSViewSizeDocumentAttribute

      NSViewSizeDocumentAttribute

      The value of this attribute is an NSValue object containing NSSize.

      OS X v10.3 and earlier string constant is @"ViewSize".

      Available in iOS 7.0 and later.

    • NSViewZoomDocumentAttribute

      NSViewZoomDocumentAttribute

      The value of this attribute is an NSValue object containing a float. 100 = 100% zoom.

      OS X v10.3 and earlier string constant is @"ViewZoom".

      Available in iOS 7.0 and later.

  • These constants are used by NSTextLayoutSectionsAttribute.

    Declaration

    Swift

    let NSTextLayoutSectionOrientation: String let NSTextLayoutSectionRange: String

    Objective-C

    NSString *NSTextLayoutSectionOrientation; NSString *NSTextLayoutSectionRange;

    Constants

    • NSTextLayoutSectionOrientation

      NSTextLayoutSectionOrientation

      An NSNumber object containing an NSTextLayoutOrientation value. The default value is NSTextLayoutOrientationHorizontal.

      Available in iOS 7.0 and later.

    • NSTextLayoutSectionRange

      NSTextLayoutSectionRange

      An NSValue object containing an NSRange representing a character range. The default value is a range covering the entire string.

      Available in iOS 7.0 and later.

  • This constant is used by NSTextEffectAttributeName.

    Declaration

    Swift

    let NSTextEffectLetterpressStyle: String

    Objective-C

    NSString *const NSTextEffectLetterpressStyle;

    Constants

    • NSTextEffectLetterpressStyle

      NSTextEffectLetterpressStyle

      A graphical text effect giving glyphs the appearance of letterpress printing, in which type is pressed into the paper.

      Available in iOS 7.0 and later.

  • Options for specifying text writing direction used with NSWritingDirectionAttributeName.

    Use the NSWritingDirectionFormatType type instead.

    Declaration

    Swift

    enum NSTextWritingDirection : Int { case Embedding case Override }

    Objective-C

    typedef enum NSTextWritingDirection : NSInteger { NSTextWritingDirectionEmbedding = (0 << 1), NSTextWritingDirectionOverride = (1 << 1) } NSTextWritingDirection;

    Constants

    • Embedding

      NSTextWritingDirectionEmbedding

      Text is embedded in text with another writing direction. For example, an English quotation in the middle of an Arabic sentence could be marked as being embedded left-to-right text.

      Use the NSWritingDirectionEmbedding constant instead.

      Available in iOS 7.0 and later.

      Deprecated in iOS 9.0.

    • Override

      NSTextWritingDirectionOverride

      Enables character types with inherent directionality to be overridden when required for special cases, such as for part numbers made of mixed English, digits, and Hebrew letters to be written from right to left.

      Use the NSWritingDirectionOverride constant instead.

      Available in iOS 7.0 and later.

      Deprecated in iOS 9.0.

    Discussion

    You can use the logical OR operator to combine these constants with NSWritingDirectionLeftToRight or NSWritingDirectionRightToLeft when used with NSWritingDirectionAttributeName to specify formatting controls defined by the Unicode Bidirectional Algorithm in Unicode Standard Annex #9.

    Import Statement

    Objective-C

    @import UIKit;

    Swift

    import UIKit

    Availability

    Available in iOS 7.0 and later.