How can I keep track of a section of text in a Dynamic TextField in AS3
-
18-04-2021 - |
Domanda
I want to be able to apply non-style attributes to sections of text in a TextField. For example characters 30-45 will be set to animate in a certain direction.
As this field is editable characters 30-45 may no longer be at 30-45 if the text is edited in any way.
Can anyone think of an elegant way to keep track of which characters had the attributes applied to them?
Soluzione
I've had a similar project and ended up extending the TextField class to fit my needs. Here's a short description of what's to do - my actual code is confidential, I'm afraid:
- Override the setters for
text
andhtmlText
Parse any content from these setters into an array of custom objects. Each of these objects contains raw text chunks and the metadata that applies to them (format, comments, etc.).
For example,
<span class="sometext" animation="true">Info</span>
would be translated to an object like this:
{ text:"Info", clazz="sometext", animation:true };
- The actual text output is then rendered by using
appendText
to add chunk by chunk of the raw text and usingsetTextFormat
to apply formatting (or do whatever else is necessary) after each append step. - Add event listeners to react on TEXT_INPUT and/or KEY_DOWN/KEY_UP events to catch any new user input. (You will replace the entire text content of your TextField over and over again, so it's not an option to use
super.text
.) - User input is processed by using
selectionBeginIndex
andselectionEndIndex
(count the number of characters in the raw text of your object array to find out which chunks are affected). Add or replace the new text directly within the container objects, then use step 3. to refresh the entire text in the TextField. - I have also added a method that reduces the array before it is rendered (i.e. combine adjacent chunks with identical metadata). This keeps the array lean and helps creating XML output that does not have a complicated tree structure (one-dimensional is quite what we like for this kind of scenario).
- Override the getters for
text
andhtmlText
to return the newly formatted info, if you need the results somewhere else. I've usedhtmlText
to return a fully decorated xml string and kepttext
for accessing the raw text content, just like in a generic TextField.