Preserve textformat when changing text in Flash / AS3

April 09, 2013 Actionscript AS3 Troubleshooting Flash Snippet
Notice that the textformat that was defined for your TextField mysteriously disappears when you just change the text? A bit annoying, but the reason is that the format is not applied to the TextField itself but the text in it. Replace the text and you replace the textformat as well.

This can however be solved by storing away the textformat before you change the text and then re-apply it like this:

// Save the old textformat before changing the text
var textFormat:TextFormat = buttonText.getTextFormat();

// Change the text
buttonText.text = "New text goes here";

// Re-apply the textformat
buttonText.setTextFormat(textFormat);

Related posts: