Flex textheight workaround

Tagged:  

I spent over an hour banging my head against the wall on this one, so I'm going to post my solution.

If you have a Flex Text component, text.textHeight gives you an incorrect result in certain situations. This is a known bug, I see it listed
http://bugs.adobe.com/jira/browse/SDK-14792 and
http://www.mail-archive.com/flexcoders@yahoogroups.com/msg63011.html.

To paraphrase the problem, basically if you create a Text component, give it a width, and a bunch of text that will cause wrapping, getting textHeight will return something about 40-50 pixels too tall.

The workaround is such:

var text:Text = new Text();
text.text = ... some text that wraps given the width.
text.explicitWidth = ... the desired width of your text component.
text.validateNow();
/* At this point, textHeight is still incorrect, 
but now at least text.measuredHeight will give us a correct result. */
text.setActualSize(itemLabel.width, text.measuredHeight + 3);
text.validateSize();

The text.measuredHeight after the validateNow will be the correct Text height. This isn't exactly the same as the textHeight, to find that out precisely you would subtract UITextField.mx_internal::TEXT_HEIGHT_PADDING (which is the constant 4).

The reason why I say text.measuredHeight + 3, is because if I don't, if you select the text and drag down, you can make the textfield scroll even though it shouldn't.

Hope this helps someone.

Had this issue and went in a slightly different direction on how to fix it today:
http://thoughts.novaleaf.com/johanm/2008/12/03/flex-solution-to-automati...
Would like your feedback as to how viable it is for others. (See previous post for more info and the link-back to your blog.)

//Johan Munkestam