Search code examples
swiftuiviewuitapgesturerecognizeribaction

Remove any view from any where e.g from window


I have 2 views on the screen, one is overlayView at the bottom and introView at the top of that overlayView. When I tap(tapToContinueAction) on the screen they should both hide or remove themselves.

extension UIView {
 ....
 func hideView(view: UIView, hidden: Bool) {
    UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
        view.isHidden = hidden
    })
}
} 

class IntroScreen
 @IBAction func tapToContinueAction(_ sender: UITapGestureRecognizer) {
    self.hideView(view: self, hidden: true)
}

--

class OverlayView : UiView {
  ...
 }

In current situation i can hide introScreen only and i dont know how the other class's action can effect the overlayView at the same time and hide that view as well. Any idea?


Solution

  • You have two different classes for your views. Make an extension of your window to remove your specific views just like I have made removeOverlay and removeIntroView both these computed properties will go and search in subviews list of window and check each view with their type and remove them. Thats how you can remove any view form any where.

    class OverLayView: UIView {}
    class IntroView: UIView {
        @IBAction func didTapYourCustomButton(sender: UIButton) {
            let window = (UIApplication.shared.delegate as! AppDelegate).window!
            window.removeOverlay
            window.removeIntroView
        }
    }
    extension UIWindow {
        var removeOverlay: Void {
            for subview in self.subviews {
                if subview is OverLayView {
                    subview.removeFromSuperview()// here you are removing the view.
                    subview.hidden = true// you can hide the view using this
                }
            }
        }
        var removeIntroView: Void {
            for subview in self.subviews {
                if subview is IntroView {
                    subview.removeFromSuperview()// here you are removing the view.
                    subview.hidden = true// you can hide the view using this
                }
            }
        }
    }