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

后端 未结 5 509
栀梦
栀梦 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:13

    This answer is a slight modification to Ariel answer which adds animation while user scrolls.

    extension ViewController:UIScrollViewDelegate{
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0{
                //scrolling down
                changeTabBar(hidden: true, animated: true)
            }
            else{
                //scrolling up
                changeTabBar(hidden: false, animated: true)
            }
        }
    
        func changeTabBar(hidden:Bool, animated: Bool){
            let tabBar = self.tabBarController?.tabBar
            let offset = (hidden ? UIScreen.main.bounds.size.height : UIScreen.main.bounds.size.height - (tabBar?.frame.size.height)! )
            if offset == tabBar?.frame.origin.y {return}
            print("changing origin y position")
            let duration:TimeInterval = (animated ? 0.5 : 0.0)
            UIView.animate(withDuration: duration,
                           animations: {tabBar!.frame.origin.y = offset},
                           completion:nil)
        }
    }
    

提交回复
热议问题