Search code examples
iosios4ios5ios-4.2

How to retrieve the row and col of selected button in an array Of buttons in iOS


Assuming I have created a 2DArray of buttons using the following code:

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];
}

How do I find out the row and column of a clicked button anywhere within that grid?


Solution

  • Set tag for each button like following.

    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];
    }  
    

    And in buttonPressed: method, find which button is pressed by following method.

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