Search code examples
iosselectoribaction

How to call an IBAction method with id sender programmatically?


I have the following IBAction method in my code.

-(IBAction)handleSingleTap:(id)sender
{
    // need to recognize the called object from here (sender)
}


UIView *viewRow = [[UIView alloc] initWithFrame:CGRectMake(20, y, 270, 60)];
// Add action event to viewRow
UITapGestureRecognizer *singleFingerTap = 
[[UITapGestureRecognizer alloc] initWithTarget:self 
                                        action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];
[singleFingerTap release];
//
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(5,30, 100, 20)];
infoLabel.text = @"AAAANNNNVVVVVVGGGGGG";
//[viewRow addSubview:infoLabel];
viewRow.backgroundColor = [UIColor whiteColor];

// display the seperator line 
UILabel *seperatorLablel = [[UILabel alloc] initWithFrame:CGRectMake(0,45, 270, 20)];
seperatorLablel.text = @" ___________________________";
[viewRow addSubview:seperatorLablel];
[scrollview addSubview:viewRow];

How to call the IBAction method while allowing it to receive the caller object of that method?


Solution

  • The method signature is common to gesture recognizer and UIControls. Both will work without warning or error. To determine the sender, first determine the type...

    - (IBAction)handleSingleTap:(id)sender
    {
    // need to recognize the called object from here (sender)
        if ([sender isKindOfClass:[UIGestureRecognizer self]]) {
            // it's a gesture recognizer.  we can cast it and use it like this
            UITapGestureRecognizer *tapGR = (UITapGestureRecognizer *)sender;
            NSLog(@"the sending view is %@", tapGR.view);
        } else if ([sender isKindOfClass:[UIButton self]]) {
            // it's a button
            UIButton *button = (UIButton *)sender;
            button.selected = YES;
        }
        // and so on ...
    }
    

    To call it, call it directly, let a UIControl it's connected to call it, or let the gesture recognizer call it. They'll all work.