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 に答える