Tuesday 12 October 2010

How to count number of lines in a TextField

I was facing this dilema to correct a game were in the textfields the text can have 1, 2 or 3 lines. Depending on the number of lines I wanted to center the text vertically so that when it had only 1 line, it would append a new line "\n" before the text.

This only applies to normal dynamic textfields, not TFL. These have their own methods to center text both horizontally and vertically... much easier.

There's a property called numLines, but this only states that the chosen TextField will have an x number of lines that you specify, you can't use it to return the number of text lines that you see.

So you have to make another type of calculation, and the textfield must be multiline.

var myHeight:Number = myText.height; //store the height of the textfield
myText.multiline = true; //don't need to do this, if it is in the properties panel
myText.wordWrap = true; //same as above

myText.height = myHeight; // here is the trick, try removing this line
trace("DYNAMIC TEXTFIELD HAVE "+myText.maxScrollV+" LINES");

Cheers

5 comments:

  1. @Sammy... Glad it helped :)

    ReplyDelete
  2. @Ivan - Yes you can, but have to be carefull how to use it. It seems that this a case where the order of lines matter. So .multiline and .wordwrap properties must come before the .text property... The solution I presented works without this... but it's more complicated. Thanks anyway! :)

    ReplyDelete
  3. Thanks it helped.

    ReplyDelete