124 lines
3.1 KiB
Plaintext
Raw Normal View History

2025-07-18 01:11:49 +08:00
local UIList = {}
UIList.__index = UIList
--> Services
local ReplicatedStorage = game:GetService("ReplicatedStorage")
--> Dependencies
local Utils = require(ReplicatedStorage.Tools.Utils)
-- 子脚本自动注入
local function AutoInjectVariables(self)
for varName, _ in pairs(self.Variables) do
if typeof(varName) == "string" then
local firstChar = string.sub(varName, 1, 1)
local sixChar = string.sub(varName, 1, 6)
local target
if firstChar == "_" then
if sixChar == "__list" then
local prefab = Utils:FindInDescendantsUI(self.UIRoot, varName)
target = UIList:Init(prefab)
else
-- _开头递归查找
target = Utils:FindInDescendantsUI(self.UIRoot, varName)
end
if not target then
error("自动注入失败未找到UI节点 " .. varName)
end
self.Variables[varName] = target
end
end
end
end
function UIList:Init(Prefab: Instance)
local self = {}
setmetatable(self, UIList)
self.Data = {}
self.Instances = {}
self.Connections = {}
self.Component = nil
self.UIRoot = Prefab
self.Org = Utils:FindInDescendantsUI(Prefab, "__org")
self.Org.Visible = false
return self
end
function UIList:AddComponent(Component: table)
self.Component = Component
end
function UIList:SetData(Data: table)
self.Data = Data
self:Refresh()
end
function UIList:AddData(data: table)
self.Data[#self.Data + 1] = data
self:SetSingleInstance(#self.Data, data)
end
function UIList:SetSingleInstance(index: number, data: table)
local child = self.Component:Init(data)
local uiInstance = self.Org:Clone()
child.UIRoot = uiInstance
uiInstance.Name = index
uiInstance.Parent = self.Org.Parent
self.Instances[index] = child
AutoInjectVariables(child)
child:Refresh()
uiInstance.Visible = true
end
function UIList:Refresh()
for _, ui in pairs(self.Instances) do ui:Destroy() end
self.Instances = {}
if not self.Component then warn("UIList:Refresh() Component未设置") return end
if self.Data then
for k, v in pairs(self.Data) do
self:SetSingleInstance(k, v)
end
end
end
function UIList:Clean()
-- 清除自己的内容
for _, connection in pairs(self.Connections) do
connection:Disconnect()
end
self.Connections = {}
-- 清除下面组件的内容
for _, ui in pairs(self.Instances) do
for _, connection in pairs(ui.SignalConnections) do
connection:DisconnectAll()
end
self.SignalConnections = nil
for _, connection in pairs(ui.Connections) do
connection:Disconnect()
end
self.Connections = nil
ui:Destroy()
end
self.Instances = {}
end
function UIList:Destroy()
self:Clean()
self.SignalConnections = nil
self.Connections = nil
self.Org:Destroy()
self = nil
end
return UIList