Home > Back-end >  How to remove view from window when another view closes?
How to remove view from window when another view closes?

Time:05-14

So I have a custom view and inside that custom view I present another view like this

UIApplication.shared.keyWindow!.addSubview(self.customView2)

it's a dropdown menu, so I need to have it on top of everything and outside of my custom view bounds, so question is, can I remove it from the window when my custom view moves out? I tried func willMove(toWindow newWindow: UIWindow?) and it's working but with a delay, which is undesirable.

CodePudding user response:

If you don't want to delay to remove your customView, you can use removeFromSuperview()

func doSomething() {
   customView2 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
   customView2?.backgroundColor = UIColor.blue
   UIApplication.shared.keyWindow!.addSubview(customView2!) // Your custom view is on Screen now

   //Your code ...

   customView2?.removeFromSuperview() //Time to remove your custom view from screen directly
}


Updated

You want to remove your custom view if user moves forward or backward in the navigation controller when it is in screen.

The best way is using UIViewController override func.

viewWillDisappear override func is called when active View Controller removes from the screen.

So you should use customView2?.removeFromSuperview() in the viewWillDisappear override func.

override func viewWillDisappear(_ animated: Bool) {
   super.viewWillDisappear(animated)
   customView2?.removeFromSuperview()
}

In this way, if the user moves forward or backward, your custom view will disappear from the screen.

  • Related