Flex addChild()方法注意事项

在Flex Application里,是不能直接用addChild添加Sprite,MovieClip等来自flash.display包里的类的。

譬如以下代码就会报错:
private function init():void { var sp:Sprite = new Sprite(); addChild(sp);}
复制代码 代码如下:

TypeError: Error #1034: 强制转换类型失败:无法将 flash.display::Sprite@156b7b1 转换为 mx.core.IUIComponent。

这是因为Application的addChild方法并非完全继承自DisplayObjectContainer,
Application→LayoutContainer→Container →UIComponent→FlexSprite→Sprite
→DisplayObjectContainer
而是在Container那里被重写了:
复制代码 代码如下:

public override function addChild(child:DisplayObject):DisplayObject
虽然参数child的类型是DisplayObject,但是它必须实现IUIComponent接口(所有Flex组件都实现了这一接口),才能添加。
如果要在Application里添加Sprite,可以先把它装进一个UIComponent,然后再添加这个UIComponent:
官方的说法:
*

Note: While the child 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.


例子:
复制代码 代码如下:

import mx.core.UIComponent;private function init():void {
var sp:Sprite = new Sprite();
var uc:UIComponent = new UIComponent();
uc.addChild(sp); addChild(uc);
}

以上就是Flex addChild()方法注意事项的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Flex