0

我有一个标签,两个按钮。从标签一到 +1 和一到 -1。

我使用以下代码:

。H

    int counter;

    IBOutlet UILabel *count;
}

-(IBAction)plus:(id)sender;
-(IBAction)minus:(id)sender;

.m

-(IBAction)plus {

    counter=counter + 1;

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

}

-(IBAction)minus {

    counter=counter - 1;

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

}

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

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

4

1 回答 1

0

您可以连续生成按钮,将它们存储在 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
}
于 2012-09-02T20:55:33.620 回答