0

我可能在这里缺少基础知识...有没有办法使用 Xcode 4.2 中的 Interface Builder 一次将多个对象链接到一个方法?

我在 UIView 中设置了大量的 UIButton。他们都只调用一种方法(比方说- (IBAction)buttonPushed:(UIButton *)aButton),该方法应该根据发件人执行不同的操作。我想不出一种方法一次将它们全部与我的方法联系起来。任何建议将不胜感激...

注意我在 Snow Leopard 上使用 Xcode 4.2,没有情节提要。

4

3 回答 3

0

这应该只是工作。也就是说,你

  1. 定义您的 IBAction
  2. 您将“内部修饰”(或其他所需的操作)附加到每个按钮的方法
  3. 您在每个按钮上设置标签值
  4. 在您的 IBAction 中,您从发件人那里获取标签并采取相应措施

    - (IBAction)buttonPressed:(id)sender;
    {
        NSInteger tag = [sender tag];
        // switch statement or some other check against tag value
    }
    
于 2012-04-06T22:58:13.810 回答
0

for 循环可能是个好主意。保留按钮的 NSArray 并执行以下操作:

for (int i = 0; i < [myArray count];  i++) {
    [(UIButton*)[myArray objectAtIndex:i] addTarget:self action:@selector(buttonPushed:) forControlEvents:UIControlEventTouchUpInside];
    [(UIButton*)[myArray objectAtIndex:i]setTag:i];
}

(来自我的 iPhone,这是我能做的最好的。它有点粗糙,可能无法编译,但你明白了要点)。

于 2012-04-06T23:36:33.470 回答
0

在 Xcode 4.2 中使用 IB 一次链接多个对象似乎是不可能的。

正如 Phillip Mills 首次建议的那样,我的代码中出现了一个 for 循环(+1 对他的评论)。

这是我的代码:

for (UIButton *aButton in [self.view subviews]) {
    [aButton addTarget:self
                action:@selector(buttonPushed:)
      forControlEvents:UIControlEventTouchUpInside];
}

谢谢大家的帮助!!!

于 2012-04-08T06:58:11.177 回答