在引擎中并没有提供相应的下拉列表控件实现,所以如果在实际应用中需要的话就要自己代码实现。
下面我介绍两种实现的方式,以供大家参考。
方法一:
这个方法我是参考了网上的一段代码,然后自己对代码进行部分的修改,下面贴出一个xcode中的下拉列表框样式:
下面先贴出自定义实现的效果图:
通常,一个下拉列表框都是这样的:
①有一个选中后的显示栏目;
②点击显示栏目后,显示下拉列表,选中的哪一个行会高亮显示;
③对下拉列表进行选择,选好后,下拉列表会消失,显示栏目显示选中的内容。
下面先贴出实现的代码:
#ifndef DropDownListBox_DROPDOWNLIST_h
#define DropDownListBox_DROPDOWNLIST_h
USING_NS_CC;
namespace CustomDropDownListBox
{
//设置背景颜色
#define DROPDOWNLIST_NORMAL_COLOR ccc4(128, 128, 128, 255)
#define DROPDOWNLIST_SELECTED_COLOR ccc4(200, 200, 200, 255)
#define DROPDOWNLIST_HIGHLIGHT_COLOR ccc4(0, 0, 255, 255)
#define DROPDOWNLIST_NORMAL_COLOR3 ccc3(128, 128, 128)
#define DROPDOWNLIST_SELECTED_COLOR3 ccc3(200, 200, 200)
#define DROPDOWNLIST_HIGHLIGHT_COLOR3 ccc3(0, 0, 255)
class DropDownList : public CCLayer
{
public:
//构造方法
DropDownList(CCLabelTTF* label, CCSize size)
: showLabel(label)
, isShowMenu(false)
, lastSelectedIndex(0)
{
//创建好一个menu,但是现在还不添加到视图中
mainMenu = CCMenu::create();
mainMenu->setPosition(CCPoint(size.width / 2, size.height / 2));
mainMenu->retain();
showLabel->setPosition(CCPoint(size.width / 2, size.height / 2));
addChild(showLabel);
setContentSize(size);
}
//析构函数
~DropDownList()
{
mainMenu->release();
}
//创建实例对象方法
static DropDownList* create(CCLabelTTF* label, CCSize size)
{
DropDownList* list = new DropDownList(label, size);
list->autorelease();
return list;
}
//获取当前选中label的string
std::string getString()
{
return showLabel->getString();
}
//获取当前选中的index
int getSelectedIndex()
{
return lastSelectedIndex;
}
//设置选中index
void setSelectedIndex(int index)
{
lastSelectedIndex = index;
for (int i = 0, j = (int)selectLabels.size(); i < j; ++i)
{
if (i == lastSelectedIndex)
{
bgLayers[i]->setColor(DROPDOWNLIST_HIGHLIGHT_COLOR3);
showLabel->setString(selectLabels[i]->getString());
}
else
{
bgLayers[i]->setColor(DROPDOWNLIST_NORMAL_COLOR3);
}
}
}
void onEnter()
{
setTouchEnabled(true);
CCLayer::onEnter();
}
void registerWithTouchDispatcher()
{
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->addTargetedDelegate(this, kCCMenuHandlerPriority, true);
}
virtual bool ccTouchBegan(CCTouch *touch, CCEvent *event)
{
if (!isShowMenu)
{
CCRect rect;
rect.origin = CCPointZero;
rect.size = getContentSize();
CCPoint position = convertTouchToNodeSpace(touch