Recipe 8.16 Formatting Existing Text

8.16.1 Problem

You want to format the existing text in a text field.

8.16.2 Solution

Pass a TextFormat object to the TextField.setTextFormat( ) method.

8.16.3 Discussion

A text field allows minimal control over the formatting of the text it displays, such as by setting the htmlText property. Although you can set the color of the entire contents of the text field using the textColor property, for example, the TextField class doesn't offer precise control over character formatting. However, the TextFormat class is a "helper" class; TextFormat objects can format the text displayed in text fields.

The first step in formatting text is to create a TextFormat object using the constructor method:

myTextFormat = new TextFormat(  );

Next, assign values to the TextFormat object's properties as you desire:

myTextFormat.align = "center";  // Center-align the text.
myTextFormat.bold = true;       // Bold the text.
myTextFormat.color = 0xFFFF00;  // Make the text yellow.
myTextFormat.blockIndent = 5;   // Adjust the margin by five pixels.

You can apply text formatting to the existing text for an entire text field by passing a TextFormat object to the text field's setTextFormat( ) method:


When you invoke the setTextFormat( ) method in this way, the formatting from the TextFormat object is applied to the text already assigned to the text field. The formatting does not apply to any text assigned to the text field after the setTextFormat( ) method is invoked. If additional text is entered by the user, the original text retains its applied formatting, but the inserted text does not have any special formatting applied to it. All formatting is removed if the text value is modified by appending a value by way of ActionScript.

myTextField.text = "this is some text";
myTextField.setTextFormat(myTextFormat); // Formatting applied
myTextField.text = "this is other text"; // No formatting applied
myTextField.setTextFormat(myTextFormat); // Formatting reapplied
myTextField.text += "appended text";     // Formatting removed

If you make changes to the TextFormat object, you should reapply the formatting to the text field by passing the modified object to the setTextFormat( ) method. Otherwise, the changes are not automatically displayed.

8.16.4 See Also

Recipe 8.10 explains how to use HTML-formatted text, Recipe 8.17 explains how to apply formatting to new text rather than existing text, and Recipe 8.18 applies formatting to individual characters rather than an entire field.

    Part I: Local Recipes
    Part II: Remote Recipes