views:

1834

answers:

2

In Flex 3.2, I'm creating a UITextField, then measuring text that I'm about to assign to that field's text property. I then use those metrics to set the size of the field. However, the calculated width is not wide enough to accommodate the text. Is there a different order to achieve proper measurement or am I seeing a problem with the measureText() function? How can I get accurate results?

// UITextField's default size appears to be 100x100
// Measure the text then set width and height
var tf:UITextFormat = uiTextField.getUITextFormat();
var tlm:TextLineMetrics = tf.measureText(this.labelText);

// Text within the field is clipped unless 'padding' is added to the size
// Flex Documentation specifies there is a 2 px gutter on each side, so
// the expected padding would be 4 px.  However, clipping occurs, for 
// "Hello, World" up to 9 px.
uiTextField.width = tlm.width + 9; 
uiTextField.height = tlm.height + 4;
uiTextField.border = true;
uiTextField.name = "uiTextField";      
uiTextField.text = this.labelText;
+2  A: 

I've had all sorts of trouble with measuring the width and heights of textFields before. It looks like you just want to autosize the textField. Have you tried:

uiTextField.autoSize = TextFieldAutoSize.LEFT;

???

James Hay
Thanks, that stops the clipping without the need for certain measurements, and I can use the uiTextField's width later on to draw and place graphics appropriately. I'm going to leave this question as unanswered because the inaccurate width from measureText() still bothers me.
Michael Prescott
A: 

Unfortunately, Flex often gets very confused when it tries to dynamically get a textWidth. Even worse, it is difficult to reliably catch the error and have Flex update itself correctly. The best options I've found:

  1. Hack it manually -- mostly reliable and has the benefit of happening before everything has finished rendering: mx.controls.Text hack AS3 describes a way to do this.
  2. Use callLater or an FlexEvent.CREATION_COMPLETE event listener -- this is less reliable, but it is definitely not a hack
  3. Use setTimeout with a delay of less than 1/10 a second ( I like 25-50 milliseconds ) -- I have found this the most reliable, but it may cause a small "blip" on the screen (generally not terribly noticeable for short code).
Christopher W. Allen-Poole