user1015777 user1015777 - 3 months ago 18
iOS Question

Calling IBAction declared in other class

I am trying to create an app for the iPhone and I have a main viewController and a number of other viewControllers. This is because it is a multiview application.

In the ViewController.h and ViewController.m files I have created all my IBActions because they will be shared by all the other views.

Now in firstViewController.m I have created a custom button using the following code:

UIButton *settingsButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
settingsButton.frame = CGRectMake(110.0, 360.0, 100.0, 30.0);
[settingsButton setTitle:@"Play" forState:UIControlStateNormal];
settingsButton.backgroundColor = [UIColor clearColor];
[settingsButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
UIImage *buttonImageNormal = [UIImage imageNamed:@"setButtonNormal.png"];
UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[settingsButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
UIImage *buttonImagePressed = [UIImage imageNamed:@"setButtonPressed.png"];
UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[settingsButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
[settingsButton addTarget:self action:@selector(loadSettingsView) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:settingsButton];


As you can see the action is called "loadSettingsView" which I have correctly declared in ViewController. But it does not work and this is because the above code is in firstViewController.m and NOT in ViewController.m where the IBAction is declared.
Note I have moved the above code in ViewController and the action works, therefore is not a problem of the action. The problem is that I cannot find a way to access the action that has been declared in a different class than the one I am working on.

Can anyone please help me with that?

Thanks a lot

Answer Source

The answer to your question is in the way you declare the target of the action for the button

[settingsButton addTarget:self action:@selector(loadSettingsView) forControlEvents:UIControlEventTouchUpInside];

If this piece of code is located in firstViewController.m and you say that the target is self, it means the compiler must look for the method in the firstViewController class. So to fix this problem you need to point the target of your button action to point to the viewController class. By the way at this point I would like to mention that your naming SUCKS, if you subclass UIViewController don't call it ViewController, make it more meaningful.

The actual fix.

make a global property that will point to ViewController object and call it vc.

[settingsButton addTarget:vc action:@selector(loadSettingsView) forControlEvents:UIControlEventTouchUpInside];