Programmatically fire button click event?
Is there a way to programmatically f开发者_StackOverflow中文版ire 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.
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];
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.
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];
}
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];
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.
精彩评论