2012年6月4日 星期一

限制 Flash TextField 輸入字數及行數

監聽 TextEvent.TEXT_INPUT 事件,
超過字數及行數使用 e.preventDefault 取消事件。
完整 code 如下:

package
{
import flash.display.Sprite;
import flash.events.TextEvent;
import flash.text.TextField;
import flash.text.TextFormat;
public class BaseInput extends Sprite
{
private const MAX_NUM_LINES:uint = 3;
private const MAX_NUM_TXT:uint = 30;
private var _tf:TextField;
public function BaseInput(__config:Object)
{
var color:Number = 0x3B5998;
if (__config.color != null) color = Number(__config.color);
var format:TextFormat = new TextFormat("Microsoft JhengHei", 14, color);
format.letterSpacing = 1;
format.leading = 2;
_tf = new TextField();
_tf.defaultTextFormat = format;
_tf.multiline = true;
_tf.wordWrap = true;
_tf.selectable = true;
_tf.type = "input";
_tf.border = false;
_tf.width = __config.w;
_tf.height = __config.h;
_tf.text = __config.txt;
addChild(_tf);
_tf.addEventListener(TextEvent.TEXT_INPUT, inputHandler);
}
private function inputHandler(e:TextEvent):void
{
/*
* 換行不計算在內
*/
if (_tf.numLines > MAX_NUM_LINES || removeExtraWhitespace(_tf.text).length > MAX_NUM_TXT - 1) {
// Cancels an event's default behavior
e.preventDefault();
}
}
// Removes windows-style line breaks
private function removeExtraWhitespace(p_string:String):String
{
if (p_string == null) { return ''; }
return p_string.replace(/[\r\n]+/g, '');
}
}
}
view raw BaseInput.as hosted with ❤ by GitHub

沒有留言:

張貼留言