How to Pass parameters in IBAction?

你说的曾经没有我的故事 提交于 2019-12-12 00:46:36

问题


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


回答1:


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

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"]];
}

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];
}



回答2:


You can pass an array in the IBAction method like this:

-(IBAction)method:(id)sender
{
   [sender objectAtIndex:0];
}

or you can do it like this:

-(IBAction)methodName:(NSString *)stringName:(NSString*)stringName2
{
  // You can pass an array and even a dictionary
}



回答3:


IBAction method follow a spesific pattern either

- (IBAction)action:(id)sender;

or

- (IBAction)action:(id)sender forEvent:(UIEvent *)event;

where sender is the UI object that sends the event, and event being the UIEvent itself.

If you are not sending these arguments then you don't want an IBAction method. Define a normal method that takes the two arguments you want and if you IBAction methods need to call it as well then do that. IBAction methods are defined as IBAction so that interface builder can find them in your code, so there is no reason to define an IBAction method that does not follow the pattern above.




回答4:


the IBAction methods could receive two parameters about the sender object and the touch event, you cannot "pass" anything, you can receive only these via:

- (IBAction)action
- (IBAction)action:(id)sender
- (IBAction)action:(id)sender forEvent:(UIEvent *)event

you could use only the sender's tag property to pass a custom identifier as NSInteger.


HERE IS THE POINT

everything else what you would like to "pass" must be exists on your Model layer already! if you know what it is...

therefore, you can reach your datas from the Model layer after you receive the action.



来源:https://stackoverflow.com/questions/12068712/how-to-pass-parameters-in-ibaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!