--展开顶部按钮
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,
我来帮你修改代码,手动实现从右到左的按钮布局。首先需要获取按钮的尺寸,然后根据设定的行数进行排列。
```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)
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)
end
```
**代码说明:**
1. **获取按钮尺寸**:
- 先创建一个临时按钮获取实际尺寸
- 假设所有按钮尺寸相同
2. **手动布局逻辑**:
- 使用`currentCol`和`currentRow`跟踪位置
- 从右到左排列:x坐标为负数递减(因为锚点在右上角)
- 每排满一行就换行
3. **参数说明**:
- `gapX`, `gapY`:按钮间隔固定为5
- `hang`:每行按钮数,默认6个
- `maxButtonsPerRow`:每行最大按钮数
4. **容器大小自适应**:
- 根据实际按钮数量和行数计算容器大小
- 使用`setContentSize`设置合适尺寸
这样就不需要依赖`GUI:UserUILayout`函数了,完全手动控制布局。如果按钮尺寸有变化,代码会自动适应。