Profio
Profio

Reputation: 3

AS3 - Input Textfield Caret Positioning

I am using a Text Field to input user text (shown below). The problem is that after typing several characters the caret's position becomes offset to the left. I am trying to figure out how to either re-position the caret or somehow update character spacing to prevent the caret from becoming offset.

var myFont:Font = new Font2();

var myFormat:TextFormat = new TextFormat();
myFormat.font = myFont.fontName;
myFormat.size = 14;
myFormat.leading = 3;

var myText:TextField = new TextField();
myText.multiline = true;
myText.wordWrap = true;
myText.autoSize = TextFieldAutoSize.LEFT;
myText.defaultTextFormat = myFormat;
mainText.embedFonts = true;
myText.antiAliasType = AntiAliasType.ADVANCED;
mainText.text = "Hello";
mainText.type = TextFieldType.INPUT;

this.addChild(mainText);

Upvotes: 0

Views: 972

Answers (1)

Creative Magic
Creative Magic

Reputation: 3141

Well, there's no caret positioning method that I'm aware of, but you can just set a selection with 0 selected chars at the end of the TextField.

Here's a simplistic script that puts the caret at the end of the TextField on click. Try clicking on the middle/start of the TextField. The caret will be positioned there at the start of the click, but will jump to the end after the click has finished:

var tf:TextField = new TextField();
tf.type = TextFieldType.INPUT;
tf.addEventListener(MouseEvent.CLICK, onTfClick);
tf.text = "test text";
addChild(tf);

And the event handler:

function onTfClick(e:MouseEvent):void
{
    tf.setSelection(tf.length, tf.length); // this sets the caret to your desired position
}

So using setSelection() with startPos and as endPos will place the caret where you want.

Hope that helps!

Upvotes: 1

Related Questions