fl.controls.Button width issues…

So recently I’ve had a few problems with the component button in Flash. Essentially I wanted the button to resize automatically to fit to the text inside and was amazed to find out (after all these years) that it doesn’t have this method! Crazy.

Anyway I managed to find a class by a dude called Matt Sweetman (http://webroo.org/2009/05/11/auto-size-button-for-flash-cs-components/) which extends the Button and adds the auto-size to it. All well and good, except that it’s still a bitch trying to align them, because we don’t know the width of the buttons when we’re cycling through them in a “for” loop. The drawLayout() method isn’t fired instantly so the alignment can’t be achieved.

The solution I came up with was to use Matt Sweetman’s class and add a dispatchEvent to it once the auto-size has been performed. You will need to set up a variable to catch the amount of buttons that have finished with their drawLayout() methods. Once this has been done simply call getRealWidth() [I’ve added this as the _width property is protected and the width property isn’t accurate] on each one and then you can align them correctly. Hopefully someone will find this useful.

Here’s the amended class :

package components
{
import fl.controls.Button;
import fl.core.InvalidationType;
import flash.events.Event;

import flash.text.TextFieldAutoSize;

public class AutoSizeButton extends Button
{
// Original class written by Matt Sweetman     - http://webroo.org/
// Ammended by Dan Sanderson                 - http://pldm.co.uk

public static const BUTTON_READY : String = "Button Ready";

public function AutoSizeButton()
{
super();
}

protected var _autoSize:Boolean = true;

/**
* Whether auto sizing is turned on. Default is true.
*/

public function get autoSize():Boolean
{
return _autoSize;
}

public function set autoSize(value:Boolean):void
{
_autoSize = value;
textField.autoSize = _autoSize ? TextFieldAutoSize.LEFT
: TextFieldAutoSize.NONE;
invalidate(InvalidationType.SIZE);
}

override protected function drawLayout():void
{
if (autoSize)
{
// Set the component width by calculating
// text & padding widths
var txtPad:Number = Number(getStyleValue("textPadding"));
_width = (textField.textWidth + 4) + (2 * txtPad);
}

super.drawLayout();

// Firing this so that we can align the buttons.
dispatchEvent(new Event(AutoSizeButton.BUTTON_READY));
}

public function getRealWidth() : Number
{
return _width;
}

}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s