Flex 4 UIComponent width and height remains zero after addChild is called
I have a component ObjectHolder
which extends UIComponent
that holds many children UIComponents
. However, after using addChild()
to add these children to ObjectHolder
, its width and height remain zero. Is it possible for the UIComponent
to automatically expand to the size of its containing children components?
public class ObjectHolder extends UIComponent
{
public function ObjectHolder()
{
var c1:UIComponent = new UIComponent();
c1.graphics.beginFill( 0xffffff );
c1.graphics.draw开发者_如何学GoRect(0, 0, 100, 100);
addChild( c1 );
trace( this.width ); // Displays zero
}
}
To change the component's size you should implement measure()
method. But you should also follow other recommendations on creating custom components. In your case you should create and add child component in createChildren()
method.
Is it possible for the UIComponent to automatically expand to the size of its containing children components?
The formal answer is no. A component is never responsible for setting it's own height and width values; it is only responsible for sizing and positioning it's children based on the values set by that component's parent.
If you implement a measure() method in your component, you can use it to set the measuredWidth and measuredHeight of your component. This will, in essence, be a suggestion that you provide to your parent's container on what is the ideal size you need to position and size all your child elements properly. Your own components should be sized and positioned in updateDisplayList() based on the unscaledWidth and unscaledHeight values passed in.
Most of the time the Flex default containers will honor these sizing values; although there are situations where they will not be. For example, if the size the child container needs is more than the size of the parent.
精彩评论