Dynamically Sized Horizontal UIGridLayout

I’m making a backpack GUI that needs to make the tool slots smaller, depending on how many there are.

My GUI can currently hold up to 14 tool slots, but let’s see what happens when I pass this limit:

It overflows. Instead, I’d like it to dynamically size the tool slots to fit within the box, no matter how many tool slots there are.

They said that they wanted it to scale dynamically, so it would get smaller when there were over 14 frames so I’m not sure that’s what they’re looking for.

Can you read my original post and then reply?

I’ve been trying to find something but the best I can come up with is to use the AbsoluteContentSize property of the uigridlayout. Else I have no idea how to do this as there aren’t many resources covering this.

1 Like

After looking at the issue in Roblox Studio for a few minutes I quickly found the solution: CellSize.

:information_source: Info:

CellSize is a property within the UIGridLayout instance that scales all objects within it’s grid.


:desktop_computer: Application:

Since it does this, you could add a local script that finds the number of icons, for example #Frame:GetChildren() – Returns the # of icons.

Then you would dynamically change CellSize from that value.


:1234: Math Time:

If your frame is 450 pixels wide and has 8 images sized 100x100 then there will be 2 rows. This is because 450/100 = 4.5 and 4.5 < 8. This means if we use our old friend algebra we can say 450/8 = 56.25, which perfectly fits into one row!

Making the equation: Frame Width / # of Images = CellSize

:thinking: But wait, what about padding?

Well don’t worry, the equation is easy, just subtract the padding amount from the total.

Making the padded equation: (Frame Width / # of Images) - Padding Width = CellSize


As for the scripting:

local gridLayout = script.Parent
local frame = gridLayout.Parent

frame.ChildAdded:Connect(function() -- A new object is added to the frame.
	local numIcons = #frame:GetChildren()
	
	local adjustedSize = (frame.Size.Offset.X / numIcons) - gridLayout.CellPadding.Offet.X -- You can use scale too: frame.Size.Scale.X / gridLayout.CellPadding.Scale.X
	gridLayout.CellSize = UDim2.fromOffset(adjustedSize, adjustedSize) -- You can use scale too: UDim2.fromScale(adjustedSize, adjustedSize)
end)

I hope this helped solve your issue,
if you still need assistance feel free to reply to this or send me a private message.

~ Xitral, Lua Programmer

2 Likes