You create an NSAttributedString
object in a number of different ways:
You can create a new string with the initWithString:
, initWithString:attributes:
, or initWithAttributedString:
method. These methods initialize an attributed string with data you provide, as illustrated in the following example:
NSFont *font = [NSFont fontWithName:@"Palatino-Roman" size:14.0]; |
NSDictionary *attrsDictionary = |
[NSDictionary dictionaryWithObject:font |
forKey:NSFontAttributeName]; |
NSAttributedString *attrString = |
[[NSAttributedString alloc] initWithString:@"strigil" |
attributes:attrsDictionary]; |
For a list of attributes provided by the Application Kit framework see the Constants section in NSAttributedString Additions.
The attribute values assigned to an attributed string become the property of that string, and should not be modified “behind the attributed string” by other objects. Doing so can render inconsistent the attributed string’s internal state. Always use NSMutableAttributedString
’s setAttributes:range:
and related methods to change attribute values. See “Changing an Attributed String” for more details.
You can can create an attributed string from rich text (RTF) or rich text with attachments (RTFD) data using the initialization methods, initWithRTF:documentAttributes:
, initWithRTFD:documentAttributes:
, and initWithRTFDFileWrapper:documentAttributes:
, as illustrated in the following example:
NSData *rtfData = ...; // assume rtfData is an NSData object containing valid RTF data |
NSDictionary *docAttributes; |
NSSize paperSize; |
NSAttributedString *attrString; |
if ((attrString = [[NSAttributedString alloc] |
initWithRTF: data documentAttributes: &docAttributes])) { |
NSValue *value = [docAttrs objectForKey:@"PaperSize"]; |
paperSize = [value sizeValue]; |
// implementation continues... |
You can can create an attributed string from HTML data using the initialization methods initWithHTML:documentAttributes:
and initWithHTML:baseURL:documentAttributes:
. The methods return text attributes defined by the HTML as the attributes of the string. They return document-level attributes defined by the HTML, such as paper and margin sizes, by reference to an NSDictionary
object, as described in “RTF Files and Attributed Strings.” The methods translate HTML as well as possible into structures of the Cocoa text system, but the Application Kit does not provide complete, true rendering of arbitrary HTML.
© 1997, 2007 Apple Inc. All Rights Reserved. (Last updated: 2007-06-04)