在 IBAction 中拥有 (id)sender 有什么好处

发布于 2024-11-17 21:44:12 字数 292 浏览 2 评论 0原文

使用 cocoa 编码时,我注意到定义 IBAction 时不需要有 sender 参数,因此以下操作:

- (IBAction)showUserInfo:(id)sender;

可以声明为

- (IBAction)showUserInfo;

所以我想知道是否有除了发送操作的按钮/菜单项之外,还有其他好处吗?我能想到的唯一情况是很少有对象调用相同的 IBAction。还要别的吗?

When coding with cocoa I've noticed that it's not necessary to have sender parameter when defining IBAction, hence following action:

- (IBAction)showUserInfo:(id)sender;

can be declared as

- (IBAction)showUserInfo;

So I'm wondering if there is any other benefit besides having the button/menu item that sent the action? Only other situation I can think of is having few objects calling same IBAction. Anything else?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

够运 2024-11-24 21:44:12

Doc 说,

sender 参数通常标识发送操作消息的控件(尽管它可以是实际发送者替换的另一个对象)。其背后的想法类似于明信片上的寄信人地址。如果需要,目标可以向发送者询问更多信息。

如果您想要从中获取任何数据,sender 参数会有所帮助。例如,在 UISegmentControl 值发生变化时,如@Mark Adams 的回答所示。因此,如果您不需要发件人提供任何信息,则可以省略它,如 - (IBAction)showUserInfo; 示例中所示。

Doc says,

The sender parameter usually identifies the control sending the action message (although it can be another object substituted by the actual sender). The idea behind this is similar to a return address on a postcard. The target can query the sender for more information if it needs to.

The sender parameter helps if you want any data from it. For example, on UISegmentControl value change, as in @Mark Adams answer. So if you don't want any information from the sender, you can just omit it, as in your - (IBAction)showUserInfo; example.

终遇你 2024-11-24 21:44:12

当您将该方法连接到值可以更改并且您可能需要使用的 UI 对象时,使用 sender 参数会很方便。

例如,如果我将一个方法连接到 UISegmentedControl 并将其控制事件设置为 UIControlEventValueChanged,我可以使用作为 sender: 参数传递的对象来获取其选定的段索引然后根据该值在 UI 中进行更改。

-(IBAction)segmentedControlValueChanged:(id)sender
{
    UISegmentedControl *control = (UISegmentedControl *)sender;

    // Show or hide views depending on the selected index of the segmented control.
    if (control.selectedSegmentIndex == 0)
        someView.hidden = YES;
    else 
        someView.hidden = NO;
}

It can be handy to use the sender argument when you're connecting the method to UI objects whose values can change and you may need to work with.

For instance if I wired up a method to a UISegmentedControl and set it's control event to UIControlEventValueChanged, I can use the object passed as the sender: argument to obtain it's selected segment index and then, based on the value, make a change in the UI.

-(IBAction)segmentedControlValueChanged:(id)sender
{
    UISegmentedControl *control = (UISegmentedControl *)sender;

    // Show or hide views depending on the selected index of the segmented control.
    if (control.selectedSegmentIndex == 0)
        someView.hidden = YES;
    else 
        someView.hidden = NO;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文