Trimming a TextField with AS 3.0

I was recently tasked with building a utility class that was designed to trim text off a TextField object; it accepts 3 argument. The initial TextField, desired width, and text to be concatenated to the existing TextField.

So in short I had to truncate due to the width argument, but also add the concatenated text, which was usually "..." signifying the text had been truncated. The code is below. I hope it helps you if you come up against a similar challenge. Good luck!

package com.mapquest.tilemap.util
{
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

public class TextFieldUtil
{

public function TextFieldUtil()
{}


/**
* Evaluates the textField and desired width param and sizes the TextField
*
* @returns sized TextField
* @param {number} desired width
* @param {TextField} text field to be edited
* @param {concatText} string to concat
*/
public function sizeTextField(textField:TextField, wid:Number, concatText:String):String
{
//size the text field and apply ellipses if it's text width is greater than desired width if (textField.textWidth > wid)
{

var initWidth:Number = textField.textWidth;
textField.appendText(concatText);
var concatWidth:Number = textField.textWidth - initWidth;
var activeWidth:Number = wid - concatWidth;

//change back to initial text textField.text = textField.text.substr(0, (textField.text.length - concatText.length))

//loop until size is right for (var i:int = 0; i < initWidth; i++)
{
if(textField.textWidth > activeWidth)
{

textField.text = textField.text.substr(0, (textField.text.length - 1));
}
else
{
textField.appendText(concatText);
break;
}
}
return textField.text;
}
else
{
return textField.text;
}
}
}
}

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
That for loop was continuing even after it concatenated the ellipses for me. I wrote a simple fix:

            //loop until size is right
            while (textField.textWidth &gt; activeWidth)
            {
                  textField.text = textField.text.substr(0, (textField.text.length - 1));
            }
            textField.appendText(concatText);
# Posted By Jimmie | 12/19/08 12:50 PM

Copyright Strikefish, Inc., 2005. All rights reserved.