从代码中调用 IBAction 的最佳方法是什么?
举例来说,我有一个IBAction,它连接到界面生成器中的UIButton。
- (IBAction)functionToBeCalled:(id)sender
{
// do something here
}
在我的代码中,例如在另一种方法中,调用该 IBAction 的最佳方法是什么?
如果我尝试这样调用它,我会收到一个错误:
[self functionToBeCalled:];
但是,如果我尝试这样调用它(我认为有点作弊),它工作得很好:
[self functionToBeCalled:0];
正确调用它的正确方法是什么?
Say for instance I have an IBAction that is hooked up to a UIButton in interface builder.
- (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?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正确的方法是:
传递一个 nil 发送者,表明它不是通过通常的框架调用的。
或
将您自己作为发件人,这也是正确的。
选择哪一个取决于该函数的具体功能以及它期望的发送者是什么。
The proper way is either:
To pass a nil sender, indicating that it wasn't called through the usual framework.
OR
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.
从语义上讲,调用
IBAction
应该仅由UI 事件(例如按钮点击)触发。如果您需要从多个位置运行相同的代码,那么您可以将该代码从 IBAction 提取到专用方法中,并从两个位置调用该方法:这允许您根据发送者(也许您可以将相同的操作分配给多个按钮,并根据
sender
参数决定要执行的操作)。并且还减少了您需要在 IBAction 中编写的代码量(这使您的控制器实现保持干净)。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 theIBAction
into a dedicated method, and call that method from both places: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 theIBAction
(which keeps your controller implementation clean).