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
The answer to your question is in the way you declare the target of the action for the button
If this piece of code is located in
firstViewController.mand you say that the target isself, it means the compiler must look for the method in thefirstViewControllerclass. So to fix this problem you need to point thetargetof your button action to point to theviewControllerclass. By the way at this point I would like to mention that your naming SUCKS, if you subclassUIViewControllerdon’t call itViewController, make it more meaningful.The actual fix.
make a global property that will point to
ViewControllerobject and call itvc.