どのボタンが押されたかを判別するには

画面上のどのボタンが押されたかを判別するには、UIButtonクラスのtagプロパティを使用します。以下サンプルコードとなります。

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // ボタン1
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button1 setTitle:@"Button1" forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    button1.frame = CGRectMake(0, 0, 200, 100);
    button1.tag = 1;
    [self.view addSubview:button1];

    // ボタン2
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button2 setTitle:@"Button2" forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    button2.frame = CGRectMake(0, 100, 200, 100);
    button2.tag = 2;
    [self.view addSubview:button2];    
}

- (void)buttonPressed:(UIButton *)sender {
    NSLog(@"%d", sender.tag);
}