Last month I wrote an article about using the Text Layout Framework in Flex 3.2 or AIR 1.5. The article was an introductory one, in which I explained the architecture and showed some basic code to use some of the main features of the framework. Some of you asked how one can add a scrollbar to scroll the text from a container that has more text than can be shown in the current viewport.
To tell you the truth, I was curious about how hard it would be, so today I just played a little bit and I managed to add a scrollbar to control the text.
You can test the code here.
Let me explain very quickly how I did it (if you want to see the details, click view source or scroll down this article for the code):
- I display the text using a single container; the size of this container is about 200 x 300 pixels.
- I added a mx:VScrollBar component to the page, setting the same height as the text container.
- When the TextFlow composes its text for displaying, a CompositionCompletionEvent.COMPOSITION_COMPLETE event is thrown. By listening for this event, I am able to determine if the text will actually flow outside of the text container.
- In the listener for CompositionCompletionEvent.COMPOSITION_COMPLETE, I get the total height of the composed text using _controller.calculateHeight() (this method returns the height in pixels. This is the height that the text needs in order to be shown entirely. If the height is bigger than the text container, then I set the max scroll value for the vertical scroll bar to that difference.
- I registered a listener for the scroll event on the vertical scroll bar. And next whenever the scroll bar moves, I use the current position of the scroll bar to set the DisplayObjectContainerController’s (this is the object that wraps the text container and it is used by TextFlow for displaying the text) verticalScrollPosition property (the value for this property is in pixels): _controller.verticalScrollPosition = event.position;
This did half of the job: when the user moves the scroll bar, the text moves. Next, I had to synchronize the scroll bar when someone scrolls the text directly too.
- To do that, I registered another listener for the scroll event on the TextFlow it self. And whenever the users scrolls the text from the text container directly (for example by selecting a piece of text, holding the left mouse button, and moving it downward or upward), I use the current position of the DisplayObjectContainerController’s verticalScrollPostion to set the scroll bar scrollPosition: scroll.scrollPosition = Math.ceil(_controller.verticalScrollPosition);
You have to use ceil() on the value because the verticalScrollPosition returns a Number, not an Integer.
- And that’s it!
I hope you enjoyed this!