我有一个像这样的UIButton数组:
@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *btn_Impact_Collection;
我有这个功能:
- (IBAction)impactAction:(id)sender;
在XIB文件中,我有九个按钮,每个按钮都通过引用插座集连接到btn_Impact_Collection数组。此外,每个按钮的Touch_inside属性都连接到函数ImpactAction。
现在,当单击一个按钮时,会调用ImpactAction函数,但在此函数中,我如何知道按下了哪个按钮?
提前感谢您的回答!
答案 0 :(得分:15)
将发件人转换为UIButton类,这将为您提供单击按钮的实例。我没有Xcode,但有类似的东西:
if ([sender isMemberOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)sender;
// Then you can reference the title or a tag of the clicked button to do some further conditional logic if you want.
if([btn.currentTitle isEqualToString:@"title of button"])
{
// do something.
}
else if(etc...)
}
答案 1 :(得分:13)
在界面构建器(1-9)中为每个按钮设置标签,然后说
if ([sender tag] == 1) {
//First button was pressed, react.
}
else if ([sender tag] == 2) {
//Second button was pressed, react.
}
// Etc...
else {
//Last button was pressed, react.
}
对所有其他人来说也一样,或者你可以把它放在一个开关里。
答案 2 :(得分:3)
不是对标题进行字符串检查(这很慢且可能很乏味),你可以:
- (void)buttonPressed:(id)sender
{
for( UIButton *button in self.buttonCollection )
{
if( sender == button )
{
// sender is your button (eg. you can access its tag)
}
}
}
答案 3 :(得分:0)
另一个选项..转发发件人以检查它是否是UIButton,然后切换sender.tag:
if ([sender isMemberOfClass:[UIButton class]]) {
switch ([sender tag]) {
case 0:
//do stuff for button with tag 0
break;
case 1:
//do stuff for button with tag 1
break;
case 2:
....
break;
default:
break;
}
}