Getting Flex UI components all the same width or height

I’ve been doing a lot of work using localization lately and as part of this I’ve had to consider the fact that words in one language are not usually the same lengths as their translations in another.  Because of this I’ve increasingly been relying on the size to fit content ability of labels, buttons etc. in side of Flex.   Now that is all well and good except for when you want a set of buttons to all be the same width or some labels and controls to all line up and be the same width.    You need some way of telling all of the components in the set to re-size to the largest size of any of the components.  I’ve written a very little function to do just that.This function works on any component with a width property (It’s intended for UI components)  here is the code:

/** Takes a series of UI components, sets all widths to the widest width */
private function setToGreatestWidth(...args):void{
   args.sortOn(['width'], Array.NUMERIC | Array.DESCENDING);
   for(var i:uint = 0; i < args.length; i++) {
        args[i].width = args[0].width;
   }
}

I would typically call it like this in the on creation complete handler for my UI container:

private function onCreationComplete():void{
   setToGreatestWidth(this.button_upload,this.button_cancel);
   setToGreatestWidth(this.label1,this.label2,this.label3,this.label4);
}

By calling it from the creation complete handler you ensure that all localization strings have loaded and layout has already occurred and therefore the controls have all adjusted to their content width.

(I’m not sure there may be  a really cool and efficient way to accomplish this in the new Spark architecture but I’m working on some older 3.4 code so I don’t have access to those components anyway.)

Advertisement

Leave a Comment

Filed under Adobe, AIR (Adobe Integrated Runtime), Flash, Flex

Leave a Reply

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

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

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