Search code examples
iosuiviewcontrolleruinavigationcontrolleruibuttonxib

Getting black screen when trying to remove ViewController from display in iOS


I have an iOS application using storyboards where I display a view controller that I create from an .xib file to the user. This view controller accepts some user input, but I then have to dismiss it and return to the main application. I am able to display the view controller, which also has a button that calls a method to dismiss the view controller. My problem is that after the user presses the button to go back to the main application, the entire screen goes black. Here is my code for the button from the .xib view controller that is trying to remove itself from the display:

- (IBAction)myButtonAction:(id)sender {
    
    [self.view removeFromSuperview];
    
}

Here is the code from my main application's view controller which calls the .xib view Controller in the first place:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    _nextView = [[NextLandscapeViewController alloc] initWithNibName:@"NextLandscapeViewController" bundle:nil];
    [_nextView setDelegate:(id)self];
    NextNavigationController *navigationController = [[NextNavigationController alloc] initWithRootViewController:_nextView];
    [self presentViewController:navigationController animated:YES completion:nil];

}

NextNavigationController is a subclass of UINavigationController which I do for the purpose of loading _nextView in landscape mode instead of portrait mode. This part is working fine. My concern now is dismissing this viewController after the user is finished working with it, and return back to the calling view controller in the main application.

Is there any reason why my screen is black? How I can resolve this issue?


Solution

  • Don't use removeFromSuperview, use [self dismissViewControllerAnimated:YES completion:nil]; Just like you use a pop to undo a push, you use dismissViewController to undo a presentViewController. The reason you get a black screen is because presenting a view controller removes the view of the presenting view controller from the window's hierarchy. So, when you remove the view from the superview, there's nothing underneath but the window.