Search code examples
iphoneeventsuibuttonsender

How to get the information about the sender in the case here


I am creating UIButtons inside a loop as shown below.

for(int i = 1; i <= count; i++){

        if(i ==1){
            UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, 40, 40)];
            [btn1 setImage:image2 forState:UIControlStateNormal];
            [self addSubview:btn1];
            continue;
        }
        x = x + 40;
        y = y + 50; 
         UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(x , y, 40, 40)];
        [btn2 setImage:image1 forState:UIControlStateNormal];
        [btn2 addTarget:self action:@selector(buttonPressed) 
       forControlEvents:UIControlEventTouchUpInside];

         [self addSubview:btn2];
    }

And I handle the UIButton clicked events as

-(void) buttonPressed{

}

I need the information about which button I have clicked in the event handling method. I need to ge the frame of the clicked button. How can I alter this code to get the information about the sender.


Solution

  • Add a tag to your button while it is created like btn.tag=i; and re define your method like this

    -(void) buttonPressed:(id)sender{
    // compare  sender.tag to find the sender here
    }