从UIWindow中删除UIViewController的视图

时间:2016-06-29 13:25:08

标签: ios objective-c uiwindow

当用户点击添加按钮时,我在UIWindow上添加视图。现在,如果用户再次点击添加按钮,我想首先删除该视图并重新添加。

我已使用此代码在UIWindow上添加视图:

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

对于删除我已尝试过此代码:

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

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:3)

试试这个

// 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;

答案 1 :(得分:1)

确保vc两个相同的对象没有区别。

我的意思是当你在你添加vc.view时你分配和init对象,当你再次删除时你分配和init然后两者都是同一个类的不同实例。

因此,最好声明实例变量或属性,如

ProgressVC *vc并只分配一次,然后在窗口中添加或删除此vc。

我认为这可能会解决您的问题。

答案 2 :(得分:0)

在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