Hi,
I have a textarea component on UI and want to add font formatting to it using TextRange class.
My code is:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" verticalAlign="middle" backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.controls.textClasses.TextRange;
private function findRangeIndex():int
{
var prev : int;
var next : int;
prev = messageSend.selectionEndIndex + 1;
//find out how many whitespaces do we have
for (var i:uint=messageSend.selectionEndIndex + 1; i<messageSend.length; i++)
{
if ((next=messageSend.text.indexOf(" ",i)) != -1 )
{
if (next - prev > 1 ) break;
prev = next;
}
else break;
}
return prev;
}
private function italicText():void
{
var index : int;
//find the index of next whitespace
if ((index = messageSend.text.indexOf(" ",messageSend.selectionEndIndex)) > -1)
{
//if you have immediate whitespace then continue else skip the process
if (index == messageSend.selectionEndIndex)
{
index = findRangeIndex();
var tr1:TextRange = new TextRange(messageSend ,true, messageSend.selectionBeginIndex, index);
}
else
{
if ((messageSend.selectionBeginIndex == 0) || (messageSend.text.charAt(messageSend.selectionBeginIndex - 1) != " "))
var tr1:TextRange = new TextRange(messageSend,true);
else
var tr1:TextRange = new TextRange(messageSend ,false, messageSend.selectionBeginIndex - 1, messageSend.selectionEndIndex);
}
}
else
{
if ((messageSend.selectionBeginIndex == 0) || (messageSend.text.charAt(messageSend.selectionBeginIndex - 1) != " "))
var tr1:TextRange = new TextRange(messageSend,true);
else
var tr1:TextRange = new TextRange(messageSend ,false, messageSend.selectionBeginIndex -1, messageSend.selectionEndIndex);
}
if (tr1.fontStyle == "normal") tr1.fontStyle = "italic";
else if (tr1.fontStyle == "italic") tr1.fontStyle = "normal";
messageSend.setSelection(messageSend.selectionBeginIndex , messageSend.selectionEndIndex);
messageSend.setFocus();
tr1 = null;
}
]]>
</mx:Script>
<mx:Canvas width="328" height="300">
<mx:TextArea id="messageSend" x="22" y="19" width="273" height="131"/>
<mx:Button x="131" y="179" label="Italic" click="italicText()"/>
</mx:Canvas>
</mx:Application>
The italic functionality works fine for all cases (I mean when you select the text written in Textarea and press the button or when you simply press the button (without selecting text) and expect that all text after that point will become italic) except when you do not have a whitespace character before the cursor position on your textarea and you press the button. What I found during debugging was that if the created TextRange has beginindex and endindex same then there will be no effect of the styling except when the beginindex = endindex = 0.
Can someone please suggest a solution? I’m seriuosly pissed off here