Flash: TextField.htmlText and Automatic Line Breaks

Problem :: When you deal with TextField.htmlText don’t append any html strings directly to htmlText property of TextField. Because the TextField appends “<br>” tag automatically before it appends any html string to htmlText property, it will set your string automatically in next line instead of the current line. This mistake is done to save memory as we don’t have to create a temporary string.

Example :

textField.htmlText = “”;                 //clear any previous texts

for(var i:uint = 0; i < 3; i++)
{
var str:String = “”;
str += “Hello World”;
str += “<br>”;                    //As you’re thinking of breaking line from here
textField.htmlText += str;
}

//output would be something like following ::
Hello World
//This line break because of <br> tag
Hello World         //This is an automatic line break
//This line break because of <br> tag
Hello World         //This is an automatic line break
//output finished

Possible Solution :: Create an empty string and append all the html strings to this string. When the final string is ready, assign this string to htmlText property of TextField. This will not create any unnecessary line breaks inside TextField.

Example :

textField.htmlText = “”;                 //clear any previous texts
var htmlStr:String = “”;                  //Temporary empty string

for(var i:uint = 0; i < 3; i++)
{
var str:String = “”;
str += “Hello World”;
str += “<br>”;                    //As you’re thinking of breaking line from here
htmlStr += str;
}

textField.htmlText = htmlStr;

//output would be something like following ::
Hello World
Hello World
Hello World
//output finished

Hope this would prevent someone from mistakes which I did 🙁