0

我对我在下面这段代码中看到的内容感到困惑。我有一个带有子按钮(我已指定其名称)的盒子容器。我编写了一个函数,试图按名称查找子按钮。但是,这并没有按预期工作 - 盒子的原因是 numChildren=0 出于某种原因,我希望它是 1,因为我在小时候添加了一个按钮。有人可以帮我理解我做错了什么吗?

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                   xmlns:s="library://ns.adobe.com/flex/spark" 
                   xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>



<mx:Box height="100%" width="100%" initialize="initializeApp();" name="MyBox">
    <fx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.controls.Button;
            import mx.core.FlexGlobals;

            public function initializeApp():void {
                var btn:Button = new Button();
                btn.name = "MyButton";
                addElement(btn);
                btn.addEventListener(MouseEvent.CLICK, clickCallback);
            }

            private function clickCallback(event:MouseEvent):void{
                var obj:DisplayObject = findChildByName(FlexGlobals.topLevelApplication as DisplayObjectContainer, "MyButton");
                if (obj==null){
                    Alert.show( "Not Found");
                }
                else{
                    Alert.show( "Found");
                }

            }

            private function findChildByName(parent:DisplayObjectContainer, name:String):DisplayObject{
                var childCount:Number = (parent==null) ? 0 : parent.numChildren;
                for (var i:Number=0;i<childCount;i++){
                    var child:DisplayObject = parent.getChildAt(i);
                    if (child is DisplayObjectContainer){
                        return findChildByName(child as DisplayObjectContainer, name);
                    }
                    else{
                        if (parent!=null && child == parent.getChildByName(name)){
                            return child;
                        }
                    }
                }
                return null;
            }



        ]]>

    </fx:Script>


</mx:Box>   
</s:WindowedApplication>

谢谢你。

4

2 回答 2

0

我的猜测是,该项目可能会添加到子对象中,在您的情况下是 Box,因为您的代码直接在框中,请指定 MyBox.addElement。或 FlxGobal.toplevelapp.addElement(

于 2013-10-31T19:47:42.587 回答
0

parent如果包含 DisplayObjectContainer,findChildByName 将提前返回。

if (child is DisplayObjectContainer){
    return findChildByName(child as DisplayObjectContainer, name);
}

这将返回找到的对象,如果在该容器中未找到对象,则返回 null。

更好的是,由于 Button 是 DisplayObjectContainer,您将尝试深入研究它而不检查对象本身是否是您正在寻找的对象。

在进一步挖掘之前,您需要先检查孩子是否是您的目标;然后,只有在找到孩子时才从递归检查中返回。就像是:

if (parent != null && child.name == name)   // Just check the name rather than getChildByName
{
    return child;
}
if (child is DisplayObjectContainer){
    var foundChild:DisplayObject = findChildByName(child as DisplayObjectContainer, name);
    if (foundChild) {
        return foundChild;
    }
}
于 2013-10-31T20:23:40.130 回答