Cam
Cam

Reputation: 1048

AS3 Textfield Can't Select Color with ColorPicker on only Selected Text

I'm creating a text editor and I want users to be able to select only part of a textfield and change the color. The problem I'm running into is the ColorPicker gains focus (I'm guessing) and the textfield loses it's "selection."

All examples of text editing show the entire textfield changing color. Which isn't exactly what I want.

Any help/insight would be appreciated.

Upvotes: 0

Views: 944

Answers (1)

richardolsson
richardolsson

Reputation: 4071

Figure out what it is that causes your text field selection to be lost (e.g. could it be the click on the color picker component?). Then get the selectionBeginIndex and selectionEndIndex from the text field before that happens, and store it in a persistant (e.g. class member) variable.

When the user selects a color, use the setTextFormat() to change the color, passing in the stored start and end indices.

A quick example:

var beginIndex : uint;
var endIndex : uint;

function beforeFocusIsLost() : void {
    beginIndex = myTextField.selectionBeginIndex;
    endIndex = myTextField.selectionEndIndex;
}

function whenColorIsPicked() : void {
    var tf : TextFormat;

    tf = new TextFormat();
    tf.color = myColor;

    myTextField.setTextFormat(tf, beginIndex, endIndex);
}

If you want to keep the selection, you can also reset it after the color has been set using the TextField.setSelection() method.

EDIT: Note that if the selection is just hidden, maybe what you're after is simply TextField.alwaysShowSelection. Try setting it to true on your text field, and all of the above may be redundant.

myTextField.alwaysShowSelection = true;

Upvotes: 1

Related Questions