0

我正在创建UIButtons一个循环,如下所示。

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

我将UIButton点击的事件处理为

-(void) buttonPressed{

}

我需要有关在事件处理方法中单击了哪个按钮的信息。我需要获取单击按钮的框架。如何更改此代码以获取有关发件人的信息。

4

2 回答 2

4

在创建按钮时向按钮添加标签并像这样btn.tag=i;重新定义您的方法

-(void) buttonPressed:(id)sender{
// compare  sender.tag to find the sender here
}
于 2012-04-01T06:30:38.260 回答
1

你应该做的是在你的代码中添加这些行:

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

现在像这样更改您的 IBAction:

 -(void) buttonPressed: (id)sender
 {

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

或者你可以这样做......这样你就可以将发件人中的对象复制到这个UIBtton对象。

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

因此,在此参数中sender,它将保留您UIButton与之交互的内容,并且您可以访问其属性,例如标签、文本等。希望对您有所帮助..

于 2012-04-01T06:44:15.973 回答