2010-12-26 8 views
0

私は過去数日間研究しており、これを理解することはできません。私は同じことをするたくさんのボタンを持っています(クリックすると消えます)。私は独自のタグでそれぞれを定義しますが、どれが押されたのかはどのようにして決めるのですか?目的C:タグを使う

-(IBAction) tapBrick{ 
int x = brick.tag; 
NSLog(@"%d", x); 


//remove last brick 
[brick removeFromSuperview]; 

//add to score 
count++; 
NSString *scoreString = [NSString stringWithFormat:@"%d", count]; 
score.text = scoreString; 

//determine x y coordinates 
int xPos, yPos; 
xPos = arc4random() % 250; 
yPos = arc4random() % 370; 
} 


-(void) produceBricks { 
//determine x y coordinates 
int xPos, yPos; 
xPos = arc4random() % 250; 
yPos = arc4random() % 370; 

//create brick 
brick = [[UIButton alloc] initWithFrame:CGRectMake(xPos,yPos + 60,70,30)]; 
[brick setBackgroundColor:[UIColor blackColor]]; 
[brick setTag:i]; 
[brick addTarget:self action:@selector(tapBrick) forControlEvents:UIControlEventTouchUpInside]; 
i++; 
[self.view addSubview:brick]; 


} 

プロデューサブリックは、タイマーによって2秒ごとに呼び出されます。

+0

最後のスレッドでタグなしでこれを行う方法に関する回答があります:http://stackoverflow.com/questions/4515592/objective-c-removing-previous -ui-elements –

+0

レコードの場合、タグはObjective Cのものではなく、UIViewクラス(およびその派生物)の機能です。 –

答えて

4

Chrisは、押されたボタンを特定するだけで、senderパラメータを受け入れるようにメソッド宣言を変更するだけで、呼び出し元(この場合はUIButton)が自身への参照を提供します。 UIButtonポインタを作成すると、押されたボタンのタグにアクセスできます。

-(void) tapBrick:(id)sender { 
    //this is the button that called your method. 
    UIButton *theButton = (UIButton *)sender; 

    int tag = theButton.tag; 
    NSLog(@"%d", tag); 

    [theButton removeFromSuperview]; 

    //rest of code 
} 

(あなたがコードでボタンを作成しているので、ところで、あなたはIBActionの戻り値を宣言する必要はありません。IBActionがあることにInterface Builderオフということのヒントを除き、voidと同じですその特定のメソッドにIBOutletを接続します)。

+0

私はそれをやりましたが、実行時にエラーが発生します。 [brick removeFromSuperview]をtheButtonなどに変更しますか? – Chris

+0

はい、それはちょうど正しいです - 私は方法の残りの部分を記入させてください。 –

+0

ありがとうございました!だから私はこれを正しく理解して、これを送信者にすることによって、押されたボタンのタグを送信するだけです。 – Chris