2014-02-26 76 views
0

我不明白,如果我想要做什麼是可能的或不。獲取標籤的UIButton和那些更小的標籤

我在for循環創建按鈕:

CGRect rect2 = CGRectMake(50, 230, 40, 40); 

for (int i = 0; i<5; i++) { 

    NSString *stringI = [NSString stringWithFormat:@"%d",i+1]; 
    NSString *stringItouch = [NSString stringWithFormat:@"%dselected",i+1]; 

    UIButton *button = [[UIButton alloc] init]; 
    [button setBackgroundImage:[UIImage imageNamed:stringI] forState:UIControlStateNormal]; 
    [button setBackgroundImage:[UIImage imageNamed:stringItouch] forState:UIControlStateSelected]; 
    [button addTarget:self action:@selector(touchButton:) forControlEvents:UIControlEventTouchUpInside]; 
    button.tag = i+1; 

    button.frame = rect2; 
    rect2.origin.x = rect2.origin.x + 45; 

    [scrollView addSubview:button]; 
} 

和之後方法touchButton我在最後一個循環得到觸摸操作的按鈕

-(void)touchButton:(id)sender { 

    UIButton *buttonSender = sender; 
    buttonSender.selected = YES; 
    NSLog(@"button tag %@",buttonSender.tag); 

    for (int i = buttonSender.tag-1; i>0; i--) { 

     NSLog(@"int = %d",i); 
     //for example if buttonSender.tag is 4, in this way i have 3,2,1 

    } 
} 

的標籤,我想選擇有按鈕標籤小於觸摸(在這種情況下3,2,1)

是否有可能?

謝謝大家

回答

5

所有你需要的是viewWithTag:就像這樣:

-(void)touchButton:(id)sender { 

    UIButton *buttonSender = sender; 
    buttonSender.selected = YES; 
    NSLog(@"button tag %@",buttonSender.tag); 

    for (int i = buttonSender.tag-1; i>0; i--) { 

     NSLog(@"int = %d",i); 
     //for example if buttonSender.tag is 4, in this way i have 3,2,1 

     /* Add this line */ 
     UIButton *tempButton = (UIButton *)[scrollView viewWithTag:i]; 
    } 
} 
+0

謝謝您的回答,我想和它的作品!謝謝 – Ilario

+0

@伊拉里奧:不要忘記接受答案......我認爲你正在等待10分鐘;) –

+0

@llario真棒,很高興它的作品! – Eric