9

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?

davr
  • 18,877
  • 17
  • 76
  • 99

4 Answers4

23

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.

davr
  • 18,877
  • 17
  • 76
  • 99
Ross Henderson
  • 1,779
  • 16
  • 23
  • 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 Jun 25 '09 at 21:58
10

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
  • 18,826
  • 3
  • 29
  • 40
3

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
  • 4,742
  • 4
  • 28
  • 37
1

Here is the answer:

var textinp:TextInput = new TextInput();
someContainer.addChild(textinp);
textinp.percentWidth = 100;
Adrian Pirvulescu
  • 4,308
  • 3
  • 30
  • 47