0

I have a programmatically created UIButton with a UIScrollView. When this button is pressed, it triggers an action, but besides just triggering the action, I want the button to send a (int) variable to the method as well.

Here is my button:

UIButton *btn15 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn15 setTitle:@"Cool title" forState:UIControlStateNormal];
    [btn15 setFrame:CGRectMake(165, 770, 145, 145)];
    [btn15 addTarget:self action:@selector(selectFav) forControlEvents:UIControlEventTouchUpInside];
    [_scroller addSubview:btn15];

...So this is my 15th button within this scroll view. I want to write the method 'selectFav' to handle a button press. I would like each button to send to the method it's number, and then have the method print the number out to NSLog. Since this example is button 15, I want to have the the number 15 somehow passed to selectFav.

I'm assuming this is an easy thing to do, but can't seem to make it work. Thanks for any suggestions!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
jake9115
  • 3,964
  • 12
  • 49
  • 78

4 Answers4

1

You can use UIView's tag property into the button, and then take the value out of the button once it's pressed.

something like:

- (void)yourAction:(UIButton *)sender{
    NSInteger value=[sender tag];
}
J2theC
  • 4,412
  • 1
  • 12
  • 14
1

This is easy to do in BlocksKit. BlocksKit allows you to attach blocks as event handlers.

UIButton *btn15= ...;
[btn15 addEventHandler:^(id sender) {
    [self selectFav:15];
} forControlEvents:UIControlEventTouchUpInside];

- (void)mySelectFav:(NSUInteger)buttonId {
    ...
}
Sonny Saluja
  • 7,193
  • 2
  • 25
  • 39
1

This is how I would do it. Set a tag property of the button and then get to the property in button action.

-(void)myMethod
{
   UIButton *btn15 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn15 setTitle:@"Cool title" forState:UIControlStateNormal];
    [btn15 setFrame:CGRectMake(165, 770, 145, 145)];
    [btn15 addTarget:self action:@selector(selectFav:) forControlEvents:UIControlEventTouchUpInside];
    [_scroller addSubview:btn15];
    btn15.tag = 15;

}

-(void)selectFav:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSLog(@"%d", button.tag); //this will print 15. Store it in a int variable
}
Sam B
  • 27,273
  • 15
  • 84
  • 121
0

You can use the tag of the UIButton being passed as mentioned by @J2theC, or you can also add a property to UIButton: Subclass UIButton to add a property

As you are passing the UIButton to the selector, you can identify which UIButton is being passed from the tag or the property.

Also do not forget to update your addTarget method implementation to include : in the selector parameter being passed:

[btn15 addTarget:self action:@selector(selectFav:) forControlEvents:UIControlEventTouchUpInside];
Community
  • 1
  • 1
Valent Richie
  • 5,226
  • 1
  • 20
  • 21