Touch Event on Text

Hi

can i give a touch action for a word in a Text. Means, can i change the background of the word in Text or Label by deep press on the word.

Thanks.

1 Like

Did you see our touch events docs?

1 Like

Look into the RichText class… Here you can do some pretty cool stuff including callbacks and what not for specific portions of text.

https://docs.cocos2d-x.org/api-ref/cplusplus/v3x/dd/d4b/classcocos2d_1_1ui_1_1_rich_text.html#details

Otherwise, If it were me not using RichText, I would subclass Label and put some bounding box collision logic inside the touch handlers.

2 Likes

Hi,
i tried with RichText. Now i can do touch event on text. Thank you so much for helping me.
Now also my requirement is not completed. i can’t move to the next step. my problem is, how can i get the character from the touchPosition or how i select a word from the RichText by touching one word.

Thanks in advance

You can probably create an XML where each word has a ‘url’ tag associated, then override the OpenUrlHandler - maybe with a simple lambda function, and then you can create your own logic from there… There might be better ways than that, but just first option that came to mind

Rudimentary and untested example below of how that might work

ui::RichText *richText = ui::RichText::createWithXML("<font size='10' face='fonts/NotoSansUI-Regular.ttf'><a href='first'>first</a> <a href='second'>second</a>");
    
richText->setOpenUrlHandler([](std::string url) {
    if (url.compare("first") == 0) {
        //first hit
    } else if (url.compare("second") == 0) {
        //second hit
    }
    CCLOG("%s", url.c_str());
});

If you do not override the url handler, cocos will default to opening the url as an actual url in an external web browser. This can also be handy if this is your use case.

1 Like