获取UIButton的标签和标签较小的标签

时间:2014-02-26 18:32:16

标签: ios objective-c 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)

是不是可能?

谢谢大家

1 个答案:

答案 0 :(得分: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];
   }
}