flash.display 패키지 내에는 DisplayObjectContainer 라는 Class가 있다.

위의 Class는 UIComponent를 상속받는 Container 들에게도 해당 속성이 적용 받는데, 포스트에 적을 것은 게중에 해당 컨테이너에 속한 컴포넌트들의 속한 순서(? addChild 된 순서)를 바꾸는 것을 알아 본다.

일단 DisplayObjectContainer에는 Canvas나 혹은 다른 Container 들에게 볼 수 있는 몇가지 Method가 있다.


setChildIndex(child:DisplayObject, index:int):void
Changes the position of an existing child in the display object container.

swapChildren(child1:DisplayObject, child2:DisplayObject):void
Swaps the z-order (front-to-back order) of the two specified child objects.

removeChild(child:DisplayObject):DisplayObject
Removes the specified child DisplayObject instance from the child list of the DisplayObjectContainer instance.

getChildIndex(child:DisplayObject):int
Returns the index position of a child DisplayObject instance.


이것 이외에도 여러가지 유사한 기능을 하는 Method들이 있다. Parameter만 다르고 기능은 거의 같으니 일단 이정도로 소개하도록 하고

 DisplayObjectContainer라는 Class 명에서 뜻하는 것처럼 다른 컴포넌트들을 담는 녀석들은 여러 자식 클래스(컨테이너에 addChild 시키는 컴포넌트들)를 담는데, 이를 add 시킨 순서로 0, 1, 2, 3, 4 .. 순으로 저장되게 된다. 그런데 이게 왜 중요하냐? 당연한게 아니냐? 의문이 들거다. 맞다. 너무 당연하다. 보통 Application들을 보면 여러가지 패널이라든지 혹은 창들을 보게 되는데 마우스를 클릭하면 해당 Unit 혹은 창들이 가장 최상위에서 활성화되게 된다. 즉, 선택한 녀석만 최상단에 나오게 되는 것이다.

 플래스를 하다가 보면 Click 이벤트로 유닛을 Drag 하고 Drop 하는 등 여러가지 일을 할 수 있는데, 이런 Container에 속한 자식들에 대한 Focus는 자체적으로 지원해 주지 않는다. ( 아시면 댓글 좀...)
 뭐 찾아보면 있을 수도 있는 거지만, 지금까지 헛 공부 한 것이 아니라면 자동으로 지원해 주지 않는다.
 그래서 위와 같이 여러 다중의 창이 떴을때 이런 것을 해주기 위해서는 위의 메서드들을 알아야 한다는 것이다.




 위의 코드에서 붉은 색 라인의 것은 swapChild를 사용해서 add 된 컴포넌트들끼리 순서를 바꿔준다. 물론 바꿔줄때 자신의 순번보다 하위에 있는 것은 손볼 필요가 없으므로 자신보다 순번이 높은 컴포넌트들끼리 바꿔주면 원하고자 하는 기능을 완성할 수 있다.

 아래는 위의 소스를 실행한 화면이다.





클릭한 사각 박스가 우선 선택 되는 것을 확인 할 수 있다.


-PS-
 가끔 오류가 나는데 Canvas로 된 Container를 선택하는게 아니라 쌩뚱맞게 뒤의 Border를 Swap 할때 선택하게 되서 오류가 난다. 드레그 한 사용자의 잘못이 아니라, 플래시 플레이어에서 이상하게 인식하는 건지 거참 요상하다. 잘되었다가 안되었다가 마음대로다. =_-...







ArrayCollection 에 담긴 데이터를 정렬할 일이 생겼다.

ArrayCollection 은 아니지만 비슷한 유형이라 관련 자료를 찾아 보았는데, ActionScript 3.4 reference에 간략한 소스와 함께 나와 있었다.

그것을 따라하면 별 다른 문제 없이 정렬이 된다.

물론 참고해야 될 것은 ArrayCollection만이 아닌 Sort, SortField 이렇게 3개를 참고해야 한다.




아래 참고 소스는 ActinoScript 3.4 reference에서 참고 한 것이다.



 
     var col:ICollectionView = new ArrayCollection();
// In the real world, the collection would have more than one item.
col.addItem({first:"Anders", last:"Dickerson"});
// Create the Sort instance.
var sort:Sort = new Sort();
// Set the sort field; sort on the last name first, first name second.
// Both fields are case-insensitive.
sort.fields = [new SortField("last",true), new SortField("first",true)];
// Assign the Sort object to the view.
col.sort = sort;
// Apply the sort to the collection.
col.refresh();



 <?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="200" height="135" borderStyle="solid" layout="absolute" backgroundColor="#EFEFEF">
    <mx:Script>
        <![CDATA[
        
            import mx.collections.Sort;
            import mx.collections.SortField;
            import mx.collections.ArrayCollection;
            
            [Bindable]
            private var array:ArrayCollection;
            private var numFlag:Boolean = false;
            private var txtFlag:Boolean = false;
            
            
            /**
             *         @function        : initApp
             *         @param            : none
             *         @description    : ArrayCollection instance와 데이터 추가
             *
             * */
            private function initApp():void
            {
                array = new ArrayCollection();                ///< ArrayCollection instance
                
                array.addItem({NUM:100, TXT:"AAAAA"});        ///< add item
                array.addItem({NUM:1, TXT:"CCCCC"});
                array.addItem({NUM:10, TXT:"BBBBB"});

            }

            /**
             *         @function        :    numClickEvent
             *         @param            :    none
             *         @description    :    numFlag 를 참조하여 오름차순, 내림찬순으로 정렬한다.
             * */            
            private function numClickEvent():void
            {
                if( array != null )        ///< 만약 초기화를 통해 null이 아니라면
                {
                    var sort:Sort = new Sort();
                    sort.fields = [ new SortField("NUM", true, numFlag) ];
                    array.sort = sort;            ///< ArrayCollection 내 sort에 대입한다
                    array.refresh();            ///< 컴포넌트를 갱신한다
                    numFlag = !numFlag;
                }                
            }            
            
            /**
             *         @function        :    txtClickEvent
             *         @param            :    none
             *         @description    :    txtFlag 를 참조하여 오름차순, 내림찬순으로 정렬한다.
             * */
            private function txtClickEvent():void
            {
                if( array != null )        ///< 만약 초기화를 통해 null이 아니라면
                {
                    var sort:Sort = new Sort();
                    sort.fields = [ new SortField("TXT", true, txtFlag) ];
                    array.sort = sort;            ///< ArrayCollection 내 sort에 대입한다
                    array.refresh();            ///< 컴포넌트를 갱신한다
                    txtFlag = !txtFlag;
                }
            }
            
        ]]>
    </mx:Script>
    
    <mx:DataGrid width="100%" height="100" dataProvider="{array}" editable="false" sortableColumns="false" creationComplete="initApp()" />
    <mx:HBox width="100%" height="25" bottom="3" horizontalCenter="0" horizontalAlign="center">
        <mx:Button width="100%" label="NUM" click="numClickEvent()"/>            
        <mx:Button width="100%" label="TXT" click="txtClickEvent()"/>
    </mx:HBox>
    
</mx:Application>


아래는 결과 swf 파일.
NUM 버튼을 누르면 NUM 정렬이, TXT를 누르면 TXT 정렬이 된다.
(두번 눌렀을 경우 역순으로 정렬)





+ Recent posts