26
Jan
08

Truncating text in the Flex Label control using the truncateToFit property

The following example shows how you can use the truncateToFit property in the Label control in Flex to truncate strings if they exceed a specified width. The label control will terminate the string with “…” and allow you to roll over the text and read the entire (non-truncated) text in a tool tip, as seen in the following snippet:

<mx:Label text="The quick brown fox jumped over the lazy dog."
        truncateToFit="true"
        maxWidth="200" />

Full code after the jump.

The following example displays three Label controls:
The first Label control (”default”), simply sets the text property and allows the Label control to size itself to match the length of the text.
The second Label control (”truncateToFit = false”) sets the truncateToFit property to false and sets the maxWidth property to 200 pixels. Because the specified text will not fit within the 200 pixel control, the extra text is not displayed and is cropped off. You can see a portion of a last character in the Label control and rolling over the text will not display a tool tip.
The third Label control (”truncateToFit = true”) sets the truncateToFit property to true and sets the maxWidth property to 200 pixels. Because the specified text will not fit within the 200 pixel control, the extra text is not displayed, but the text displays “…” at the end of the control. No partial characters are displayed and rolling over the text displays a tool tip showing the entire contents of the text string.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/01/26/truncating-text-in-the-flex-label-control-using-the-truncatetofit-property/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:String id="str">The quick brown fox jumped over the lazy dog.</mx:String>

    <mx:Form>
        <mx:FormItem label="default:">
            <mx:Label text="{str}" />
        </mx:FormItem>
        <mx:FormItem label="truncateToFit = false:">
            <mx:Label truncateToFit="false"
                    text="{str}"
                    maxWidth="200" />
        </mx:FormItem>
        <mx:FormItem label="truncateToFit = true:">
            <mx:Label truncateToFit="true"
                    text="{str}"
                    maxWidth="200" />
        </mx:FormItem>
    </mx:Form>

</mx:Application>

View source is enabled in the following example.


7 Responses to “Truncating text in the Flex Label control using the truncateToFit property”


  1. 1 Quentin Feb 10th, 2008 at 5:00 am

    A quick comment to add that ‘truncateToFit’ won’t show the ‘…’ ending string on HTML Labels. They only get truncated.

    Here what you can find in Label.as :

    // Plain text gets truncated with a "...".
    // HTML text simply gets clipped, because it is difficult
    // to skip over the markup and truncate only the non-markup.
    // But both plain text and HTML text gets an automatic tooltip
    // if the full text isn't visible.

  2. 2 rob Apr 30th, 2008 at 7:05 am

    Hey folks, would anyone know how to extend the Label class, so that the tooltip is always shown when you hover over it? whether or not the label is truncated..

  3. 3 Chris Brind May 23rd, 2008 at 2:43 am

    @rob there’s a couple of ways I can think of. Inline:

    <mx:Label id="_alabel" text="hello" toolTip="{_alabel.text}" />
    

    secondly, you could subclass label and override the setter for the text property and assigning the text being set to the tooltip. i haven’t tried this, so this code is off the top of my head:

    public class TippedLabel extends Label {
    
      override public function set text(o:String) : void {
        super.text = o;
        super.toolTip = o;
      }
    
    }
    

    Hope that helps.

    Cheers,
    Chris

  4. 4 Pat Long Aug 1st, 2008 at 4:04 am

    Is there a way of using truncateToFit AND getting the Label to wrap? It seems the only way to get truncateToFit is to set a MaxWidth but the only way I have found to get wrapping to work is to set width=100%

  5. 5 mregert Aug 5th, 2008 at 8:47 am

    One possible solution would be:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    	<mx:Script>
    		<![CDATA[
    		import mx.utils.StringUtil;
    		[Bindable]
    		private var longString:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    		private var maxStringLength:int = 50;
    		private function truncatedString(source:String):String {
    			var shortString:String = StringUtil.trim(source);
    			shortString = shortString.substr(0, maxStringLength);
    			if (source.length != 0 && source.length > maxStringLength) {
    				shortString += "...";
    			}
    			return shortString;
    		}
    		]]>
    	</mx:Script>
    	<mx:Panel layout="absolute" left="10" right="10" bottom="10" top="10">
    		<mx:TextArea x="10" y="10" maxWidth="200" maxHeight="50" text="{truncatedString(longString)}" id="lblLongText" height="65" wordWrap="true"/>
    	</mx:Panel>
    
    </mx:Application>
    
  6. 6 mregert Aug 5th, 2008 at 8:49 am
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    	<mx:Script>
    		<![CDATA[
    		import mx.utils.StringUtil;
    		[Bindable]
    		private var longString:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    		private var maxStringLength:int = 50;
    		private function truncatedString(source:String):String {
    			var shortString:String = StringUtil.trim(source);
    			shortString = shortString.substr(0, maxStringLength);
    			if (source.length != 0 && source.length > maxStringLength) {
    				shortString += "...";
    			}
    			return shortString;
    		}
    		]]>
    	</mx:Script>
    	<mx:Panel layout="absolute" left="10" right="10" bottom="10" top="10">
    		<mx:TextArea x="10" y="10" maxWidth="200" maxHeight="50" text="{truncatedString(longString)}" id="lblLongText" height="65" wordWrap="true"/>
    	</mx:Panel>
    
    </mx:Application>
    
  7. 7 Dinesh Copoosamy Nov 24th, 2008 at 2:27 pm

    Is there a way to get truncated text to move left and right periodically so you can read the entire label?

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




Badge Farm

  • Firefox 2
  • Powered by Redoable 1.2
  • Feeds burnt by Feedburner
  • Feed