Frustrating Flex problems solved #2 – addChild

this.addChild(new Sprite())

looks simple enough doesn’t it? especially if you’ve been working solely in Flash AS3. But if you try this line within a Flex component, you’ll receive the error: ‘Type Coercion failed: cannot convert flash.display::Sprite@86cc0e1 to mx.core.IUIComponent.’

This is because Flex components implement a different addChild method. although addChild is described as accepting a DisplayObject as a parameter, this DisplayObject must implement the IUIComponent interface.

How to add a sprite then? You can either:

specify a UIComponent. eg:

this.addChild(new UIComponent())

This sort of works in this case as UIComponent implements the Sprite. However the additional implementation of UIComponent may at best be unnecessary and at worst cause problems with your code. Also, this alternative won’t work in some cases, say if for some reason you wanted to add a MovieClip.

so an alternative is that you can add your child to the component’s rawChildren, a property which contains a list of ALL of the container’s children – not just the children that the container wants you to know about! (this.numChildren<=this.rawChildren.numChildren) see flex help for more info on this. this alternative looks like: this.rawChildren.addChild(new Sprite())

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

Tagged with: , ,
Posted in Flex
3 comments on “Frustrating Flex problems solved #2 – addChild
  1. Thanks for the solution, been struggling with this a bit.

  2. Glad to have been of help, Alchemist Dan!

  3. Matt says:

    Amazing! I was at my wits end. Thanks a bunch!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: