2012-09-02 21 views
0

하나의 레이블, 두 개의 단추가 있습니다. 라벨에서 1 대 1 및 1 대 -1. 나는 다음 코드를 사용하십시오하나의 IBAction 다중 단추 및 레이블

:

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의 라벨 (계산)에 연결되어있다 .H

. 지금 내 질문에. 이와 같은 버튼과 라벨을 더 갖고 싶다면 어떻게해야합니까? 코드를 복사하여 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

답변 해 주셔서 감사합니다. 이 새로운 코드에 내가 궁금한가요? .m? 이 코드를 붙여 넣는 동안 많은 오류가 발생합니다. – Kallen

+0

@Kallen 물론 .m 파일에 있습니다. 복사하여 붙여 넣지 마십시오. 이것은 1 : 1 작업 코드가 아닌 예제입니다. –

관련 문제