Created
June 4, 2012 04:55
-
-
Save wwwins/2866443 to your computer and use it in GitHub Desktop.
limit input chars in a textfield
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, ''); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment