· 7 years ago · Nov 21, 2018, 01:44 PM
1local AutoCanvasSize = {}
2
3 local connections = {}
4
5 local function GetVerticalAmount(objs)
6 local amount = -1
7 local absolutes = {}
8
9 for i=1, #objs do -- loop thru all the frames
10 local o = objs[i]
11 local absolute_x = o.AbsolutePosition.X
12 if absolutes[absolute_x] then -- if this absolute y exists in the table, add this frame
13 table.insert(absolutes[absolute_x], o)
14 else
15 absolutes[absolute_x] = {} -- if it doesn't, create it.
16 table.insert(absolutes[absolute_x], o) -- then add this frame.
17 end
18 end
19 for absolute_x, gui_objs in pairs(absolutes) do -- loop thru the absolutes
20 if #gui_objs > amount then -- if this absolute_y has more frames than the current amount then, update the horizontal amount
21 amount = #gui_objs
22 end
23 end
24 return amount -- return the current horizontal amount.
25 end
26
27 function AutoCanvasSize.Disconnect(for_scroller)
28 print("Disconnect")
29 if connections[for_scroller] then
30 for i=1, #connections[for_scroller] do
31 local connection = connections[for_scroller][i]
32 print("Disconnecting a connection")
33 if connection then connection:Disconnect() end
34 end
35 connections[for_scroller] = nil
36 end
37 end
38
39 function AutoCanvasSize.Connect(scroller)
40 local grid = scroller:WaitForChild("UIGridLayout")
41
42 local function GetGuiObjects()
43 local objs = {}
44 local c = scroller:GetChildren()
45 for i=1, #c do
46 local o = c[i]
47 if o:IsA("GuiObject") then
48 table.insert(objs,o)
49 end
50 end
51 return objs
52 end
53
54 -- updates the CanvasSize based on the amount of frames in the frame, along with
55 local function Update()
56 local cell_size = Vector2.new(grid.CellSize.X.Offset, grid.CellSize.Y.Offset)
57 local gui_objs = GetGuiObjects()
58 local y_amount = GetVerticalAmount(gui_objs)
59 scroller.CanvasSize = UDim2.new(0,0,0, (cell_size.Y + grid.CellPadding.Y.Offset) * y_amount)
60 end
61 connections[scroller] = {
62 scroller.AncestryChanged:Connect(function()
63 if not scroller.Parent then
64 AutoCanvasSize.Disconnect(scroller)
65 end
66 end),
67 scroller.ChildAdded:Connect(function()
68 spawn(Update) -- it appears the child does not get added until the connection returns (or something of that effect)
69 -- so, we spawn the Update so it is inclusive of the new child.
70 end),
71 scroller.ChildRemoved:Connect(Update)
72 }
73 end
74
75return AutoCanvasSize