Thursday, February 28, 2008

Multiline /newline Button label in Flex 3

I was having the hardest time getting a newline to appear in my Button component. I followed the documentation in the Adobe Flex 3 docs to use &13; but that still did not work.

I got some e-mails from Matt Horn of Adobe Flex Docs, and he gave me several things to try, including using the standard "\n" character escape sequence, and the HTML "<br/>". Finally, he gave me a link to a blog entry by Alex Harui titled "Multiline Buttons".

The code needed a little tweaking for Flex 3, but all I did was extend the Button class, and use the same exact code Alex used in his MultilineRadioButton.

That being said, here's my MultilineButton.
You can use this component like a regular button; the difference now is that if you include "&13;" in your label, it will render a newline!

Enjoy.


package
{
import flash.display.DisplayObject;
import flash.text.TextLineMetrics;

import mx.controls.Button;
import mx.core.IFlexDisplayObject;
import mx.core.mx_internal;
use namespace mx_internal;


public class MultilineButton extends Button
{
public function MultilineButton()
{
//TODO: implement function
super();
}

override protected function createChildren():void
{
if (!textField)
{
textField = new NoTruncationUITextField();
textField.styleName = this;
addChild(DisplayObject(textField)); //cast required for Flex 3; if in Flex 2; remove
}

super.createChildren();

textField.multiline = true;
textField.wordWrap = true;
}

override protected function measure():void
{
if (!isNaN(explicitWidth))
{
var tempIcon:IFlexDisplayObject = getCurrentIcon();
var w:Number = explicitWidth;
if (tempIcon)
w -= tempIcon.width + getStyle("horizontalGap") + getStyle("paddingLeft") + getStyle("paddingRight");
textField.width = w;
}
super.measure();

}

override public function measureText(s:String):TextLineMetrics
{
textField.text = s;
var lineMetrics:TextLineMetrics = textField.getLineMetrics(0);
lineMetrics.width = textField.textWidth + 4;
lineMetrics.height = textField.textHeight + 4;
return lineMetrics;
}
}
}

2 comments:

Anonymous said...

Great post thanks!

The correct code for the newline is

Anonymous said...

I've tried this code several times and I always get an error at run time stating Could not resolve to a component implementation I really have no clue what I am doing wrong any info would be helpful