Sunday, July 20, 2008

Centering multiline text fields in AS3?

This seems to be a regression-without-cure between AS2 and AS3. In AS2 I could write:
txt.htmlText="blah, blah, blah";

and each line in that text field would be centered.

In AS3 I am writing:
txt.htmlText="blah, blah, blah";

but it ends up left-aligned.
The bigger problem is that this is the documented behaviour: if wordWrap is set then align will not center text.

So, how do I center a multi-line text field?!!

(Time passes.)

I cannot believe there is nothing on the web about this. Have all the flash developers in the world stopped centering their text, or am I missing something obvious?

(More time passes.)

OK, after some trial-and-error I have a workaround, which sucks but will get the job done:

CopyA.htmlText='<body><p align="center">blah, blah, blah</p></body>';

Why do I say this sucks? Because I cannot (easily) apply it afterwards: I will need to get the current htmlText contents, detect the body tag and insert after it; and a corresponding closing-P tag at the end.

But in this application the text string comes from a DB and is allowed to contain HTML tags. What if it too already has a P tag? Will I get an extra blank line? Are P tags allowed to be nested?
(Well, I just tried, and it seems fine still, and if the inner P tag has an align that is the one that gets applied. So all good there.)

UPDATE: I discovered I can also write this:
CopyA.htmlText='<p align="center"><body>blah, blah, blah</body></p>';
That is dubious, and I wonder if it is future-proof, or if I am exploiting a bug? But it is obviously far easier, as it saves me having to do any parsing - I can just wrap whatever the existing htmlText is:
copyA.htmlText='<p align="center">'+copyA.htmlText+'</p>';