从代码中调用 IBAction 的最佳方法是什么?

发布于 2024-09-02 08:33:22 字数 444 浏览 4 评论 0原文

举例来说,我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

困倦 2024-09-09 08:33:22

正确的方法是:

- [self functionToBeCalled:nil] 

传递一个 nil 发送者,表明它不是通过通常的框架调用的。

- [self functionToBeCalled:self]

将您自己作为发件人,这也是正确的。

选择哪一个取决于该函数的具体功能以及它期望的发送者是什么。

The proper way is either:

- [self functionToBeCalled:nil] 

To pass a nil sender, indicating that it wasn't called through the usual framework.

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.

清醇 2024-09-09 08:33:22

从语义上讲,调用IBAction 应该仅由UI 事件(例如按钮点击)触发。如果您需要从多个位置运行相同的代码,那么您可以将该代码从 IBAction 提取到专用方法中,并从两个位置调用该方法:

- (IBAction)onButtonTap:(id)sender {
    [self doSomething];
}

这允许您根据发送者(也许您可以将相同的操作分配给多个按钮,并根据 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 the IBAction into a dedicated method, and call that method from both places:

- (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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文