简体   繁体   中英

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)
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM