Flex addChild()方法注意事項
更新時間:2009年08月03日 23:36:22 作者:
在Flex Application里,是不能直接用addChild添加Sprite,MovieClip等來自flash.display包里的類的。
譬如以下代碼就會報錯:
private function init():void { var sp:Sprite = new Sprite(); addChild(sp);}
TypeError: Error #1034: 強制轉(zhuǎn)換類型失敗:無法將 flash.display::Sprite@156b7b1 轉(zhuǎn)換為 mx.core.IUIComponent。
這是因為Application的addChild方法并非完全繼承自DisplayObjectContainer,
Application→LayoutContainer→Container →UIComponent→FlexSprite→Sprite
→DisplayObjectContainer
而是在Container那里被重寫了:
public override function addChild(child:DisplayObject):DisplayObject雖然參數(shù)child的類型是DisplayObject,但是它必須實現(xiàn)IUIComponent接口(所有Flex組件都實現(xiàn)了這一接口),才能添加。
如果要在Application里添加Sprite,可以先把它裝進一個UIComponent,然后再添加這個UIComponent:
官方的說法:
* <p><b>Note: </b>While the <code>child</code> argument to the method
* is specified as of type DisplayObject, the argument must implement
* the IUIComponent interface to be added as a child of a container.
* All Flex components implement this interface.</p>
例子:
import mx.core.UIComponent;private function init():void {
var sp:Sprite = new Sprite();
var uc:UIComponent = new UIComponent();
uc.addChild(sp); addChild(uc);
}
private function init():void { var sp:Sprite = new Sprite(); addChild(sp);}
復(fù)制代碼 代碼如下:
TypeError: Error #1034: 強制轉(zhuǎn)換類型失敗:無法將 flash.display::Sprite@156b7b1 轉(zhuǎn)換為 mx.core.IUIComponent。
這是因為Application的addChild方法并非完全繼承自DisplayObjectContainer,
Application→LayoutContainer→Container →UIComponent→FlexSprite→Sprite
→DisplayObjectContainer
而是在Container那里被重寫了:
復(fù)制代碼 代碼如下:
public override function addChild(child:DisplayObject):DisplayObject
如果要在Application里添加Sprite,可以先把它裝進一個UIComponent,然后再添加這個UIComponent:
官方的說法:
* <p><b>Note: </b>While the <code>child</code> argument to the method
* is specified as of type DisplayObject, the argument must implement
* the IUIComponent interface to be added as a child of a container.
* All Flex components implement this interface.</p>
例子:
復(fù)制代碼 代碼如下:
import mx.core.UIComponent;private function init():void {
var sp:Sprite = new Sprite();
var uc:UIComponent = new UIComponent();
uc.addChild(sp); addChild(uc);
}
相關(guān)文章
如何定義一個getter和seter設(shè)置的屬性可以被綁定
Define private variable for maxFontSize.2009-05-05
Flex 動態(tài)綁定BindingUtils.bindProperty
Flex 動態(tài)綁定BindingUtils.bindProperty實現(xiàn)代碼。2009-06-06

