W S
W S

Reputation: 115

iOS crash when pressing button from manually loaded viewcontroller

I programmatically instantiate a UIViewController from a xib, add it as a child VC to an existing main view, then add the child VC's view (which contains a button) to my main view. The view with the button displays just fine, but when I press the button, the app crashes with an "unrecognized selector" message.

I created the XIB by creating a custom subclass of a UIViewController ( File - New - Cocoa Touch class, selecting a subclass of UIViewController, and asking Xcode to also generate the XIB file). I then placed a button on that XIB, and hooked it up to the newly created UIViewController subclass. The XIB file's owner is set to the name of the new class.

So it looks to me like the ButtonPushed action message doesn't get send to my custom UIVC, and is going instead to the generic UIViewController - which rightly doesn't understand the ButtonPushed message.

How do I make sure that the action message sent when the button is pressed in fact goes to my custom UIViewController?

This is the code in my awakeFromNib method for the main view (main view is from Main.storyboard):

UIViewController *vc2 = [[UIViewController alloc] initWithNibName:@"ButtonVC" bundle:nil];

vc2.view.frame = CGRectMake(90, 140, 50, 200); //dont obscure the main view completely.

[self addChildViewController:vc2];
[self.view addSubview:vc2.view];  //vc2.view has a button, which shows up fine

[vc2 didMoveToParentViewController:self];

I've managed to get the equivalent functionality by creating a storyboard just with the button, and programmatically loading that, then instantiating my buttonViewController, adding it and its view as a child VC to my main view. That works just fine, but it seems to me like I should be able to achieve this with "only" a XIB.

Upvotes: 0

Views: 159

Answers (1)

Maciek Czarnik
Maciek Czarnik

Reputation: 6191

Try this:

UIViewController *vc2 = [[ButtonVC alloc] initWithNibName:@"ButtonVC" bundle:nil];

And also make sure that the class in your xib for the view controller is set properly (see my answer here)

Upvotes: 2

Related Questions