将多个按钮链接到一个具有不同作业的方法

时间:2012-04-06 16:15:44

标签: iphone objective-c cocoa-touch methods

我的故事板上有一个巨大的疯狂场景,有36个不同的按钮,每个按钮在点击时都意味着不同的东西。我真的不想创建36种不同的方法,所以如何在按下36个按钮之一时调用的方法中引用按钮标题或按钮名称。

这可能是一个简单的问题,但我是iOS和Objective C的新手......

谢谢!

6 个答案:

答案 0 :(得分:6)

您可以创建一个方法,如下所示:

- (IBAction)buttonTapped:(id)sender{

  // The button that was tapped is called "sender"
  // This will log out the title of the button

  //NSLog(@"Button: %@", sender.titleLabel.text);

  //Edit: You need a cast in the above line of code:

  NSLog(@"Button: %@", ((UIButton *)sender).titleLabel.text);
}

然后,您可以使用Interface Builder连接到所有按钮。您可以使用某种if / else逻辑来测试点击了哪个按钮。

您可以检查titleLabel属性,也可以为每个按钮分配IBOutlet并检查它。

例如:

if([sender isEqual:buttonOutlet1]){
  //If this button is attached to buttonOutlet1
  //do something
}

或者,您可以简单地使用每个按钮的标签,而不必担心插座。

第三种选择是在代码中生成和布局按钮,然后将它们作为按钮数组的元素进行访问。

第四个选项是在按钮中添加标签,并在功能中检查按钮的标签。

答案 1 :(得分:2)

为每个按钮指定唯一的标记值。在IBAction中,sender.tag告诉您点击了哪个按钮。

答案 2 :(得分:1)

您设置用于处理按钮按下的IBAction例程具有sender参数。检查一下来决定。

答案 3 :(得分:0)

这很简单,但既然你是新人,这就是答案。
(根据斯坦福大学cs193p课程,2010-2011秋季(这是他们用计算器应用程序做的))制作一个接收参数的方法,即UIButton。 例如:

- (IBAction) someMethodThatDoesSomething:(UIButton *)sender;

然后根据sender.titleLabel.text制作if语句
我不知道是否有其他解决方案。希望这有帮助!

答案 4 :(得分:0)

-(IBAction) buttonPress: (id) sender {
    UIButton *pressedButton = (UIButton *)sender;
    NSString *buttonTitle = [pressedButton currentTitle];
    if ([buttonTitle isEqualToString: @"SomeTitle"]) {
        //do work for that button.
    }
}

您可以使用各种NSString方法来比较或过滤按下的按钮,并通过if或开关处理它。

答案 5 :(得分:0)

- (IBAction)myButtonAction:(id)sender {

    if ([sender tag] == 0) {
        // do something here
    }
    if ([sender tag] == 1) {
        // Do some think here
   }

}

//换句话说

- (IBAction)myButtonAction:(id)sender {

     NSLog(@"Button Tag is : %i",[sender tag]);

    switch ([sender tag]) {
    case 0:
        // Do some think here
        break;
    case 1:
       // Do some think here
         break;
   default:
       NSLog(@"Default Message here");
        break;

}

相关问题