Objective c 一个iAction多个按钮和标签

Objective c 一个iAction多个按钮和标签,objective-c,xcode,Objective C,Xcode,我有一个标签,两个按钮。标签上的一对+1和一对-1 我使用以下代码: h m 这两个按钮链接到IB中的标签(计数)。 现在回答我的问题。如果我想有更多这样的按钮和标签,我该怎么做? 我知道我可以复制代码并在IB中重新链接,但这需要很长时间。 当按钮链接到计数标签时,只在IB中复制它们是不起作用的,按钮起作用,但它会计数第一个标签。我需要数一数每一个标签 那么,我怎样才能做到这一点并节省时间呢?这其中有很多。你可以按顺序生成按钮,将它们存储在NSArray中,并对标签执行同样的操作。然后可以使用数

我有一个标签,两个按钮。标签上的一对+1和一对-1

我使用以下代码:

h

m

这两个按钮链接到IB中的标签(计数)。 现在回答我的问题。如果我想有更多这样的按钮和标签,我该怎么做? 我知道我可以复制代码并在IB中重新链接,但这需要很长时间。 当按钮链接到计数标签时,只在IB中复制它们是不起作用的,按钮起作用,但它会计数第一个标签。我需要数一数每一个标签


那么,我怎样才能做到这一点并节省时间呢?这其中有很多。

你可以按顺序生成按钮,将它们存储在NSArray中,并对标签执行同样的操作。然后可以使用数组中的索引将它们关联起来

// Assuming a view controller
@interface MyVC: UIViewController {
    NSMutableArray *buttons;
    NSMutableArray *labels;
}

// in some initialization method
buttons = [[NSMutableArray alloc] init];
labels = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfButtonsAndLabels; i++) {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // configure the button, then
    [self.view addSubview:btn];
    [buttons addObject:btn];

    UILabel *lbl = [[UILabel alloc] initWithFrame:aFrame];
    // configure the label, then
    [self.view addSubview:lbl];
    [labels addObject:lbl];
    [lbl release];
}

- (void)buttonClicked:(UIButton *)sender
{
    NSUInteger index = [buttons indexOfObject:sender];
    UILabel *label = [labels objectAtIndex:index];

    // use index, sender and label to do something
}
//假设为视图控制器
@接口MyVC:UIViewController{
NSMUTABLEARRY*按钮;
NSMutableArray*标签;
}
//在某些初始化方法中
按钮=[[NSMutableArray alloc]init];
labels=[[NSMutableArray alloc]init];
对于(int i=0;i
谢谢您的回答。我是新来的,不知道我是不是把这个密码放在这里了?在.m?粘贴此代码时,我遇到了许多错误。@Kallen当然在.m文件中。不要复制粘贴-这是一个示例,不是1:1工作代码。
-(IBAction)plus {

    counter=counter + 1;

    count.text = [NSString stringWithFormat:@"%i",counter];

}

-(IBAction)minus {

    counter=counter - 1;

    count.text = [NSString stringWithFormat:@"%i",counter];

}
// Assuming a view controller
@interface MyVC: UIViewController {
    NSMutableArray *buttons;
    NSMutableArray *labels;
}

// in some initialization method
buttons = [[NSMutableArray alloc] init];
labels = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfButtonsAndLabels; i++) {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // configure the button, then
    [self.view addSubview:btn];
    [buttons addObject:btn];

    UILabel *lbl = [[UILabel alloc] initWithFrame:aFrame];
    // configure the label, then
    [self.view addSubview:lbl];
    [labels addObject:lbl];
    [lbl release];
}

- (void)buttonClicked:(UIButton *)sender
{
    NSUInteger index = [buttons indexOfObject:sender];
    UILabel *label = [labels objectAtIndex:index];

    // use index, sender and label to do something
}