views:

1504

answers:

4

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?

+6  A: 

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.

Ross Henderson
Thanks, I knew it had to be something simple. I promise to study the docs more carefully next time, but sometimes it's easy to miss stuff that's inherited from base UI classes.
davr
+1  A: 

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.

Sophistifunk
+1  A: 

Here is the answer:

var textinp:TextInput = new TextInput();
someContainer.addChild(textinp);
textinp.percentWidth = 100;
Adrian Pirvulescu
+3  A: 

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;
Daniel Brockman