ios 从代码内调用 IBAction 的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2889408/
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
What's the best way to call an IBAction from with-in the code?
提问by iwasrobbed
Say for instance I have an IBActionthat is hooked up to a UIButtonin interface builder.
举例来说,我有一个IBAction,它连接到界面构建器中的UIButton。
- (IBAction)functionToBeCalled:(id)sender
{
// do something here
}
With-in my code, say for instance in another method, what is the best way to call that IBAction?
在我的代码中,例如在另一种方法中,调用IBAction的最佳方法是什么?
If I try to call it like this, I receive an error:
如果我尝试这样称呼它,我会收到一个错误:
[self functionToBeCalled:];
But, if I try to call it like this (cheating a bit, I think), it works fine:
但是,如果我尝试这样称呼它(我认为有点作弊),它可以正常工作:
[self functionToBeCalled:0];
What is the proper way to call it properly?
正确调用它的正确方法是什么?
回答by Jakob Borg
The proper way is either:
正确的方法是:
- [self functionToBeCalled:nil]
To pass a nil sender, indicating that it wasn't called through the usual framework.
传递一个 nil 发送者,表明它不是通过通常的框架调用的。
OR
或者
- [self functionToBeCalled:self]
To pass yourself as the sender, which is also correct.
把自己当作发件人,这也是正确的。
Which one to chose depends on what exactly the function does, and what it expects the sender to be.
选择哪一个取决于函数的作用是什么,以及它期望发送者是什么。
回答by Cristik
Semantically speaking, calling an IBAction
should be triggered by UI events only (e.g. a button tap). If you need to run the same code from multiple places, then you can extract that code from the IBAction
into a dedicated method, and call that method from both places:
从语义上讲,调用 anIBAction
应该仅由 UI 事件触发(例如点击按钮)。如果您需要从多个地方运行相同的代码,那么您可以将该代码从 中提取IBAction
到一个专用方法中,并从两个地方调用该方法:
- (IBAction)onButtonTap:(id)sender {
[self doSomething];
}
This allows you to do extra logic based on the sender (perhaps you might assign the same action to multiple buttons and decide what to do based on the sender
parameter). And also reduces the amount of code that you need to write in the IBAction
(which keeps your controller implementation clean).
这允许您根据发送者执行额外的逻辑(也许您可以将相同的操作分配给多个按钮并根据sender
参数决定要执行的操作)。并且还减少了您需要编写的代码量IBAction
(这使您的控制器实现保持干净)。