Search code examples
iphoneiosobjective-cxcodeios6

Respond to touches on programmatically generated custom UIButtons inside UIScrollView


I have a UIScrollView full of custom UIButtons that are generated programmatically. This code executes every iteration through the loop, typically 7 times.

[cardButton
      addTarget:self
      action:@selector(buttonPressed:)
      forControlEvents:UIControlEventTouchUpInside];
[cardButton setTag:i + 100];
[self.scrollView addSubview:cardButton];

Elsewhere I have this function:

- (IBAction) buttonPressed:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSLog(@"%d", [button tag]);
}

How do I link the two? My button actually stores all the information I need from it inside its label so I really just need to detect when it is being tapped so I can respond.


Solution

  • You already linked two with this line

    [cardButton
          addTarget:self
          action:@selector(buttonPressed:)
          forControlEvents:UIControlEventTouchUpInside];
    

    Sender is returning the instance of button which you pressed.so

    - (IBAction) buttonPressed:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        NSLog(@"%d", [button tag]);
        switch (button.tag) {
            case 1:
                //Action for button with tag 1
                break;
            case 2:
                //Action for button with tag 2
                break;
    
            default:
                break;
        }
    
    
    }