Caqu
Caqu

Reputation: 1254

How do I programmatically scroll to the end of a Flex Spark Textarea when a new line is added?

The old method for the mx:TextArea no longer works. Specifically:

myMxTextArea.verticalScrollPosition = myMxTextArea.maxVerticalScrollPosition;

I've found this method for Spark but seems a bit kludgy:

mySparkTA.scrollToRange(mySparkTA.text.length-1, mySparkTA.text.length);

Is there a more straightforward way to do this?

Upvotes: 5

Views: 7219

Answers (4)

1.21 gigawatts
1.21 gigawatts

Reputation: 17726

<s:TextArea id="consoleTextArea" 
            change="consoleTextArea_changeHandler(event)"
            valueCommit="consoleTextArea_valueCommitHandler(event)"
            updateComplete="scrollToTheBottom()"
            />

And then in ActionScript:

        protected function consoleTextArea_valueCommitHandler(event:FlexEvent):void {
            scrollToTheBottom();
        }

        protected function consoleTextArea_changeHandler(event:TextOperationEvent):void {
            scrollToTheBottom()
        }

        public function scrollToTheBottom():void {
            var scrollBar:VScrollBar = consoleTextArea.scroller.verticalScrollBar;
            scrollBar.value = scrollBar.maximum;
            consoleTextArea.validateNow();

            if (scrollBar.value != scrollBar.maximum) {
                scrollBar.value = scrollBar.maximum;
                consoleTextArea.validateNow();
            }
        }

You might need to put the if statement in a loop for a few iterations or until the value matches or is close to the maximum.

Update: Added listener for updateComplete event. This may get in the way of someone typing but may work fine for this use case.

Upvotes: 0

jamix
jamix

Reputation: 5628

Assuming that you have

<s:TextArea id="ta" width="100%" height="100%" />

The following will work:

ta.scroller.verticalScrollBar.value = ta.scroller.verticalScrollBar.maximum;

No need to wrap the TextArea in a Scroller component.

Upvotes: 5

michaPau
michaPau

Reputation: 1648

The spark TextArea has an "appendText" method This appends the text and scrolls automatically down to the line added..

Upvotes: 1

J_A_X
J_A_X

Reputation: 12847

That is how you do with with a spark textarea, but you could always try to wrap it in a Scroller component and not have the textarea itself bother with scrolling:

<s:Scroller id="scroller">
   <s:TextArea id="ta" width="100%" height="100%" />
</s:Scroller>

Then doing this in AS:

scroller.verticalScrollBar.value = scroller.verticalScrollBar.maximum;

There's no other easy way to do it.

Upvotes: 2

Related Questions