AlecGamble
AlecGamble

Reputation: 109

iOS UIButton in programmatically instantiated subview not firing

I have a Nib in my storyboard which is not connected to anything but I'm instantiating it as a subview thusly:

-(void)LoadCameraOverlayView
{
    CameraOverlayViewController *cameraVC = [self.storyboard instantiateViewControllerWithIdentifier:@"CameraOverlayNib"];
    cameraVC.view.userInteractionEnabled = YES;
    [self.view addSubview:cameraVC.view];
}

The UIViewController has a camera with feedback which is working fine and a button which (when I segue to the view controller also works fine.)

The button is linked to a Touch Down event and Touch Up Inside event.

When I click the button I can see it is changing visually from its default state to its focused or highlighted state however none of the code seems to be executing. If I put an NSLog in the ViewDidLoad I can see that in the console but not for the linked method. However if I segue to the view it does work.

What's going on?

I looked at other solutions but I don't think it could be that there is a view in the way or that the CGRect isn't calibrated correctly or anything since I can see the visual change when clicking the button.

Upvotes: 0

Views: 85

Answers (1)

matt
matt

Reputation: 535989

This code violates Rule One of how to use view controllers:

CameraOverlayViewController *cameraVC = [self.storyboard instantiateViewControllerWithIdentifier:@"CameraOverlayNib"];
[self.view addSubview:cameraVC.view];

You cannot simply instantiate a view controller and then add its view manually to the view hierarchy like that. There are very strict rules about this; there is an elaborate "dance" that you must do in order to add a view controller's view to your interface manually, and you are not doing the dance.

The result is that your cameraVC comes into existence, is given no place in the view controller hierarchy, and vanishes in a puff of smoke. There is thus no object for your button to talk to, and so when the button is tapped, nothing happens.

My suggestion would be: use a .xib file, not a storyboard scene, for this view; and after you have loaded it and put it into the interface, use code to configure the button so that it talks to self, your current view controller.

Upvotes: 4

Related Questions