Reputation: 4905
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.
Upvotes: 126
Views: 103422
Reputation: 439
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.
Upvotes: 1
Reputation: 211
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.
Upvotes: 13
Reputation: 14334
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];
Upvotes: 316
Reputation: 55354
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];
}
Upvotes: 8
Reputation: 22284
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];
Upvotes: 1