Cocos2d x UI development CCControlSlider control class use instance
- 2020-04-02 02:46:20
- OfStack
See article: (link: #) for some configuration when controls are used. Here just write out the source code, inside the comments on the use of the control has a detailed introduction.
bool HelloWorld::init()
{
bool bRet = false;
do
{
CC_BREAK_IF(! CCLayer::init());
//Sets a label that displays a string
CCLabelTTF * title = CCLabelTTF::create("slider value = 0.00","Arial",32);
title->setPosition(ccp(240,200));
//Set the tag of the label to 1 for easy retrieval later
this->addChild(title,0,1);
//These three pictures are the bottom, the progress bar, and the control button
CCControlSlider * slider = CCControlSlider::create("sliderTrack.png","sliderProgress.png",
"sliderThumb.png");
//Set the maximum and minimum values for the slider
slider->setMaximumValue(100);
slider->setMinimumValue(0);
//Adds an event listener function to the slider
slider->addTargetWithActionForControlEvents(this,cccontrol_selector(HelloWorld::valueChanged),
CCControlEventValueChanged);
//Set the location
slider->setPosition(ccp(240,160));
this->addChild(slider);
//Using the CCControlSlider to implement the health bar, simply change the third control button to be transparent and it will look like a health bar
CCControlSlider * slider2 = CCControlSlider::create("sliderTrack.png","progress.png","sliderThumb2.png");
//Make it impossible to change its value by the following function
slider2->setTouchEnabled(false);
slider2->setMaximumValue(100);
slider2->setMinimumValue(0);
//You can add an event handler and change its value in the event handler
slider2->setValue(100);
slider2->setPosition(ccp(240,100));
this->addChild(slider2);
bRet = true;
} while (0);
return bRet;
}
//Notice that this function needs to pass in two parameter types
void HelloWorld::valueChanged(CCObject * pSender,CCControlEvent controlEvent)
{
CCControlSlider * slider = (CCControlSlider *)pSender;
CCLabelTTF * title = (CCLabelTTF *)this->getChildByTag(1);
//Try not to change the content of CCLabelTTF when using it, for the sake of simplicity
title->setString(CCString::createWithFormat("slider value = %0.02f",slider->getValue())->getCString());
}