local function zhuanpan(msgID, msgData)
local screenWidth = SL:GetMetaValue("SCREEN_WIDTH", 0)
local screenHeight = SL:GetMetaValue("SCREEN_HEIGHT", 0)
local parent = GUI:Win_Create("zhuanpan", 0, 0, 0, 0, false, false, true, false, fal
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-04-20 14:51:31 |
👁️ 阅读: 10
你的代码中有一个关键问题:在循环内部过早地移除了 `ui.Button_1`,导致后续的 `GUI:addOnClickEvent` 调用时,按钮对象已经无效(nil)。
**问题分析:**
1. 在 `for i = 1, 10 do` 循环内部,你调用了 `GUI:removeFromParent(ui.Button_1)`。
2. 这个移除操作发生在第一次循环时(i=1),之后 `ui.Button_1` 就变成了 nil。
3. 但循环还在继续(i=2到10),每次循环都会再次执行 `GUI:addOnClickEvent(ui.Button_1, function() ... end)`。
4. 此时 `ui.Button_1` 已经是 nil,所以 `GUI:addOnClickEvent` 会报错 "target is nil value"。
**解决方案:**
将 `GUI:removeFromParent(ui.Button_1)` 移到循环外部,确保只移除一次,并且不会影响循环内的其他逻辑。
```lua
local function zhuanpan(msgID, msgData)
local screenWidth = SL:GetMetaValue("SCREEN_WIDTH", 0)
local screenHeight = SL:GetMetaValue("SCREEN_HEIGHT", 0)
local parent = GUI:Win_Create("zhuanpan", 0, 0, 0, 0, false, false, true, false, false, false, 1)
local fullScreenAnim = GUI:Frames_Create(
parent,
"FullScreenFrames",
screenWidth/2,
screenHeight/2,
"res/public/word_fubentg_",
".png",
1,
10,
{speed = 100, count = 10, loop = -1}
)
GUI:setAnchorPoint(fullScreenAnim, 0.5, 0.5)
GUI:setContentSize(fullScreenAnim, screenWidth, screenHeight)
GUI:setIgnoreContentAdaptWithSize(fullScreenAnim, false)
local layout = GUI:Layout_Create(parent, "layout", screenWidth/2, screenHeight/2, 900, 500)
if layout then
GUI:setAnchorPoint(layout, 0, 0)
GUI:setTouchEnabled(layout, true)
end
local bg_kuang = GUI:Image_Create(layout, "bg_kuang", 450, 250, "res/01/010011.jpg")
if bg_kuang then
GUI:setAnchorPoint(bg_kuang, 0.5, 0.5)
GUI:setContentSize(bg_kuang, {width = 900, height = 500})
end
GUI:LoadExport(layout, "zhuanpan")
local ui = GUI:ui_delegate(layout)
GUI:setCascadeOpacityEnabled(layout, true)
GUI:setOpacity(layout, 0)
GUI:runAction(layout, GUI:ActionFadeIn(2))
GUI:addOnClickEvent(ui.Button_1, function()
-- 先移除按钮,确保只执行一次
GUI:removeFromParent(ui.Button_1)
for i = 1, 10 do
local t = {}
local b = {}
local pos = GUI:getPosition(ui['Image_'..i])
table.insert(t, i, {x = pos.x, y = pos.y})
local chi = GUI:getContentSize(ui['Image_'..i])
table.insert(b, i, {width = chi.width, height = chi.height})
GUI:removeFromParent(ui['Image_'..i])
local beimian = GUI:Button_Create(layout, "bei"..i, t[i].x, t[i].y, "res/public_win32/1900000610.png")
GUI:setContentSize(beimian, b[i].width, b[i].height)
GUI:setVisible(beimian, true)
GUI:runAction(beimian, GUI:ActionMoveTo(1, -72, -103))
GUI:addOnClickEvent(beimian, function()
SL:print('点击了' .. i)
end)
end
-- 注意:这里不能再次移除 ui.Button_1,因为它已经在循环开始前移除了
end)
end
```
**关键修改:**
1. 将 `GUI:removeFromParent(ui.Button_1)` 移到了循环开始前,确保只执行一次。
2. 删除了循环内部的第二个 `GUI:removeFromParent(ui.Button_1)` 调用。
3. 确保按钮点击事件只注册一次,避免重复注册。
**建议:**
下次写循环逻辑时,注意对象的状态变化。如果一个对象在循环中被移除,后续循环中就不能再使用它。可以使用 `GUI:Win_IsNull(widget)` 来检查控件是否有效。
如果还有问题,记得检查 `ui['Image_'..i]` 是否存在,避免访问不存在的UI组件。
← 返回问答库