给我出一个滚动容器的示例,里面放item框
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-06-28 01:32:22 |
👁️ 阅读: 1
我来给你一个完整的滚动容器示例,里面放置多个item框。这个示例会创建一个垂直滚动的容器,并添加一些带背景的格子。
```lua
-- 创建父窗口
local parent = GUI:Win_Create("GMMain", 0, 0, 0, 0, false, false, true, false, false, false, 1)
-- 创建滚动容器(垂直滚动)
local scrollView = GUI:ScrollView_Create(parent, "ScrollView_Container", 100, 100, 300, 400, 1)
-- 设置滚动容器属性
GUI:ScrollView_setBounceEnabled(scrollView, true) -- 启用回弹效果
GUI:ScrollView_setClippingEnabled(scrollView, true) -- 启用裁切
GUI:ScrollView_setBackGroundColor(scrollView, "#333333") -- 设置背景颜色
-- 设置内部容器大小(比可见区域大,才能滚动)
GUI:ScrollView_setInnerContainerSize(scrollView, 300, 800)
-- 创建多个item框并添加到滚动容器
local function createItemBox(index, x, y)
-- 创建item背景框
local itemBg = GUI:Widget_Create(scrollView, "item_bg_"..index, x, y, 80, 80)
GUI:Widget_setBackGroundImage(itemBg, "res/public/1900000610.png", 0)
-- 创建item序号文字
local textLabel = GUI:Text_Create(itemBg, "Text_index", 0, 0, 16, "#ffffff", "Item "..index)
GUI:Text_setFontName(textLabel, "fonts/font5.ttf")
GUI:setPosition(textLabel, 40, 40) -- 居中显示
-- 创建item按钮
local itemBtn = GUI:Button_Create(itemBg, "btn_item", 0, 0, "res/public/1900000612.png")
GUI:Button_setTitleText(itemBtn, "点击")
GUI:setPosition(itemBtn, 40, 20)
-- 添加按钮点击事件
GUI:addOnClickEvent(itemBtn, function()
SL:print("点击了Item "..index)
end)
return itemBg
end
-- 创建3行5列的item网格
local itemWidth = 80
local itemHeight = 80
local padding = 10
local startX = 20
local startY = 20
for row = 1, 3 do
for col = 1, 5 do
local index = (row - 1) * 5 + col
local x = startX + (col - 1) * (itemWidth + padding)
local y = startY + (row - 1) * (itemHeight + padding)
createItemBox(index, x, y)
end
end
-- 添加滚动事件监听
GUI:ScrollView_addOnScrollEvent(scrollView, function()
local innerSize = GUI:ScrollView_getInnerContainerSize(scrollView)
local scrollPercent = GUI:ScrollView_getScrolledPercentVertical(scrollView)
SL:print("当前滚动百分比: "..scrollPercent)
end)
-- 设置滚动到顶部按钮
local btnTop = GUI:Button_Create(parent, "btn_top", 420, 100, "res/public/1900000612.png")
GUI:Button_setTitleText(btnTop, "滚动到顶部")
GUI:addOnClickEvent(btnTop, function()
GUI:ScrollView_scrollToTop(scrollView, 0.5, true) -- 0.5秒内滚动到顶部,带衰减效果
end)
-- 设置滚动到底部按钮
local btnBottom = GUI:Button_Create(parent, "btn_bottom", 420, 150, "res/public/1900000612.png")
GUI:Button_setTitleText(btnBottom, "滚动到底部")
GUI:addOnClickEvent(btnBottom, function()
GUI:ScrollView_scrollToBottom(scrollView, 0.5, true) -- 0.5秒内滚动到底部,带衰减效果
end)
SL:print("滚动容器创建完成!")
```
**示例说明:**
1. **创建滚动容器**:使用`GUI:ScrollView_Create`创建垂直滚动容器
2. **设置容器属性**:
- `setBounceEnabled`:设置回弹效果
- `setInnerContainerSize`:设置内部容器大小(高度800 > 可见高度400,才能滚动)
3. **创建item框**:每个item包含:
- 背景框(使用你指定的图片)
- 序号文字
- 可点击按钮
4. **网格布局**:3行5列,共15个item
5. **滚动事件**:监听滚动位置变化
6. **控制按钮**:提供滚动到顶部/底部的功能
**注意事项:**
- 确保`res/public/1900000610.png`和`res/public/1900000612.png`图片存在
- 滚动容器需要设置内部容器大小大于可见区域才能滚动
- 每个item都需要唯一的ID
这个示例展示了滚动容器的基本用法,你可以根据需要调整item数量、布局和样式。如果item数量很多,建议使用`QuickCell_Create`来动态创建,避免一次性创建太多节点影响性能。
← 返回问答库