Maduranga E
Maduranga E

Reputation: 1689

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?

Upvotes: 2

Views: 7117

Answers (3)

danh
danh

Reputation: 62686

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.

Upvotes: 3

Kjuly
Kjuly

Reputation: 35191

As you want:

[self handleSingleTap:self.view];

sender can by anything as you like, it's id type. You can also send a UIButton instance with a tag.

Upvotes: 1

Scar
Scar

Reputation: 3480

You don't have to call it, cause you use the methods as as Selector to the UITapGestureRecognizer, so it will call automatically when there is a tap on the app. Also, if you can recognize the colon after the name of the methods in the action:@selector(handleSingleTap:), it means that send an object of type UITapGestureRecognizer to the method. If you don't want to send any object you just delete the colon and the (id)sender from the method.

Upvotes: 1

Related Questions