function npc.leftButtonLoading(p1)
SL:print(p1)
npc.buttron_Layout = GUI:Layout_Create(parent, "buttron_Layout_", -366, -256, 135, 446, false)
--[[ GUI:Layout_setBackGroundColor(npc.buttron_Layout, "#FF0000")
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-06-04 17:12:14 |
👁️ 阅读: 7
根据浮生梦老师前端课程内容,你的代码有几个需要改进的地方:
```lua
function npc.leftButtonLoading(p1)
SL:print("当前选中按钮索引:", p1)
-- 先检查父节点是否存在
if GUI:Win_IsNull(parent) then
SL:print("错误:父节点为空")
return
end
-- 创建或获取按钮布局
if GUI:Win_IsNull(npc.buttron_Layout) then
npc.buttron_Layout = GUI:Layout_Create(parent, "buttron_Layout_", -366, -256, 135, 446, false)
-- 可以设置背景颜色(可选)
-- GUI:Layout_setBackGroundColor(npc.buttron_Layout, "#FF0000")
-- GUI:Layout_setBackGroundColorType(npc.buttron_Layout, 1)
-- GUI:Layout_setBackGroundColorOpacity(npc.buttron_Layout, 100)
else
-- 清空现有子控件
GUI:removeAllChildren(npc.buttron_Layout)
end
npc.buttron = {}
-- 遍历列表创建按钮
for index, value in ipairs(npc.list) do
local y = 424 - ((index - 1) * 44)
local png = p1 == index and value.png_2 or value.png_1
-- 创建按钮
npc.buttron[index] = GUI:Button_Create(npc.buttron_Layout, "buttron_" .. index, 67, y, "res/custom/duanwunongqing_ui/" .. png .. ".png")
-- 设置按钮属性
GUI:setAnchorPoint(npc.buttron[index], 0.5, 0.5)
GUI:setContentSize(npc.buttron[index], 135, 44)
GUI:setTouchEnabled(npc.buttron[index], true)
-- 设置按钮文字(如果需要)
if value.name then
GUI:Button_setTitleText(npc.buttron[index], value.name)
GUI:Button_setTitleColor(npc.buttron[index], "#ffffff")
GUI:Button_setTitleFontSize(npc.buttron[index], 14)
end
-- 设置点击事件
local idx = index
GUI:addOnClickEvent(npc.buttron[index], function()
npc.leftButtonLoading(idx)
end)
end
end
-- 初始化调用
local p1 = 1
if npc.list and #npc.list > 0 then
npc.leftButtonLoading(p1)
else
SL:print("错误:npc.list 为空或未定义")
end
```
**主要修改点:**
1. **增加空值检查**:使用 `GUI:Win_IsNull()` 检查父节点和布局是否存在
2. **优化布局创建**:如果布局已存在则复用,避免重复创建
3. **增加错误处理**:检查 `npc.list` 是否存在且不为空
4. **改进按钮ID**:将按钮ID改为 `"buttron_" .. index` 避免与布局ID冲突
5. **添加文字设置**:如果按钮需要显示文字,可以设置标题文本
6. **增强调试信息**:打印更详细的日志信息
**函数说明:**
- `GUI:Win_IsNull(widget)`:检查控件是否为空
- `GUI:removeAllChildren(widget)`:移除所有子控件
- `GUI:Button_setTitleText(button, text)`:设置按钮文字
- `GUI:Button_setTitleColor(button, color)`:设置按钮文字颜色
- `GUI:Button_setTitleFontSize(button, size)`:设置按钮文字大小
**注意事项:**
1. 确保 `parent` 变量在调用前已正确创建
2. `npc.list` 需要是一个包含按钮信息的数组,格式如:`{ {png_1="btn1_normal", png_2="btn1_selected", name="按钮1"}, ... }`
3. 按钮图片路径需要确保文件存在
如果还有问题,可以告诉我具体的错误现象,浮生梦老师会帮你进一步分析!
← 返回问答库