Search code examples
iosswiftswift4tabbaruitabcontroller

How do you really hide and show a tab bar when tapping on part of your view? (no buttons but any location of the screen)


override func viewDidLoad() {        

    let tap = UITapGestureRecognizer(target: self, action: #selector(touchHandled))
    view.addGestureRecognizer(tap)


}


@objc func touchHandled() {
    tabBarController?.hideTabBarAnimated(hide: true)
}


extension UITabBarController {
    func hideTabBarAnimated(hide:Bool) {
        UIView.animate(withDuration: 2, animations: {
            if hide {
                self.tabBar.transform = CGAffineTransform(translationX: 0, y: 100)
            } else {
                self.tabBar.transform = CGAffineTransform(translationX: 0, y: -100)
            }
        })
    }

}

I can only hide the tab bar but I can't make it show when you tap again. I tried to look for answers on stack overflow but the answers seems to only work if you're using a button or a storyboard.


Solution

  • Have a variable isTabBarHidden in class which stores if the tabBar has been animated to hide. (You could have used tabBar.isHidden, but that would complicate the logic a little bit when animate hiding and showing)

    class ViewController {
    
        var isTabBarHidden = false // set the default value as required
    
        override func viewDidLoad() {        
            super.viewDidLoad()
    
            let tap = UITapGestureRecognizer(target: self, action: #selector(touchHandled))
            view.addGestureRecognizer(tap)
        }
    
        @objc func touchHandled() {
            guard let tabBarControllerFound = tabBarController else {
                return
            }
            tabBarController?.hideTabBarAnimated(hide: !isTabBarHidden)
            isTabBarHidden = !isTabBarHidden
        }
    
    }