cocos2d-xcocos2d-x-3.0cocos2d-x-3.x

How to make wrapped, scrollable text in cocos2d-x?


I've got a ui::Text in a ui::Layout and depending on the content, it overflows. I've looked into Label::setOverflow and Label::setWrap off the ui::Text's virtualRenderer Label, but I don't see a way to make it scrollable and wrap.

How can I make a scrollable ui::Text while making sure it's wrapping text properly?


Solution

  • The trick is, instead of using ui::Scrollview, to use a ui::ListView with only one item inside, the ui::Text. This lets you scroll around and dynamically resize the container, for when you change the text content of the ui::Text.

    The key is a) setting the width of the ui::Text to the same size as its parent ui::ListView and the height to 0 and b) calling my_listview->requestDoLayout() on the listview anytime the text content changes, so that the scrollable area reflects that.

    Here's an example of how you'd implement the large body of text scrolling into a smaller ui::Panel:

    ui::ListView* listview = ListView::create();
    my_scene->addChild(listview);
    listview->setContentSize({300, 500}); //give it whatever size
    
    ui::Text* text = ui::Text::create("[multiline content]", "fontName.ttf", 16);
    text->setTextAreaSize({300, 0}); //use that same size, but use 0 height. This auto sets overflow and wrap in the backend
    listview->addChild(text);
    listview->requestDoLayout(); //this triggers resizing the listview to accommodate the
                                 //string content. Needs to happen each time you
                                 //text->setString(new_content) too.