Search code examples
iosobjective-cuiwindow

Remove view of UIViewController from UIWindow


When user click on add button, I'm adding view on UIWindow. Now If user clicks on add button again I want to first remove that view and add it again.

I have used this code to add view on UIWindow :

ProgressVC *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"IDProgressVC"];
[[[[UIApplication sharedApplication] delegate]window] addSubview:vc.view];

For Remove I have tried this code :

[vc.view removeFromSuperview];
[[[[UIApplication sharedApplication] delegate]window] setNeedsLayout];
vc = nil;

Any help will be appreciated.


Solution

  • Try This

    // Make this global property
    
    @property(nonatomic, strong) UIView * currentView;
    
    //store the view in gloabal property
    ProgressVC *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"IDProgressVC"];
    currentView = vc.view;
    [[[[UIApplication sharedApplication] delegate]window] addSubview:currentView];
    
    //remove it 
    [currentView removeFromSuperview];
    [[[[UIApplication sharedApplication] delegate]window] setNeedsLayout];
    currentView = nil;