iosswiftaddsubviewsuperview

Swift multiple subviews and getting back to original TableView


I have created my own TabView the first tab is always the Home tab which contains a TableView . The other 3 Tabs Search, Menu and Inbox are subviews . I can go from

This is my code

From Home Controller to Menu Controller

@IBAction func MenuTabAction(_ sender: UIButton) {
    let Popup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MenuC") as! MenuC

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

}

From Menu Controller to Home Controller & Search Controller

   @IBAction func HomeTabAction(_ sender: UIButton) {
        if let viewWithTag = self.view.viewWithTag(100) {
            print("Tag 100")
            viewWithTag.removeFromSuperview()
        }

    }

       @IBAction func SearchTabAction(_ sender: UIButton) {

    let Popup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LocalSearchC") as! LocalSearchC
    Popup.view.frame = self.view.frame
    Popup.view.tag = 100
    self.view.addSubview(Popup.view)
    Popup.didMove(toParentViewController: self)
}

I am guessing that the remove superview only removes 1 superview at a time so if I go from Subview1 to subview2 then click on the HomeTab it brings me to subview1 instead of the original HomeTab . Is there a way to remove all superview/subviews when clicking the Home Tab ?

enter image description here


Solution

  • Each Tab got it's own view controller. Ideally, you should removeFromSuperview all controllers you're not showing.

    At your code, you only removeFromSuperView at HomeTabAction.

    Try to change it:

    if let viewWithTag = self.view.viewWithTag(100) {
        print("Tag 100")
        viewWithTag.removeFromSuperview()
    }
    

    to

    for v in self.view.subviews {
        if v.tag == 100 {
            v.removeFromSuperview()
        }
    }
    

    But please, keep in mind that each time a user press any tabs without returning to home (i.e: tapping many times between Menu and Search), it's look like you are just instantiating many controllers, without removing them.

    You should remove other Views every time a new one is instantiated. Would be wise to give a unique tag to each view controller and remove the hidden others after every change, not only when returning to Home. Or at least, check if the view controller with a given type already is instantiated before create a new one.