Programmatically fire button click event?

IosObjective CIphone

Ios Problem Overview


Is there a way to programmatically fire a button click event? I have a button placed there in an UIView, and in a particular scenario i want to click the button via code, not manually as a user. Is it possible in iOS development? Please provide your suggestions and guide me how to do that.

Thanks.

Ios Solutions


Solution 1 - Ios

Sort of like Ken's answer, but more flexible as it'll keep track of the buttons actual actions if you change them or add more than one.

[button sendActionsForControlEvents:UIControlEventTouchUpInside];

Solution 2 - Ios

I had the same issue as above. I would have posted a comment, but my reputation isn't high enough. So, I will instead post the full answer:

[btn setHighlighted:YES];
[btn sendActionsForControlEvents:UIControlEventTouchUpInside];
[btn performSelector:@selector(setHighlighted:) withObject:NO afterDelay:0.25];

This will programmatically hit the button and highlight it for a seemingly normal amount of time. Richie's suggestion didn't work as the button was only highlighted (if at all) for an imperceptible amount of time.

Solution 3 - Ios

Why not just execute the code that executes when the user presses the button?

-(void)myMethod
{
   // do stuff
}

-(IBAction)myButtonClick:(id)sender
{
    [self myMethod];
}

-(void)clickMyButton
{
    [self myMethod];
    // OR
    [self myButtonClick:nil];
}

Solution 4 - Ios

If you're talking about a UIButton, you can just call the same method that the UIButton is calling when it is tapped. For example:

[self myButtonsTargetMethod];

Solution 5 - Ios

Yes,

[_button setHighlighted:YES];
[_button sendActionsForControlEvents:UIControlEventTouchUpInside];
[_button setHighlighted:NO];

But the problem here is you will not be able to see those event because its too fast . so what you can do is try the above code with NSTimer .

NSTimer *quick = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(MeFirst:) userInfo:nil repeats:NO];

MeFirst is the method i have created.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGetsyView Question on Stackoverflow
Solution 1 - IosZaky GermanView Answer on Stackoverflow
Solution 2 - IosChad HineView Answer on Stackoverflow
Solution 3 - IosEvan MulawskiView Answer on Stackoverflow
Solution 4 - IosKen PespisaView Answer on Stackoverflow
Solution 5 - IosBharat jainView Answer on Stackoverflow