Search code examples
iosswiftuiscrollviewuitabbarcontrollershow-hide

iOS/Swift - Hide/Show UITabBarController when scrolling down/up


I'm quite new to iOS development. Right now i'm trying to hide my tabbar when I scroll down and when scrolling up the tabbar should appear. I would like to have this animated in the same way like the navigation bar. For the navigation bar I simply clicked the option in the Attributes Inspector. I saw some examples for the toolbar, but I cant adopt it the tabbar.

self.tabBarController?.tabBar.hidden = true just hides my tabbar, but its not animated like the navigation controller.


Solution

  • This is code that i'm actually using in a production app.

    It's in Swift and it also updates UITabBar.hidden var.

    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0{
            changeTabBar(hidden: true, animated: true)
        }
        else{
            changeTabBar(hidden: false, animated: true)
        }
    }
    

    You can also use the other callback method:

    func scrollViewDidScroll(scrollView: UIScrollView) {
        ...
    }
    

    but if you choose so, then you must handle multiple calls to the helper method that actually hides the tabBar.

    And then you need to add this method that animates the hide/show of the tabBar.

    func changeTabBar(hidden:Bool, animated: Bool){
        var tabBar = self.tabBarController?.tabBar
        if tabBar!.hidden == hidden{ return }
        let frame = tabBar?.frame
        let offset = (hidden ? (frame?.size.height)! : -(frame?.size.height)!)
        let duration:NSTimeInterval = (animated ? 0.5 : 0.0)
        tabBar?.hidden = false
        if frame != nil
        {
            UIView.animateWithDuration(duration,
                animations: {tabBar!.frame = CGRectOffset(frame!, 0, offset)},
                completion: {
                    println($0)
                    if $0 {tabBar?.hidden = hidden}
            })
        }
    }
    

    Update Swift 4

    func changeTabBar(hidden:Bool, animated: Bool){
        guard let tabBar = self.tabBarController?.tabBar else { return; }
        if tabBar.isHidden == hidden{ return }
        let frame = tabBar.frame
        let offset = hidden ? frame.size.height : -frame.size.height
        let duration:TimeInterval = (animated ? 0.5 : 0.0)
        tabBar.isHidden = false
    
        UIView.animate(withDuration: duration, animations: {
            tabBar.frame = frame.offsetBy(dx: 0, dy: offset)
        }, completion: { (true) in
            tabBar.isHidden = hidden
        })
    }