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

后端 未结 5 500
栀梦
栀梦 2020-12-08 17:36

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 anima

5条回答
  •  隐瞒了意图╮
    2020-12-08 18:19

    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
        })
    }
    

提交回复
热议问题