Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove subview of uiwindow?

i want to remove a view from uiwindow,so i nslog in appdelegate method,it says window's subviews count as two NSLog(@" %d",[[self.window subviews] count]); so how can i remove that subviews from window,if i remove that subviews i have tab bar controller to be continued...

- (void) GetUserCompleted

{
    NSLog(@"   %@",[[self.window subviews] objectAtIndex:0]);   
    NSLog(@"   %@",[[self.window subviews] objectAtIndex:1]); 
}
like image 579
Ahamed Aathil Avatar asked Feb 21 '13 07:02

Ahamed Aathil


2 Answers

You can remove the a single subview using the following code.

[subview_Name removeFromSuperview];

if you want to remove all subviews form the view then use this.

NSArray *subViewArray = [self.window subviews];
for (id obj in subViewArray)
{
    [obj removeFromSuperview];
}
like image 86
Vinayak Kini Avatar answered Sep 29 '22 03:09

Vinayak Kini


Swift version of @Maddy 's answer:

//create view then add a tag to it. The tag references the view
var myNewView = UIView()
myNewView.tag = 100

//add the  view you just created to the window
window.addSubview(myNewView)

//remove the view you just created from the window. Use the same tag reference
window.viewWithTag(100)?.removeFromSuperview

Update

Here is another way to remove a UIView without using a tag from the window. The key is the view has to be an instance property.

lazy var myNewView: UIView = {
    let view = UIView()
    return view
}()

viewDidLoad() {

    guard let window = UIApplication.shared.windows.first(where: \.isKeyWindow) else { return }

    window.addsubView(myNewView)
}

// call this in deinit or wherever you want to remove myNewView
func removeViewFromWindow() {

    guard let window = UIApplication.shared.windows.first(where: \.isKeyWindow) else { return }

    if myNewView.isDescendant(of: window) {
        print("myNewView isDescendant of window")
    }

    for view in window.subviews as [UIView] where view == myNewView {
        view.removeFromSuperview()
        break
    }

    if myNewView.isDescendant(of: window) {
        print("myNewView isDescendant of window")
    } else {
        print("myNewView is REMOVED from window") // THIS WILL PRINT
    }
}

deinit() {
    removeViewFromWindow()
}
like image 42
Lance Samaria Avatar answered Sep 29 '22 05:09

Lance Samaria