Cocos2d-lua(四)加载CocosStudio导出的UI界面

来源:互联网 发布:linux 复制 当前目录 编辑:程序博客网 时间:2024/04/30 03:40

       在实际开发游戏时,会使用大量的工具来辅助我们快速开发游戏。比如:CocosStudio,TiledMap(地图编辑器),Particle Builder(粒子编辑器),TexturePacker(图片资源打包)等。CocosStudio和TexturePacker程序需要掌握,资源图片和UI得拼装我们都得管理。这节主要讲解怎么把CocosStudio制作好的UI界面加载到游戏中。

UI界面是用的CocosStudio的示例,可以看这篇博客:http://blog.csdn.net/fjdmy001/article/details/52914020


一、加载UI界面

1.代码

--MainScene类,继承ViewBaselocal MainScene = class("MainScene", cc.load("mvc").ViewBase)function MainScene:onCreate()    --加载DemoLogin.json,形成界面,uiRoot:ui的根节点    local uiRoot = ccs.GUIReader:getInstance():widgetFromJsonFile("ui/DemoLogin.json");     --添加到场景中    self:addChild(uiRoot);endreturn MainScene


2.运行效果



二、获取UI节点(也称控件)

1.UI比如是一棵树,首先要有根(根节点),通过这根、枝干去找叶(节点),每个叶要有唯一标识(名字)。那我们如何获取UI的节点呢?父节点通过子节点的名称,标识Tag来获取子节点,所以在我们CocosStudio中的节点命名,Tag一定要规范,唯一。

  • 通过子节点名称,方法名:getChildByName
  • 通过子节点Tag,方法名:getChildByTag
  • 推荐,使用节点名称获取节点节点名称

2.任务:获取控件name_LabelBMFont(tag:501),password_LabelBMFont(tag:502),confirm_LabelBMFont(tag:503)


--MainScene类,继承ViewBaselocal MainScene = class("MainScene", cc.load("mvc").ViewBase)function MainScene:onCreate()    --加载DemoLogin.json,形成界面    local uiRoot = ccs.GUIReader:getInstance():widgetFromJsonFile("ui/DemoLogin.json");     --添加到场景中    self:addChild(uiRoot);--    self:resetLabelByName(uiRoot);    self:resetLabelByTag(uiRoot);endfunction MainScene:resetLabelByName(uiRoot)    --通过名称获取控件    local nameLabelBMFont = uiRoot:getChildByName("name_LabelBMFont")    --设置文本    nameLabelBMFont:setString("A")    local passwordLabelBMFont = uiRoot:getChildByName("password_LabelBMFont")    passwordLabelBMFont:setString("B")    local confirmLabelBMFont = uiRoot:getChildByName("confirm_LabelBMFont")    confirmLabelBMFont:setString("C")endfunction MainScene:resetLabelByTag(uiRoot)    --通过Tag获取控件    local nameLabelBMFont = uiRoot:getChildByTag("501")    --设置文本    nameLabelBMFont:setString("E")    local passwordLabelBMFont = uiRoot:getChildByTag("502")    passwordLabelBMFont:setString("F")    local confirmLabelBMFont = uiRoot:getChildByTag("503")    confirmLabelBMFont:setString("G")endreturn MainScene
运行之后,你会发现没什么变化,MainScene.lua文件需要的编码为:UTF-8 无签名

3.修改编码,vs --> 文件 --> 高级保护选项 





4.运行



这篇已经完了,文本控件如何设置中文,这篇没讲。如果没看懂的,留言!



0 0