Ilario
Ilario

Reputation: 6079

get tag of UIButton and those with smaller tags

I'm not understanding if what I'm trying to do is possible or not.

I am creating buttons in for loop:

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];
}

and after in method touchButton i get the tag of touched button

-(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

   }
}

in the last loop i want to select the buttons that have the tag less than that touched (in this case 3,2,1)

is it possible or not???

thanks everybody

Upvotes: 0

Views: 71

Answers (1)

Eric
Eric

Reputation: 5681

All you need is viewWithTag: like so:

-(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];
   }
}

Upvotes: 5

Related Questions