Marc Hughes

I am a developer from a bit west of Boston.

Programatically add constraints through Actionscript

06 May 2007

Flex Builder has that great "Constraints" UI that allows you to anchor components to their parent that I'm sure everyone has used.

But what happens if you create an object in actionscript and then you want add constraints to it? There is no "top" property you can set to anchor the component to the top. It turns out the constraint system is entirely based on Flex's style system and can be used as follows:

var someComponent:SomeComponent = new SomeComponent();
var style:CSSStyleDeclaration = new CSSStyleDeclaration();
style.setStyle("top", 0);
style.setStyle("horizontalCenter", 0);
someComponent.styleDeclaration = style;

And BAMN, someComponent will be anchored to the top, center of it's parent (assuming it's parent is a container that supports anchors.) Available style selectors are:

  1. top
  2. left
  3. right
  4. bottom
  5. horizontalCenter
  6. verticalCenter
You could also specify the styles in a css sheet, or by adding them to an already existing style.


As a commenter has posted you can also use the setStyle method in addition to the various other methods I mentioned. So the following would also work: