Skip to main content
Inspiring
August 16, 2013
Answered

AS3: How to get height of a dynamically created text field

  • August 16, 2013
  • 1 reply
  • 1465 views

I am importing text from an XML file and want the lines of text to display in separate text fields beneath each other. How can I set the y value of each succeeding text field so that there is some space (40 pixels or so) from the above field, regardless of the length of the text? Here is my current code. Any help would be greatly appreciated.

var textArray:Array = new Array();
for (var i:int; i <myXML.TOPIC[0].QUERY.length(); i++) {
var textField:TextField = new TextField();
textField.htmlText = myXML.TOPIC[0].QUERY.QUESTION;
textField.x = 100;
//below is my problem....I want the y value to be based on the height of all the previous text fields that have been created

textField.y = 100+(40*i);
textField.border = true;
textField.width = 800;
textField.textColor = 0x000000;
textField.multiline = true;
textField.wordWrap = true;
textField.selectable = false;
addChild(textField);
textArray.push(textField);
}

This topic has been closed for replies.
Correct answer Ned Murphy

Keep a variable separate from the loop that you update in the loop to keep track of the current y value.  The current y value would be updated to the previous value plus the height of the newest textfield after it has been filled with text.

1 reply

Ned Murphy
Ned MurphyCorrect answer
Legend
August 16, 2013

Keep a variable separate from the loop that you update in the loop to keep track of the current y value.  The current y value would be updated to the previous value plus the height of the newest textfield after it has been filled with text.

Inspiring
August 17, 2013

Thanks, Ned! Can I borrow some of the brain cell you are not using?

Since it might help others, below is the code I added. There may be a more elegant way to code it, but it works!

for (var j:int = 0; j <myXML.TOPIC[0].QUERY.length(); j++) {

  if (j == 0) {

   textArray.y = 100;

  }

  else {

  textArray.y = textArray[j-1].y+textArray[j-1].height+5;

}}

Ned Murphy
Legend
August 17, 2013

There's nothing wrong with the approach you took... retain it as is.  What I was suggesting is basically the same, just a slightly different angle that doesn't need the conditional....

var currentY:Number = 100;

for (var j:int = 0; j <myXML.TOPIC[0].QUERY.length(); j++) {

 

   textArray.y =  currentY;

    // text gets added somewhere in here

    currentY =  currentY+textArray.height+5;

}