Search code examples
iosswiftxcodeuitabbarcontrolleruitabbaritem

Variables don't update in UITabBarControllerDelegate


Here is what I'm trying to do:

Menu view Compressors view

When user clicks the 'Compressors' button, it shows a scroll view with details of compressors (or whatever). And to get back to menu, user clicks the 'More' tab bar item.

I've set up a variable first to store information if this is first time user taps the 'More' item.

class MoreVC: UIViewController {

var first : Bool = true

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.isHidden = true

}


open func hideEverything(_ bool : Bool)
{
    print(bool)
    if bool == true
    {
        // First time user taps More - nothing happens
        return
    }
    print("hideEverything()")

}

@IBAction func compressorsButton(_ sender: Any) {
    scrollView.isHidden = false
    print(first)
}

override func viewDidAppear(_ animated: Bool) {
    print("-> \(self.title!)")
    first = false
}

override func viewDidDisappear(_ animated: Bool) {
    scrollView.isHidden = true
    first = true
}

}

Then I have Tab bar delegate in different file:

class myTabBarController: UITabBarController, UITabBarControllerDelegate
{
override func viewDidLoad() {
    self.delegate = self
}



func tabBarController(_ tabBarController: UITabBarController, didSelect selectedViewController: UIViewController) {
    if selectedViewController is MoreVC
    {
        let more = MoreVC()
        print("more.first = \(more.first)")
        if more.first == false
        {
            more.scrollView.isHidden = true
        }
    }
}
}

So, when I tap compressors button, view shows up, when I switch tabs, view hides. But when scrollView is up and I press 'More', it doesn't trigger the more.scrollView.isHidden = true because it detects that first = true, which it is not! It's set to false (as it should be), but I still get true there. I think what I need to do is somehow update myTabBarController, but I have no idea how.

Please help, any hint on what is going on will be much appreciated! Also thanks for reading this far, I hope you understood my problem.

EDIT from future me:

This problem could have been resolved more naturally by using navigation controller through my app (which I ended up doing anyway). Joe's answer is correct, but if someone bumps into same problem as me, there is a second way.


Solution

  • Since you are updating the boolean on the newly created MoreVC, the existing one doesn't change at all.

    Instead of:

    if selectedViewController is MoreVC
    

    update it to:

    if let more = selectedViewController as? MoreVC
    

    then get rid of the line where you create a brand new MoreVC.