Как получить строку и столбец выбранной кнопки в массиве кнопок в iOS - PullRequest
1 голос
/ 17 ноября 2011

Предполагается, что я создал 2DArray кнопок, используя следующий код:

for (NSInteger rowIndex = 0; rowIndex < 6; rowIndex++) 
{
        NSMutableArray *rowOfButtons = [[NSMutableArray alloc] init];
        for (NSInteger colIndex = 0; colIndex < 7; colIndex++)
        {   
            CGRect newFrame = CGRectMake(2+colIndex * 45, 100 + rowIndex * 40, 45, 40);

            UIButton  *calButton = [UIButton buttonWithType:UIButtonTypeCustom];
            calButton.frame = newFrame;             
            [calButton setBackgroundColor:[UIColor whiteColor]];

            [rowOfButtons addObject:calButton];

            [calButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];           
            [self.view addSubview:calButton];             
        }
        [m_button2DArray addObject:rowOfButtons];
}

Как узнать строку и столбец нажатой кнопки в любом месте этой сетки?

1 Ответ

3 голосов
/ 17 ноября 2011

Установить тег для каждой кнопки следующим образом.

for (NSInteger rowIndex = 0; rowIndex < 6; rowIndex++) 
{
    NSMutableArray *rowOfButtons = [[NSMutableArray alloc] init];
    for (NSInteger colIndex = 0; colIndex < 7; colIndex++)
    {   
        CGRect newFrame = CGRectMake(2+colIndex * 45, 100 + rowIndex * 40, 45, 40);

        UIButton  *calButton = [UIButton buttonWithType:UIButtonTypeCustom];
        calButton.frame = newFrame;             
        [calButton setBackgroundColor:[UIColor whiteColor]];

        NSInteger tag = (rowIndex * 10) + colIndex;
        calButton.tag = tag;


    [calButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];  

        [rowOfButtons addObject:calButton];

        [self.view addSubview:calButton];             
    }
     [m_button2DArray addObject:rowOfButtons];
    [rowOfButtons release];
}  

И в buttonPressed: метод, найти, какая кнопка нажата следующим методом.

-(void)buttonPressed:(id)sender
{
    NSInteger tag = [sender tag];
    int row = tag / 10;
    int col = tag % 10;
    //do what you required for the particular button
}
...