Constrain input to textfield bounds.

By hp.

This is a bit of hack but nonetheless a genuine requisite in many cases.

It checks if text-input break the text out of field.width or field.height, in which case it prevents the change. Works with both single-line, and multiline TextFields Works best with multiline fields.

//Fields from the IDE tend to return wrong numLines initially, so make sure they are empty:
nameField.text = ""
descriptionField.text = ""
 
addEventListener(TextEvent.TEXT_INPUT, textInputhandler);
 
 
private function textInputhandler(event:TextEvent):void {
  var field:TextField = event.target as TextField;
 
  var oldText:String = field.text;
  var selectBegin:int = field.selectionBeginIndex;
  var selectEnd:int = field.selectionEndIndex;
  var newText:String = oldText.substr(0, selectBegin) + event.text + oldText.substr(selectEnd);
  field.text = newText
 
  var maxLines:int = int(field.height / (field.textHeight / field.numLines))
 
  if (field.textWidth > field.width || field.numLines > maxLines) {
  	event.preventDefault()
  }
 
  field.text = oldText;
  field.setSelection(selectBegin, selectEnd);
}

Leave a Reply