您需要设置每个按钮的目标动作.
[button setTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)
然后someMethod:像这样实现:
- (void)someMethod:(UIButton *)sender {
if (sender.tag == 1) {
// do action for button with tag 1
} else if (sender.tag == 2) {
// do action for button with tag 2
} // ... and so on
}
Run Code Online (Sandbox Code Playgroud)
为什么需要使用tag来获取按钮。您可以直接从其操作方法中获取按钮引用。
- (void)onButtonPressed:(UIButton *)button {
// "button" is the button which is pressed
NSLog(@"Pressed Button: %@", button);
// You can still get the tag
int tag = button.tag;
}
Run Code Online (Sandbox Code Playgroud)
我希望您已经为按钮添加了目标操作。
[button addTarget:self action:@selector(onButtonPressed:)
forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)