Friday, July 1, 2011

SHIFT+ENTER adding a new line - chat textfield

Looking all over the internet for a simple adding a new line when pressing SHIFT+ENTER... not to be found.

So, for the ones who also looked very long, here is an example.
This sample also disables the ENTER key. Only when you hit SHIFT+ENTER it adds a new line to the textfield

public class TextfieldSample extends Sprite
private var textfield:TextField;

public function TextfieldSample()
//Creating the textfield an adding it on stage.
textfield = new TextField();

//event to disable the ENTER key
textfield.addEventListener(TextEvent.TEXT_INPUT, handleTextEvent);
//event to enable SHIFT+ENTER key
textfield.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);

//Make it an input textfield
textfield.type = TextFieldType.INPUT;

//Just use border to show it easy on stage.
textfield.border = true;
//You need multiline for adding new lines.
textfield.multiline = true;


private function handleTextEvent(event:TextEvent):void
if (event.text.charCodeAt() == 10)
//char code 10 == ENTER key

private function handleKeyDown(event:KeyboardEvent):void
if(event.keyCode == Keyboard.ENTER)
//You need to give something else the focus, otherwise the textfield is blocked
//and adding the new line will not work.
stage.focus = stage;
//Don't use appendtext for adding a new line, this function does not puts the new line in the correct position.
textfield.replaceText(textfield.selectionBeginIndex, textfield.selectionBeginIndex, "\n");
//Give the textfield the focus again
stage.focus = textfield;

If you have any improvement for this code, just let me know...

Tuesday, May 3, 2011

AS3 - Children adding reverse

Today I learned an extra feature of adding children into a DisplayObject in reverse.
Normally I would make two loops. First one is adding the children, the second is placing the children in reverse.
But... it can be done so much easier:

for(var i:int = 0; i < numChildren; i++)



The second parameter sets the child on the first place.

For many known, not for me.. maybe not for you either....