如何在IBAction中传递参数? [英] How to Pass parameters in IBAction?

查看:76
本文介绍了如何在IBAction中传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以编程方式访问IBAction&希望通过此IBAction调用传递两个参数。
谁能建议一种简单的方法...

I am accessing IBAction programatically & want to pass two parameter with this IBAction call. Can any one suggest easy way...

推荐答案

IBAction通常由用户界面元素调用,它们可以没有任意数量的参数。

IBActions are usually called by user interface elements, and they can't have an arbitrary number of parameters.

如果要以编程方式调用操作方法,则可以通过将字典作为参数传递来滥用sender参数,并按住您想要传递的实际参数,例如:

If you want to call the action method programmatically, you could abuse the sender parameter by passing a dictionary as an argument, holding the actual arguments you want to pass, like so:

- (void) foo
{
    [self myAction: [NSDictionary dictionaryWithObject: @"bar" forKey: @"baz"]];
}

但是,我建议创建一个带有两个参数的附加方法。 IBAction可以使用适合发送者的参数来调用它,而您可以通过编程使用所需的任何参数来调用它。这可能是该代码的轮廓:

However, I would recommend creating an additional method with two parameters; the IBAction can call it with arguments appropriate to the sender, and programmatically you can call it using whatever arguments you need. This would be a possible outline for the code:

// The atual "logic" method, doing sth interesting
- (void) foo: (NSString *) s bar: (NSInteger) i
{
     // some code
}

- (IBAction) myAction: (id) sender
{
    // can be invoked by a button, or any view action
    if (sender == self.buttonX) {
        [self foo: @"x" bar: 42];
    }

    if (sender == self.buttonY) {
        [self foo: @"y" bar: 4];
    }
}

- (void) methodCallingFooBarProgrammatically
{
    [self foo: @"s" bar: 17];
}

这篇关于如何在IBAction中传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆