2012-09-02 72 views
0

我有一个标签,两个按钮。一个是+1,另一个是标签-1。一个IBAction多个按钮和标签

我用下面的代码:

.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中复制它们,按钮可以工作,但它会计算第一个标签。我需要统计每个标签。

那么,我该如何做到这一点,节省时间?它会是很多这些。

回答

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 
} 
+0

谢谢你的回答。即时通讯新的这个,并想知道我把这个代码?在他们中?粘贴此代码时出现很多错误。 – Kallen

+0

@Kallen当然在.m文件中。并且不要复制粘贴 - 这是一个例子,而不是1:1的工作代码。 – 2012-09-03 04:30:20