目标 C:使用标签

Chr*_*ris 0 tags objective-c uibutton

过去几天我一直在研究,无法弄清楚这一点。我有很多按钮做同样的事情(点击时消失)。我用自己的标签定义了每一个,但如何确定按下了哪个?

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


}
Run Code Online (Sandbox Code Playgroud)

计时器每 2 秒调用一次 Produce Bricks。

Sam*_*hie 5

Chris,如果您需要做的就是识别按下的按钮,只需更改您的方法声明以接受sender参数,调用者(UIButton在本例中为 a )将提供对自身的引用。创建一个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  
}
Run Code Online (Sandbox Code Playgroud)

(顺便说一下,因为你创建的代码的按钮,你并不需要声明的返回值IBActionIBAction是一样的void,只不过它的提示关闭界面生成器,你会被一些连接IBOutlet到特定的方法.)