The only problem with your code is that it would make the grid as followed by index
7 8 9
4 5 6
1 2 3
If you don't write any index number on your levels or whatever you are making the grid for, your code is good enough, but I needed it to be like so:
1 2 3
4 5 6
7 8 9
So I "fix'd" it.
Other than that, I also made an opportunity to center the menugrid, for obvious reasons :)
Your code was fantastic startpoint, and I couldn't appreciate it more, and without it I wouldn't even have comed so far. So thx a ton.
Here is my newer version. It's a mess, because I am a noob with cocos2d, but it should work.
Feel free to rewrite it :)
-(void) layoutWithStyle:(EGridStyle)gridStyle itemLimit:(int)itemLimit padding:(CGPoint)padding centerInParent:(BOOL) center{
int col = 0, row = 0, itemCount = 0;
for (CCMenuItem* item in self.children)
{
item.anchorPoint = ccp(0, 1);
CGPoint newPosition = CGPointMake(col * padding.x, row * padding.y);
newPosition = [[CCDirector sharedDirector] convertToUI:newPosition];
item.position = newPosition;
++itemCount;
if (gridStyle == kCollumsFirst)
{
++col;
if (itemCount == itemLimit)
{
itemCount = 0;
col = 0;
++row;
}
}
else
{
++row;
if (itemCount == itemLimit)
{
itemCount = 0;
row = 0;
++col;
}
}
}
if (center) {
self.position = ccp(0 , 0);
float locationForLowestItem = self.contentSize.height;
for (CCMenuItem* child in self.children) {
[child setAnchorPoint:ccp(0, 0)];
if (child.position.y < locationForLowestItem) {
locationForLowestItem = child.position.y;
}
}
for (CCMenuItem* child in self.children) {
[child setAnchorPoint:ccp(0, 0)];
child.position = ccp(child.position.x, child.position.y - locationForLowestItem);
}
float contentWidth = 0;
float contentHeight = 0;
for (CCNode* child in self.children) {
if (child.position.x + child.boundingBox.size.width > contentWidth) {
contentWidth = child.position.x + child.boundingBox.size.width;
}
if (child.position.y + child.boundingBox.size.height > contentHeight) {
contentHeight = child.position.y + child.boundingBox.size.height;
}
}
self.contentSize = CGSizeMake(contentWidth, contentHeight);
CGSize winSize = [[CCDirector sharedDirector] winSize];
self.position = ccp((winSize.width/2) - (self.contentSize.width/2) , (winSize.height/2)-(self.contentSize.height/2));
}
}