--展开顶部按钮
function Button:upshow()
local Node = GUI:getChildByName(parent, "Node1_upshow")
if Node then
GUI:setVisible(Node, true)
return
end
local Node_1 = GUI:Node_Create(parent, "Node1_upshow", 0, 0)
--基础容器
local layout = GUI:L
看了你的代码,问题主要出在坐标计算上。你的新代码使用了从0开始的坐标递减布局,但原始代码使用了`GUI:UserUILayout`函数来自动排列,两者的布局逻辑不同。
根据浮生梦老师前端课程内容,`GUI:UserUILayout`函数会自动处理按钮的排列,而你的手动布局需要调整坐标计算方式。
以下是修改后的代码,确保layout位置与之前一致:
```lua
--展开顶部按钮
function Button:upshow()
local Node = GUI:getChildByName(parent, "Node1_upshow")
if Node then
GUI:setVisible(Node, true)
return
end
local Node_1 = GUI:Node_Create(parent, "Node1_upshow", 0, 0)
--基础容器
local layout = GUI:Layout_Create(Node_1, "layout1_upshow", topweizhi.x, topweizhi.y, 100, 120, false)
GUI:setAnchorPoint(layout, 1, 1)
local toplist = {} --top表重构
for k, v in pairs(budata) do
if v.type == 1 then
toplist[v.weizhi] = v
end
end
-- 获取第一个按钮的尺寸(假设所有按钮尺寸相同)
local firstBtnData = toplist[1] or toplist[next(toplist)]
if not firstBtnData then
SL:Print("没有找到按钮数据")
return
end
-- 创建第一个临时按钮来获取尺寸
local tempBtn = GUI:Button_Create(layout, "temp_btn", 0, 0, firstBtnData.img)
local btnSize = GUI:getContentSize(tempBtn)
GUI:removeFromParent(tempBtn) -- 移除临时按钮
local btnWidth = btnSize.width
local btnHeight = btnSize.height
-- 设置间隔
local gapX = 5
local gapY = 5
-- 获取行数
local hang = budata[1].rownums == nil and 6 or budata[1].rownums
-- 计算每行最大按钮数
local maxButtonsPerRow = hang
local currentRow = 0
local currentCol = 0
-- 按位置排序(从1开始)
local sortedKeys = {}
for k in pairs(toplist) do
table.insert(sortedKeys, k)
end
table.sort(sortedKeys)
-- 创建按钮并手动布局
for _, key in ipairs(sortedKeys) do
local v = toplist[key]
-- 计算当前按钮在行中的位置
local colInRow = currentCol % maxButtonsPerRow
-- 关键修改:调整坐标计算方式
-- 从容器右侧开始向左排列,x坐标为负值
local xPos = -colInRow * (btnWidth + gapX)
-- y坐标从容器顶部开始向下排列
local yPos = -currentRow * (btnHeight + gapY)
local bt = GUI:Button_Create(layout, v.redname, xPos, yPos, v.img)
GUI:addOnClickEvent(bt, function()
local func = MList[v.script]
if not func or not func.main then
return SL:Print(v.script .. " 不存在或没有main函数")
end
-- 点击触发,执行main函数
func:main()
end)
currentCol = currentCol + 1
-- 检查是否需要换行
if currentCol % maxButtonsPerRow == 0 then
currentRow = currentRow + 1
end
end
-- 根据实际按钮数量调整容器大小
local totalRows = math.ceil(#sortedKeys / maxButtonsPerRow)
local containerWidth = maxButtonsPerRow * btnWidth + (maxButtonsPerRow - 1) * gapX
local containerHeight = totalRows * btnHeight + (totalRows - 1) * gapY
GUI:setContentSize(layout, containerWidth, containerHeight)
-- 关键修改:调整layout的锚点和位置
-- 设置layout的锚点为右上角(1,1)
GUI:setAnchorPoint(layout, 1, 1)
-- 确保layout的初始位置正确
GUI:setPosition(layout, topweizhi.x, topweizhi.y)
end
```
主要修改点:
1. 保持了`GUI:setAnchorPoint(layout, 1, 1)`,确保锚点在右上角
2. 按钮布局从右上角开始,x坐标为负值向右递减,y坐标为负值向下递减
3. 最后重新设置layout的位置到`topweizhi.x, topweizhi.y`
这样修改后,你的手动布局应该与之前使用`GUI:UserUILayout`函数的效果位置一致了。如果还有偏移,可以调整`topweizhi`的坐标值。