Pergunta

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.

Foi útil?

Solução

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
}

Outras dicas

What you should do is add these lines in your code:

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

         [btn1 setTag:i];   // This will set tag as the value of your integer i;

        [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 setTag:i];   // also set tag here.
    [btn2 addTarget:self action:@selector(buttonPressed) 
   forControlEvents:UIControlEventTouchUpInside];

     [self addSubview:btn2];
}

And now change your IBAction like this:

 -(void) buttonPressed: (id)sender
 {

  if(sender.tag==1) // determine which button was tapped using this tag property.
     {
         // Do your action..
     }
 }

Or you can do it this way..This way you copy the object thats in sender to this UIBtton object.

-(void) buttonPressed: (id)sender
 {

  UIButton *tempBtn=(UIButton *) sender; 
  if(tempBtn.tag==1) // determine which button was tapped using this tag property.
     {
         // Do your action like..
         tempBtn.backgroundColor=[UIColor blueColor];
         tempBtn.alpha=0.5;
     }
 }

So in this parameter sender its going to hold your UIButton on which you interact and you can access its properties like tag, text etc. Hope it helps..

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top