来自Adobe Devnet:
问题描述:
我需要创建一个固定尺寸的TextArea组件,但是如果用户输入的文本长度超出了TextArea的高度,我希望TextArea能自动改变高度,而不是使用滚动条。
解决方案:
扩展TextArea,重写text和height属性的Setter方法,并且添加一个事件来侦听文本内容的改变。
主要代码:
private function adjustHeightHandler (event:Event ): void { trace ( "textField.getLineMetrics(0).height: " + textField. getLineMetrics ( 0 ). height ); if ( height <= textField. textHeight + textField. getLineMetrics ( 0 ). height ) { height = textField. textHeight; validateNow ( ); } }
演示以及源码下载:
http://www.riameeting.com/examples/DynamicTextArea/DynamicTextAreaSample.html
点击右键可查看源码
DynamicTextAreaSimple.mxml
<?xml version="1.0" encoding="utf-8" ?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:comp="*" creationComplete="init();" viewSourceURL="srcview/index.html">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private var str:String = "This text will be long enough to trigger " +
"the TextArea to increase its height.";
private function setLargeText():void{
txt1.text = str;
txt2.text = str;
txt3.text = str;
txt4.text = str;
}
]]>
</mx:Script>
<comp:DynamicTextArea id="txt1" width="300" height="14"/>
<comp:DynamicTextArea id="txt2" width="300" height="20"/>
<comp:DynamicTextArea id="txt3" width="300" height="28"/>
<comp:DynamicTextArea id="txt4" width="300" height="50"/>
<mx:Button label="Set Large Text" click="setLargeText();"/>
</mx:Application>
DynamicTextArea.as
package {
import flash.events.Event;
import mx.controls.TextArea;
public class DynamicTextArea extends TextArea{
public function DynamicTextArea(){
super();
super.horizontalScrollPolicy = "off";
super.verticalScrollPolicy = "off";
this.addEventListener(Event.CHANGE, adjustHeightHandler);
}
private function adjustHeightHandler(event:Event):void{
trace("textField.getLineMetrics(0).height: " + textField.getLineMetrics(0).height);
if(height <= textField.textHeight + textField.getLineMetrics(0).height){
height = textField.textHeight;
validateNow();
}
}
override public function set text(val:String):void{
textField.text = val;
validateNow();
height = textField.textHeight;
validateNow();
}
override public function set height(value:Number):void{
if(textField == null){
if(height <= value){
super.height = value;
}
}else{
var currentHeight:uint = textField.textHeight + textField.getLineMetrics(0).height;
if (currentHeight<= super.maxHeight){
if(textField.textHeight != textField.getLineMetrics(0).height){
super.height = currentHeight;
}
}else{
super.height = super.maxHeight;
}
}
}
override public function get text():String{
return textField.text;
}
override public function set maxHeight(value:Number):void{
super.maxHeight = value;
}
}
}