» iTunes CoverFlow Flex 2 component with Away3D

Actionscript 3, Adobe Flex 2

Adding a Sprite as a child to a Flex Container

04.08.08 | 17 Comments

This is a problem i stumbled upon while trying to add a Sprite or MovieClip (or any DisplayObject) with actionscript to my DisplayList in Flex. I wanted to add a View3D (which is an extended Sprite) to my DisplayList in Flex. This just didn’t work because the Container Class overrides the addChild method:

1
2
var canvas:Canvas = new Canvas();
canvas.addChild(new Sprite());

According to the documentation i can add any type of DisplayObject as a child to any type of Container, but when you try to do that you’ll get this:

1
cannot convert flash.display::Sprite@54abdd1 to mx.core.IUIComponent

This is because Canvas, or more specific, Container tries to cast our newly created Sprite to a UIComponent, which is an Object lower in the Flex inheritance chain and casting to a more specific type is not allowed. This is one of the basic principles of Object Oriented Programming; you can’t cast any object to another object of a more specific type because you would add functionality to it by doing that.

I could just add my Sprite to the rawChildren property of my container like this:

1
2
var sprite:Sprite = new Sprite();
canvas.rawChildren.addChild(sprite);

But that’s not a really nice solution because the sprite wouldn’t behave like a Flex component and I would get my Sprite mixed up with all of the skinning Sprites and MovieClips of the container.

But I’m wandering off now, here’s the solution to our little Flex and Sprites and addChild problem:

1
2
3
4
var canvas:Canvas = new Canvas();
var uiComponent:UIComponent = new UIComponent();
canvas.addChild(uiComponent);
uiComponent.addChild(new Sprite());

Just use a UIComponent as a container for the Sprite. For as far as i know UIComponent is the only component that can actually add a Non-Flex-Component as a child.

17 Comments

have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

:

:



» iTunes CoverFlow Flex 2 component with Away3D