2009-06-17 83 views
1

我有一個自定義組件,基本上是VBoxLabelTextField不包括組件大小的尺寸

<mx:VBox width="50%"> 
    <mx:Label width="100%"/> 
    <mx:TextField width="100%"/> 
</mx:VBox> 

我想要什麼,基本上是有兩個這樣的VBox ES的奠定了在HBox和各會採取整整50% - 他們的孩子LabelTextField應該只是服從這一點。

如果我同時設置LabelTextField的寬度爲100%,而Label文本不適合,默認行爲是要擴大VBox寬度 - 我不希望這樣的事情發生。 TextField應該始終佔據寬度的100%,並且我希望Label明確設置爲TextField的寬度,因此文本將被截斷並且不會擴大VBox寬度。

有沒有辦法告訴標籤只是服從VBox(或TextField)寬度,而不是包含在VBox寬度的測量?

不知道我是否清楚。 :) 在此先感謝。

回答

1

這並不像我想的那麼容易。在開始時,我想建議maxWidth,但它不能正確使用標籤。不過我只是測試這一點:

<?xml version="1.0" encoding="utf-8"?> 
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"> 
    <mx:Script> 
     <![CDATA[ 
      import mx.controls.TextInput; 
      import mx.controls.Label; 
      private function onTextChanged(event:Event):void { 
       var currentText:String = TextInput(event.target).text; 
       var shortened:Boolean = false; 
       // adding 30 to leave some space for ... 
       while (lbl.measureText(currentText).width > (lbl.width-30)) { 
        currentText = currentText.substr(0,currentText.length-1); 
        shortened = true; 
       } 
       lbl.text = currentText + ((shortened) ? "..." : ""); 
      } 
     ]]> 
    </mx:Script> 
    <mx:VBox width="50%"> 
     <mx:Label id="lbl" width="100%" /> 
     <mx:TextInput width="100%" change="onTextChanged(event);" /> 
    </mx:VBox> 
</mx:WindowedApplication> 

它可能不被寫入的方式(只是歸因),你預期,但它確實你需要什麼。 如果這不是一個解決方案,您可以考慮按以下方式擴展標籤。 克里特島的自定義標籤:

radekg/MyLabel.as

package radekg { 
    import mx.controls.Label; 

    public class MyLabel extends Label { 
     public function MyLabel() { 
      super(); 
     } 

     private var _myText:String; 

     override public function get text():String { 
      return _myText; 
     } 

     override public function set text(value:String):void { 
      if (value != null && initialized) { 
       // store the copy so the getter returns original text 
       _myText = value; 
       // shorten: 
       var shortened:Boolean = false; 
       while (measureText(value).width > (width-30)) { 
        value = value.substr(0,value.length-1); 
        shortened = true; 
       } 
       super.text = value + ((shortened) ? "..." : ""); 
      } 
     } 
    } 
} 

而且使用這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:controls="radekg.*"> 
    <mx:VBox width="50%"> 
     <controls:MyLabel width="100%" id="lbl" text="{ti.text}" /> 
     <mx:TextInput width="100%" id="ti" /> 
     <mx:Button label="Display label text" click="mx.controls.Alert.show(lbl.text)" /> 
    </mx:VBox> 
</mx:WindowedApplication> 

這可以簡單地結合使用。一旦你在文本輸入中輸入非常長的文本並且標籤顯示...點擊按鈕。你會注意到text()getter返回原始文本。

希望這會有所幫助。