ios 以编程方式触发按钮单击事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5625651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically fire button click event?
提问by Getsy
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.
有没有办法以编程方式触发按钮单击事件?我在 UIView 中放置了一个按钮,在特定情况下,我想通过代码单击该按钮,而不是作为用户手动单击。在iOS开发中可以吗?请提供您的建议并指导我如何做到这一点。
Thanks.
谢谢。
回答by Zaky German
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.
有点像 Ken 的回答,但更灵活,因为如果您更改按钮或添加多个按钮,它将跟踪按钮的实际操作。
[button sendActionsForControlEvents:UIControlEventTouchUpInside];
回答by Chad Hine
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 的建议没有奏效,因为按钮只是在不知不觉中突出显示(如果有的话)。
回答by Evan Mulawski
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];
}
回答by Bharat jain
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 是我创建的方法。
回答by Ken Pespisa
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:
如果你在谈论一个 UIButton,你可以调用 UIButton 被点击时调用的相同方法。例如:
[self myButtonsTargetMethod];