-- 传入互斥的checkbox列表,格式如下 --[[checkBoxs = { box_1 = callBack_1, box_1 = callBack_1, box_1 = callBack_1, }--]] local RadioCheckBox = class("RadioCheckBox") function RadioCheckBox:ctor() -- checkBox集合 self.checkBoxs = {} self.lastSelectedBox = nil end -- 注册回调函数 function RadioCheckBox:registerCheckBoxs(checkBoxs, defaultSelect) -- checkBox集合 self.checkBoxs = checkBoxs self.lastSelectedBox = defaultSelect if self.lastSelectedBox then self.lastSelectedBox:setSelectedState(true) local callbackfun = self.checkBoxs[self.lastSelectedBox] if type(callbackfun) == "function" then callbackfun() end end for i, v in pairs(self.checkBoxs) do local function onCheckBoxClicked() if i:getSelectedState() then if self.lastSelectedBox then self.lastSelectedBox:setSelectedState(false) end -- 回调被选中的函数 if type(v) == "function" then if v() == false then i:setSelectedState(false) if self.lastSelectedBox then self.lastSelectedBox:setSelectedState(true) end return end end else i:setSelectedState(true) end -- 替换上一次的选中 self.lastSelectedBox = i end i:addEventListener(onCheckBoxClicked) end end -- 获取最后一次的选中box function RadioCheckBox:getLastSelectedCheckBox() return self.lastSelectedBox end -- 选中某个按钮 function RadioCheckBox:selectCheckBox(checkBox) local callbackFunc = self.checkBoxs[checkBox] if callbackFunc then if self.lastSelectedBox then self.lastSelectedBox:setSelectedState(false) end checkBox:setSelectedState(true) -- 回调被选中的函数 if type(callbackFunc) == "function" then if callbackFunc() == false then checkBox:setSelectedState(false) if self.lastSelectedBox then self.lastSelectedBox:setSelectedState(true) end return end end -- 替换上一次的选中 self.lastSelectedBox = checkBox end end return RadioCheckBox