Reputation: 5799
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.
Upvotes: 0
Views: 3581
Reputation: 151
In Swift 3.2
let storybord = UIStoryboard.init(name: "Main", bundle: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let vc = storybord.instantiateViewController(withIdentifier: "IDProgressVC")
as IDProgressVC
currentVC = vc.view
appDelegate.window?.addSubview(currentVC!)
// Remove it
currentVC?.removeFromSuperview()
appDelegate.window?.setNeedsLayout()
currentVC = nil
Upvotes: 1
Reputation: 3875
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;
Upvotes: 3
Reputation: 27438
Make sure that both vc
is same object not different.
I mean when you add vc.view at that time you alloc and init object and when you remove then again you alloc and init then both are different instance of same class.
So it's better to declare instance variable or property like,
ProgressVC *vc
and alloc it only once and add or remove this vc from window.
It may solve your issue i think.
Upvotes: 1