一般來說,actionscript3的view component體系下,按照Composition模式,只要把一個視覺元素addChild到它的container下就行了。但是在flex或air application下,按照這個方法添加一個sprite就會報錯(鬱悶的),會出一個錯誤,大概意思是sprite 不能轉換成UIComponent。很明顯,addChild在某個派生環節中被重寫了。馬上打開language reference看看,果然addChild defined by Container,Container何許人也?
Container UIComponent FlexSprite Sprite DisplayObjectContainer InteractiveObject DisplayObject EventDispatcher Object
Container是mx.containers.*下所有類的父類,說白了,是flex容器類的基類。reference上的解釋是:child:DisplayObject
— The DisplayObject to add as a child of this Container. It must implement the IUIComponent interface.
呵呵,說實話真有點誤導在裏邊呢。
於是解決方法也明瞭了:
- var ui:UIComponent = new UIComponent();
- ui.addChild(yourSprite);
- this.addChild(ui);