00003 不思议迷宫.0009.2.3:自动换装:回改到真实环境
在将代码弄到真实环境之前,先将UIAutoEquipingConfig中的类似代码重构一下。
local label_goingFloor =cc.Label:createWithTTF("进入下一层",FONT, FONT_SIZE);
local icon_goingFloor =cc.Sprite:create(grayedEquipment);
local button_goingFloor =ccui.Button:create(BUTTON_IMAGE_NORMAL, BUTTON_IMAGE_SELECTED);
button_goingFloor:setTitleText(BUTTON_TEXT);
button_goingFloor:setTitleFontName(FONT);
button_goingFloor:setTitleFontSize(FONT_SIZE);
local function onButton_goingFloor(sender,eventType)
print("onButton_goingFloor");
end
AddTouchEventListener(button_goingFloor,onButton_goingFloor);
self:addChild(label_goingFloor);
self:addChild(icon_goingFloor);
self:addChild(button_goingFloor);
上面的这个代码,抽取到一个函数中:
functionUIAutoEquipingConfig:appendItem(equipType, labelText, buttonCallback)
local label = cc.Label:createWithTTF(labelText,FONT, FONT_SIZE);
local icon =cc.Sprite:create(grayedEquipments[equipType]);
local button =ccui.Button:create(BUTTON_IMAGE_NORMAL, BUTTON_IMAGE_SELECTED);
button:setTitleText(BUTTON_TEXT);
button:setTitleFontName(FONT);
button:setTitleFontSize(FONT_SIZE);
AddTouchEventListener(button,buttonCallback);
self:addChild(label);
self:addChild(icon);
self:addChild(button);
return {label, icon, button,};
end
原来的构造函数改成这样:
functionUIAutoEquipingConfig:ctor(equipType)
self:setName("UIAutoEquipingConfig");
local background =cc.Sprite:create("images/ui/button/btn_large_disable.png");
self:addChild(background);
UIPositioning.fitToScreen(background);
local button_close =ccui.Button:create("images/ui/equip/222.png");
local function onButton_close(sender,eventType)
self:getParent():removeChild(self)
end
AddTouchEventListener(button_close,onButton_close);
self:addChild(button_close);
UIPositioning.rightTop(button_close);
UIPositioning.hvCenter({
self:appendItem(equipType,"当前装备 ",
function (sender,eventType)
print("onButton_current");
end),
self:appendItem(equipType,"进入下一层",
function (sender,eventType)
print("onButton_nextFloor");
end),
self:appendItem(equipType,"进到下一层",
function (sender,eventType)
print("onButton_arrivingFloor");
end),
self:appendItem(equipType,"胜利者石柱",
function (sender,eventType)
print("onButton_clickingColumn");
end),
}, HSPACING, VSPACING);
return self
end
是不是变得简短很多?当然,随着修改的进行,可能还会把按钮回调函数抽取出去:
functionUIAutoEquipingConfig:ctor(equipType)
……
local function onButton_current(sender,eventType)
print("onButton_current");
end