Search code examples
iosswiftuitabbarcontrolleruitabbarviewcontroller

TabBar hides in viewDidLoad but doesnt in gesture function


I tried calling tabBarController!.tabBar.hidden = true in viewDidLoad() and it hides the TabBar. However, I tried to set tap gesture and hide the bar on Tap. The parent viewController that has ScrollView inside it with subview (that is connected with IBOutlet as myView)

override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        myView.addGestureRecognizer(tap)
}

func handleTap(sender: UITapGestureRecognizer? = nil) {
   print("A") // logs successfully
           if TabBarHidden == false {
               print("B") // logs successfully

               //I tried:
               tabBarController?.tabBar.hidden = true

               // I also tried
               tabBarController?.tabBar.alpha = 0
               tabBarController?.tabBar.frame.origin.x += 50
               hidesBottomBarWhenPushed = true


           } else {
               ...
               TabBarHidden = false
           }
    }

hidden does work when I call it in viewDidLoad as I said, but not if I call in tap gesture function. What may be the problem? What am I missing?


Solution

  • this code totally works for me:

    class ViewController: UIViewController {
        var tabBarHidden: Bool = false {
            didSet {
                tabBarController?.tabBar.hidden = tabBarHidden
            }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized(_:)))
            view.addGestureRecognizer(tapGestureRecognizer)
        }
    
        func tapGestureRecognized(sender: UITapGestureRecognizer) {
            tabBarHidden = !tabBarHidden
        }
    }