Cocos2d-x Version 3.17
// Create Button : Type - 1
{
Sprite *spr1 = Sprite::createWithSpriteFrameName(FRAME_MM_PLAY);
Sprite *spr2 = Sprite::createWithSpriteFrameName(FRAME_MM_PLAY);
spr2->setColor( Color3B(200, 200, 200) );
auto *playButton = MenuItemSprite::create(spr1, spr2, CC_CALLBACK_1(CBirdMainMenu::playBtnPress, this));
playButton->setScale(1.0f);
playButton->setEnabled(true);
auto playMenu = Menu::create(playButton, nullptr);
}
// Create Button : Type - 2
Button *infoButton
{
infoButton = Button::create(FRAME_MM_INFO,FRAME_MM_INFO,FRAME_MM_INFO,Widget::TextureResType::PLIST);
infoButton->setZoomScale(0.2f);
infoButton->setPressedActionEnabled(true);
infoButton->addTouchEventListener([&](Ref* sender, cocos2d::ui::Widget::TouchEventType type){
switch (type)
{
case ui::Widget::TouchEventType::BEGAN:
break;
case ui::Widget::TouchEventType::ENDED:
this->infoButtonPress();
break;
default:
break;
}
});
This->addChild(infoButton, 2);
}
In Type-2 how to change color of button when clicked. I used single image for all states. I don't like to use separate image. Is it possible to change color of selected sprite in Type2 ? In Type1, for MenuItemSprite , we can easily set color for selected image……In Type-2, if I call setColor on Button, then it is crashing.
infoButton->setColor(Color3B(200, 200, 200)); //Crashed on this
Don't know how to change color of button when pressed.
you are creating the button and assigning to the
InfoButtonpointer.the problem is though your
infoButtonis a local pointer.from the screenshot you have provided, I can see that it's locally created in
CBirdMenu::SetupMenu().you then add the
info buttonas a child to an object pointed by a pointer calledtoolBarHowever the moment theCBirdMenu::SetupMenu()ends, yourinfoButtonwill no longer be recognised by the lambda expression.one way and perhaps easiest way is to fix your problem is using dynamic casting on the lambda parameter
Ref* senderwithin the lambda expression.or alternativly, instead of having a local pointer
infoButton, store it as a class member ofCBirdMenu. this wayinfoButtonwill never get lost while thecBirdMenuexists.here is a quick demo. the header file;
notice the private member
cocos2d::ui::Button * InfoButton;And finally the source file where the button is instantiated and assigned to theinfoButtonpointer.if you apply the same principle to your code, this should solve your current problem with the
lambda. However I'm still not sure what yourtoolBarclass does since this is not included in the code. iftoolBaris a custom class, i recommend you to move yourinfoButtonfromCBirdMenutotoolBarinstead if you going with the second approach to adress your issue.