Dynamic Textfield with custom font

I noticed a little bug in flash (at least, in my version), for which I wanted to share the fix.

The bug is as follows: you create a TextField, you change it’s text and then it looks empty.

Here’s the code that triggers the bug:

// create
var fmt = new TextFormat("Arial", 10, 0x000000); // make sure you embedded this
var label = new TextField( );
label.text = "Default text";
label.setTextFormat(fmt);
addChild(label);
// use
label.text = "Custom text";

You’d expect it to say “Custom text” but instead the label is empty. What worked for me is to first call the replace function and replace the first character with the first character. Like this:

// create
var fmt = new TextFormat("Arial", 10, 0x000000); // make sure you embedded this
var label = new TextField( );
label.text = "Default text";
label.setTextFormat(fmt);
label.replaceText(0, 1, "D");
addChild(label);
// use
label.text = "Custom text";

Now it will say “Custom text”. Speaking of bugs, there’s a related one, where your text doesn’t show up at all. This is when you assign the text after the textformat. So this will not work:

label.setTextFormat(fmt);
label.text = "Default text";

But this will:

label.text = "Default text";
label.setTextFormat(fmt);

Go figure.

Tags: , ,

Leave a Reply

Security Code: