MultipleControllers in one view

橙三吉。 提交于 2019-12-02 20:55:43

问题


I am basically trying to add two view controllers to one controller.

I created a view based application called "MultipleViews". After that i add two controller classes "RedView.h" and "BlueView.h" with their own xibs. I am able to add the views of both the controllers to "MutipleViewsViewController" by the method [self.view addSubview:red.view]. Both the views are displayed properly. The problem is when I add a button to the red and blue controllers. Whenever I click the button it says unrecognized selector sent to instance even though I linked the buttons with their functions properly. Am i missing something here?

here is the code:

MultipleViewsViewController.h

#import <UIKit/UIKit.h>

@interface MutipleViewsViewController : UIViewController {

}

@end

MutipleViewsViewController.m

-

 (void)viewDidLoad {
    [super viewDidLoad];

    RedView *red = [[RedView alloc]init];

    red.view.frame = CGRectMake(0, 0, 320, 240);

    [self.view addSubview:red.view];

    BlueView *blue = [[BlueView alloc]init];

    blue.view.frame = CGRectMake(0, 240, 320, 240);

    [self.view addSubview:blue.view];



}

RedView.h

#import <UIKit/UIKit.h>


@interface RedView : UIViewController {

}

-(IBAction)buttonPressed;

@end

BlueView.h

#import <UIKit/UIKit.h>


@interface BlueView : UIViewController {

}

-(IBAction)buttonPressed;

@end

The buttons are linked to the buttonPressed method through IB. The message i get when i click the button in the red view is:

MutipleViews[1865:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RedView buttonPressed]: unrecognized selector sent to instance 0x4e12500'

Sorry for not being clear earlier.




回答1:


The IBActions typically take an input parameter of type id. So your buttonPressed action should look like

-(IBAction)buttonPressed:(id)sender;

When this action is actually called, a reference to the control which calls it (in this case the button) is passed.

When calling it programatically, you can send the controller's object (self) to it.




回答2:


Without seeing the code it is tough to say exactly what the problem is. That said, it is most definitely a target-action related problem. When the button is clicked, it sends its target an action message. Whatever target you have assigned your button does not respond to the action you are trying to send to it.

Perhaps you didn't implement the action on the target you desire? Perhaps you entered the wrong target or action name by mistake (or connected them incorrectly in interface builder)?



来源:https://stackoverflow.com/questions/5101080/multiplecontrollers-in-one-view

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