Выравнивание CCMenu в сетке - PullRequest
3 голосов
/ 14 июня 2011

Кто-нибудь знает лучший практический подход для получения массива CCMenuItems для выравнивания по сетке? Это вопрос cocos2d

Например:

int levelCount = 10;

CCMenu *menuArray = [CCMenu menuWithItems:nil];

for (int x = 1; x<=levelCount; x++) {
    CCLOG(@"Creating level icon for Level %i", x);     
    [menuArray addChild:[CCMenuItemImage itemFromNormalImage:@"Button2n.png" 
                                               selectedImage:@"Button2s.png" 
                                                      target:self 
                                                    selector:@selector(onPlay:)]];

}

[menuArray alignToGridWouldbeGreat????!!!!];
[self addChild:menuArray];

Я могу выровнять по вертикали, по горизонтали, по столбцам или строкам, но не могу перенести конфигурацию столбца или строки.

Заранее спасибо!

Ответы [ 5 ]

7 голосов
/ 26 ноября 2011

Вам просто нужно вызвать один из перегруженных методов alignItemsInColumns или alignItemsInRows.Например, если у вас есть 15 пунктов меню и вам нужно 3 строки по 5 столбцов, сделайте следующее:

CCMenu* menu = [CCMenu menuWithItems:...];
NSNumber* itemsPerRow = [NSNumber numberWithInt:5];
[menu alignItemsInColumns:itemsPerRow, itemsPerRow, itemsPerRow, nil];

Единственный недостаток в том, что, как представляется, нет способа установить отступ при выравнивании посетка.

1 голос
/ 19 сентября 2011

Вот мое решение, надеюсь, оно поможет.

Сначала определите эту структуру где-нибудь:

typedef struct
{
 int cols;
}RowInfo;

Затем:

-(void)layoutMenu:(CCMenu *)menu rowInfo:(RowInfo[])inf rows:(int)rows padding:(CGPoint)padding     
{
CCMenuItem *dummy = (CCMenuItem *)[menu.children objectAtIndex:0];
int itemIndex = 0;

float w = dummy.contentSize.width;
float h = dummy.contentSize.height;

CGSize screenSize = [[CCDirector sharedDirector]winSize];
CCArray *items = [menu children];

float startX;

for (int i = rows - 1; i >=0; i--)
{
    int colsNow = info[i].cols;

    startX = (screenSize.width - (colsNow * w + padding.x * (colsNow - 1)))/2;
    float y = i * (padding.y + h);

    for (int j = 0; j < colsNow; j++)
    {
        CCMenuItem *item = (CCMenuItem *)[items objectAtIndex:itemIndex];
        item.anchorPoint = ccp(0,0);
        item.position = ccp(startX, y);
        startX += padding.x + w;
        itemIndex++;
    }
}
}

Вызов будет выглядеть так (пользовательская клавиатура):

//create custom keyboard
NSArray *captions = [NSArray arrayWithObjects:
@"Q", @"W", @"E", @"R", @"T", @"Y", @"U", @"I", @"O", @"P",
   @"A", @"S", @"D", @"F", @"G",@"H", @"J", @"K", @"L",
     @"Z", @"X", @"C", @"V", @"B", @"N", @"M", nil];

CCMenu *menu = [CCMenu menuWithItems:nil];

[self addChild:menu];

for (NSString *caption in captions)
{
    CCLabelTTF *label = [CCLabelTTF labelWithString:caption fontName:@"Courier" fontSize:25];
    CCMenuItemLabel *item = [CCMenuItemLabel itemWithLabel:label target:self selector:@selector(callDelegate:)];
    [menu addChild:item];
}

RowInfo info[3] = {{7}, {9}, {10}}; //inverse order

[self layoutMenu:menu withRowInfo:info rows:3 padding:ccp(15, 15)];
1 голос
/ 16 июня 2011

Хорошо, хотя и не так гибко, как хотелось бы, у меня есть достаточно приличное решение для моих целей. Любой другой может свободно использовать этот код, если он тоже находит его полезным.

//////// Put images (or whatever) for all levels in an array /////////        

    int levelCount = 15;
    NSMutableArray* menuArray = [NSMutableArray arrayWithCapacity:levelCount];
    for (int x = 1; x<=levelCount; x++) {

        CCLOG(@"Creating level icon for Level %i", x);

        CCMenuItemImage* item = [CCMenuItemImage itemFromNormalImage:@"Button2n.png" 
                                                       selectedImage:@"Button2s.png" 
                                                              target:self 
                                                            selector:@selector(onPlay:)];
        [menuArray addObject:item];                        
    }

//////// расположены в сетке с определенным количеством столбцов /////////

    CGSize screenSize = [CCDirector sharedDirector].winSize;

    int columns = 5;

    int spaceBetweenColumns = columns + 1;

    int spacing = screenSize.width / spaceBetweenColumns;

    CCLOG(@"screenWidth (%f) / columnsWithEdges (%i) = spacing = %i, ", screenSize.width, spaceBetweenColumns, spacing);

    CGPoint currentDrawPoint = CGPointMake(0, screenSize.height - spacing);  // start at the top 

    for (CCMenuItem *item in menuArray) {

        currentDrawPoint.x = currentDrawPoint.x + spacing;

        if (currentDrawPoint.x > (columns * spacing)) {
            // start a new line as we have reached the end of the previous one
            currentDrawPoint.x = spacing;
            currentDrawPoint.y = currentDrawPoint.y - spacing;
        }

        item.position = currentDrawPoint;
        [self addChild:item];

    }
0 голосов
/ 14 июня 2011

Насколько я знаю, ответ Аниш - ваш лучший образ действий. Это было бы то же самое, что выравнивание по сетке, и это то, что я лично использую. Просто установите позицию меню и отступы для выравнивания, и вы получите то, что ищете.

0 голосов
/ 14 июня 2011

Может быть, вы можете попробовать это ...

[menuArray alignItemsVerticallyWithPadding:20.0];

или

[first_menu alignItemsHorizontallyWithPadding:20.0];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...