iosswiftswift3subviewssuperview

IOS swift how can I Check between remove super view or dismissing it in subviews


I have a dilemma that I can not seem to solve correctly . I have a Main_Page then different subviews such as Menu_Subview and Profile_Subview . My issue is that I do not know whether to use Dismiss or remove fromsuperview and that is leading to the app crashing . For example

if I go from Main_Page to Profile_Subview then I can go back like this and it works

   @IBAction func backAction(_ sender: UIButton) {
       if let viewWithTag = self.view {
            viewWithTag.removeFromSuperview()

        }  
    }

if I go from Main_Page to Menu_Subview to Profile_Subview then I can't use the code above because it crashes and I have to use this

 @IBAction func backAction(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }

How can I detect in the backAction function whether there is a superview or subview in the previous controller ?

All my subviews are opened like below

   @IBAction func Menu_Action(_ sender: Any) {

        let Popup = UIStoryboard(name: "Main", bundle: 
      nil).instantiateViewController(withIdentifier: "Menu_Subview")
      as! Menu_Subview

        self.addChildViewController(Popup)
        Popup.view.frame = self.view.frame
        self.view.addSubview(Popup.view)
        Popup.didMove(toParentViewController: self)
    }

Solution

  • what you open as addChildViewController - you should close by dismiss, because it is ViewController, and when you open as addSubview - close it by removeFromSuperview, because it is View in the another View. I suppose, it crashes, because there is no superview for your ViewController. If you have opened a lot of them, and you do not want to go back and rewrite it in a proper way, you can just check if your view has a superview, and according to boolean value you receive choose to dismiss or removeFromSuperview - if yourView.superview != nil