How to set focus on TLFTextField

2019-07-15 19:36发布

问题:

like the title said. How to set focus on TLFTextField on runtime?

I already do some research and find a few question answered in SO like this How to set focus to a TLFTextfield object

And on few forum, they said to use this code

stage.focus = txt;

or

txt.stage.focus = txt;

or

txt.textFlow.interactionManager.setFocus();

But none works for me.. I'd try on simple project and still failed..

I need to show a MovieClip with a TLFTextField and focus on it.. So user can just type to edit the TLFTextfield.

my code:

public function TFLayer() {
    tf = new TLFTextField();
    tf.width = 400;
    tf.height = 30;
    tf.x = 300;
    tf.y = 300;
    tf.border = true;
    tf.type = TextFieldType.INPUT;
    tf.backgroundColor = 0xffffff;
    tf.text = "Lorem ipsum";
    addChild(tf);

    tf.textFlow.interactionManager.setFocus();
}

回答1:

Given an editable TLFTextField named tf, you can enable focus with:

import flashx.textLayout.edit.EditManager;

tf.textFlow.interactionManager = new EditManager();
tf.textFlow.interactionManager.selectRange(0, 0);
tf.textFlow.interactionManager.setFocus();

Using this method, the text field is focused ready to receive input from the keyboard; however, the cursor will not blink. Therefore, there's no visual indication of focus.

TLFTextFields are not optimal for user input. Consider using TextField or TextArea instead.



回答2:

Thanks to Jason Sturges, now I have the simplified answer. After testing his code, I decide to experiment further and it comes that I only need 2 lines of code to make this works..

    tf.textFlow.interactionManager.setFocus();
    tf.setSelection(tf.text.length, tf.text.length);.

there is no need to import flashx.textLayout.edit.EditManager. Weird enough, because interactionManager actually need EditManager to works.

But this code works fine for me. I compile it with FlashDevelop. I event didn't add textLayout.swc to my libs