简体   繁体   English

以编程方式触发按钮点击事件?

[英]Programmatically fire button click event?

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. 我在UIView中放置了一个按钮,在特定情况下,我想通过代码单击按钮,而不是手动作为用户。 Is it possible in iOS development? iOS开发有可能吗? Please provide your suggestions and guide me how to do that. 请提供您的建议并指导我如何做到这一点。

Thanks. 谢谢。

有点像Ken的答案,但更灵活,因为如果您更改或添加多个按钮,它会跟踪按钮的实际操作。

[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. Richie的建议不起作用,因为按钮仅在不可察觉的时间内突出显示(如果有的话)。

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. 如果你在谈论UIButton,你可以调用UIButton在点击时调用的方法。 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尝试上面的代码。

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

MeFirst is the method i have created. MeFirst是我创造的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM