cocos2dx用checkbox實現單選框和button實現table按鈕,cocos2dxcheckbox
轉載請註明出處:簾卷西風的專欄(http://blog.csdn.net/ljxfblog)
cocos2dx有checkbox和button,但是checkbox是個複選框,也沒有table按鈕,本文主要是利用這兩個控制項來實現單選框和table按鈕的功能。
主要思路就是,通過響應checkbox和button的事件,來設定和他一組的其他控制項的狀態來達到我們需要的效果。
我的工作環境時cocos2dx3.2+lua。
首先看看checkbox的實現,我用來實現男女性別的選擇。
local manCheck = self:getChild("CheckBox_Man")local womanCheck = self:getChild("CheckBox_Woman")if manCheck and womanCheck thenlocal function callback(sender, eventType)if eventType == ccui.CheckBoxEventType.selected thenif sender == manCheck thenwomanCheck:setSelectedState(false)elsemanCheck:setSelectedState(false)endelseif eventType == ccui.CheckBoxEventType.unselected thenif sender == manCheck thenwomanCheck:setSelectedState(true)elsemanCheck:setSelectedState(true)endendendmanCheck:addEventListener(callback)womanCheck:addEventListener(callback)manCheck:setSelectedState(true)womanCheck:setSelectedState(false)end
然後再來一個table按鈕的實現。
先定義一些table的常量定義:
--定義常量local Item_Tag_All = 1000 local Item_Tag_Equip = 1001local Item_Tag_Material = 1002local Item_Tag_Other = 1003local ButtonSwitch = {[Item_Tag_All] = "全部",[Item_Tag_Equip] = "裝備",[Item_Tag_Material] = "材料",[Item_Tag_Other] = "其他",}然後建立按鈕,並設定tag:
--篩選按鈕local width = title_bg:getContentSize().widthfor tag = Item_Tag_All, Item_Tag_Other doif ButtonSwitch[tag] thenlocal curbtn = ccui.Button:create()curbtn:setTouchEnabled(true)curbtn:setScale9Enabled(true)curbtn:loadTextures(BTN__NORMAL, BTN_SELECTED, "", ccui.TextureResType.plistType)curbtn:setSize(cc.size(100, 53))local size = curbtn:getContentSize()curbtn:setPosition(cc.p(width + size.width / 2, winSize.height - 20 - size.height / 2))curbtn:setTitleText(ButtonSwitch[tag])curbtn:setTitleFontSize(25)curbtn:setTag(tag)self._widget:addChild(curbtn)--註冊點擊事件local function callback_tag(sender, eventType)if eventType == ccui.TouchEventType.ended thenshowTable(tag)endendcurbtn:addTouchEventListener(callback_tag)width = width + curbtn:getContentSize().width + 10endend
最後是顯示按鈕的規則,把同組的其他table設定成正常,選中的設定成高亮:
--顯示一個tablefunction showTable(showTag) for tag = Item_Tag_All, Item_Tag_Other do local tagBar = self._widget:getChildByTag(tag) if tagBar then if showTag == tag then tagBar:setBrightStyle(ccui.BrightStyle.highlight) else tagBar:setBrightStyle(ccui.BrightStyle.normal) end end endend
好了,分享完了。看看吧!