davr
davr

Reputation: 19147

Set Flex component width to 100% at runtime?

If I am creating say a input field through MXML, I can set the width to 100%. But I cannot seem to do this at runtime through ActionScript.

This works:

<mx:TextInput ... width="100%" />

This wont compile, says width is a number, not a string:

var textinp:TextInput = new TextInput();
someContainer.addChild(textinp);
textinp.width = "100%"

How can I set 100% as the size on a component created at runtime via ActionScript?

Upvotes: 9

Views: 10902

Answers (4)

Daniel Brockman
Daniel Brockman

Reputation: 19290

If you later want to switch back to pixel-based widths for the same component, here’s what you have to do:

textinp.percentWidth = NaN;

Upvotes: 10

Ross Henderson
Ross Henderson

Reputation: 1779

You just need to use the percentWidth attribute, instead of the width attribute.

So, the third line in your code would be :

textinp.percentWidth = 100;

This tripped me up for awhile, too.

Upvotes: 23

Adrian Pirvulescu
Adrian Pirvulescu

Reputation: 4340

Here is the answer:

var textinp:TextInput = new TextInput();
someContainer.addChild(textinp);
textinp.percentWidth = 100;

Upvotes: 1

Sophistifunk
Sophistifunk

Reputation: 5042

The above answer is correct, but I can't comment on it coz I'm too new to SO.

When you want to add this functionality to a custom component, you can do something like this:

[PercentProxy("percentMultiplier")]
public function set multiplier(value:Number):void
{
  _multiplier = value;
  invalidSomethingOrDoSomething();
}

public function set percentMultiplier(value:Number):void
{
  multiplier = value / 100;
}

Of course, when you're doing it for width, the Container subclasses are looking for percentWidth, and don't inspect the metada, so don't call it widthInPercent or something, even though you can.

Upvotes: 3

Related Questions