UI系统-版本1
cocos2dx 3.10版本提供了 cocos studio 界面导出到lua,还提供了一套基本的MVC框架。
再次基础上改进代码,实现以下功能
1.无需手动填写 RESOURCE_BINDING 的内容,
2.Button 自动根据ui名字绑定到 函数名,比如 btnClose,的单击会被绑定到函数 ui_btnCloseClicked,这样,只需要在cocostudio重命名,然后lua在脚本添加函数ui_btnCloseClicked 即可。
3.ui的元素自动绑定到table成员,比如有个txtTips,lua脚本,里面使用直接self.ui.txtTips:setString(“11”);,方便快速开发
eg:添加一个新按钮流程
cocostudio 添加一个按钮名字为btnNew,导出资源为lua格式
MainScene.lua添加函数 ui_btnNewClicked ,即为点击事件回调
重构后的代码
MainScene.lua
local t = class("MainScene", cc.load("mvc").ViewBase) t.RESOURCE_FILENAME = "res/MainScene.lua" t.RESOURCE_BINDING = { -- ["Button_1"]={["varname"]="Button_1",["events"]={{["event"]="touch",["method"]="onBtnTouch"}}}, -- ["Text_1"] = {["varname"] = "txt_info"}, -- ["Panel"] = {["varname"] = "Panel"}, }; function t:onCreate() printf("resource node = %s", tostring(self:getResourceNode())) end function t:ui_btnCloseClicked() print(" close"); end function t:ui_btnSendClicked() print(" send"); self.counter =(self.counter and self.counter + 1) or 0; self.ui.txtInfo:setString("12344 " .. self.counter); end function t:ui_Panel_Panel2_btnShowClicked() print(" pp show"); end function t:ui_Panel_btnShowClicked() print("show " .. self.counter); end return t
ViewBase.lua
function ViewBase:ctor(app, name) self:enableNodeEvents() self.app_ = app self.name_ = name -- check CSB resource file local res = rawget(self.class, "RESOURCE_FILENAME") if res then self:createResoueceNode(res) end local binding = rawget(self.class, "RESOURCE_BINDING") if res and binding then self:createResoueceBinding(binding) end if self.onCreate then self:onCreate() end self.ui = { }; self.ui.root = self.resourceNode_; self:autoBind(self.resourceNode_); end function ViewBase:getFullParentName(node) local parent = ""; if node and node ~= self.ui.root then local tmp = node; while tmp:getParent() ~= self.ui.root do parent = tmp:getParent():getName() .. "_" .. parent; tmp = tmp:getParent(); end end return parent; end function ViewBase:autoBind(node) for _, v in pairs(node:getChildren()) do print(v:getName()); local node_name = v:getName(); if string.find(node_name, "btn") then -- bind button v:onTouch( function(e) if e.name == "ended" then local name = self:getFullParentName(v) .. node_name .. "Clicked"; local cb = self["ui_" .. name]; if cb then cb(self); else end end end ); end self.ui[self:getFullParentName(v) .. node_name] = v; -- bind var self:autoBind(v); -- bind child end end