[Solved] Focus on TextField at specified position

Hi!

I have an editable textfield that was created like this:

tf = new TextField();
tf.width = 200;
tf.height = 20;
tf.type = TextFieldType.INPUT;
tf.border = true;
addChild(tf);

After I move the mouse around and click on other things (so after losing focus), I’m trying to click on a specific spot on this editable text again. By using a mono-spaced font, I could calculate the position of the caret, so I could start editing at that specific position.

Here is how I first focus the text field:

Lib.current.stage.focus = tf;

(EDIT: which seems to move the caret at the beginning of the text)

And then, I would like to do something like:

tf.caretIndex = new_caret_position;

but unfortunately, caretIndex is read-only :frowning:

Any ideas?

Some more info: I’m actually using a way more complex setup, with some custom Bitmap fonts. When I click on a position, it hides the rendered text and replaces it with a regular TextField. This is why I have to manually focus on the new TextField.

Does textField.setSelection(index, index); work?

Indeed it does! Thank you so much, singmajesty! You made my day! <3 :heart_eyes:

From the docs:

If the two parameter values are the same, this method sets the insertion point, as if you set the caretIndex property.

I really don’t know how I missed this, I really searched for caret within the page, but still missed it at the time. Anyhow, now I don’t have to write my own custom textfield class just for handling this. So that’s an extra time saved for working on my other features. Yeey!

1 Like