Set button width to text width in flex

Posted on Jul 14, 2010

Well, I have been working on a very interesting project recently, really stretching flex to the limits

I needed to set buttons, linkButtons, Labels and more components width to the width of the text inside them.

Usually, flex does it for you, but the width was hardcoded in compile time and I needed to change the text and the width in runtime and resize the component according to that.

I have written a nifty helper function for that.

Here it is:

[as3]

/**

  • This function will accept the text and the UI component and set the width to the width of the text

  • @param text the text or label of the component

  • @param container the container casted to a UIComponent

*/

public static function measureTextWidthAndResizeComponent(text:String, container:UIComponent):void

{

var _measuredWidth:Number = 0;

var _paddingLeft:uint = 0;

var _paddingRight:uint = 0;

var _horizontalGap:uint = 0;

var _addedToWidth:int;

if(text == null)

return;

if(text.length <= 1)

return;

_paddingLeft = container.getStyle(“paddingLeft”);

_paddingRight = container.getStyle(“paddingRight”);

_horizontalGap = container.getStyle(“horizontalGap”);

_addedToWidth = int(_horizontalGap + _paddingLeft + _paddingRight);

var lineMetrics:TextLineMetrics = container.measureText(text);

_measuredWidth = (lineMetrics.width + _addedToWidth);

container.width = _measuredWidth;

}

[/as3]

That’s it, enjoy!